id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
19,876
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBind...
null
19,877
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBind...
Multiline input function.
19,878
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBind...
Multiline input function.
19,879
import re from typing import Set from prompt_toolkit import prompt from prompt_toolkit import PromptSession from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import WordCompleter from prompt_toolkit.history import InMemoryHistory from prompt_toolkit.key_binding import KeyBind...
Get filtered list of object variable names. :param keys: List of keys to include. If the first key is "not", the remaining keys will be removed from the class keys. :return: List of class keys.
19,880
from __future__ import annotations import base64 import binascii import contextlib import json import logging import secrets import subprocess import sys import time import uuid from functools import wraps from os import environ from os import getenv from pathlib import Path from typing import AsyncGenerator from typin...
Generate a random hex string Args: length (int, optional): Length of the hex string. Defaults to 17. Returns: str: Random hex string
19,881
from __future__ import annotations import base64 import binascii import contextlib import json import logging import secrets import subprocess import sys import time import uuid from functools import wraps from os import environ from os import getenv from pathlib import Path from typing import AsyncGenerator from typin...
Generate a random integer Args: min (int): Minimum value max (int): Maximum value Returns: int: Random integer
19,882
from __future__ import annotations import base64 import binascii import contextlib import json import logging import secrets import subprocess import sys import time import uuid from functools import wraps from os import environ from os import getenv from pathlib import Path from typing import AsyncGenerator from typin...
Logger decorator Args: is_timed (bool): Whether to include function running time in exit log Returns: _type_: decorated function
19,883
from __future__ import annotations import base64 import binascii import contextlib import json import logging import secrets import subprocess import sys import time import uuid from functools import wraps from os import environ from os import getenv from pathlib import Path from typing import AsyncGenerator from typin...
The solver function should take in a list of images in base64 and a dict of challenge details and return the index of the image that matches the challenge details Challenge details: game_type: str - Audio or Image instructions: str - Instructions for the captcha URLs: list[str] - URLs of the images or audio files
19,884
from __future__ import annotations import base64 import binascii import contextlib import json import logging import secrets import subprocess import sys import time import uuid from functools import wraps from os import environ from os import getenv from pathlib import Path from typing import AsyncGenerator from typin...
Looks for a config file in the following locations:
19,885
import datetime import sphinx_rtd_theme import doctest import karateclub import community def setup(app): def skip(app, what, name, obj, skip, options): members = [ '__init__', '__repr__', '__weakref__', '__dict__', '__module__', ] ...
null
19,886
import networkx as nx import matplotlib.pyplot as plt from matplotlib.axes import Axes from sklearn.decomposition import PCA from karateclub.node_embedding.structural import SINr The provided code snippet includes necessary dependencies for implementing the `embed_and_plot` function. Write a Python function `def embed...
Embed the graph using SINr and plot the 2D PCA projection. Args: graph (nx.Graph): The graph to embed. gamma (int): The modularity multi-resolution parameter. ax (Axes): The matplotlib axis to plot the graph on.
19,887
import math from functools import partial from typing import List, Callable import numpy as np import networkx as nx import scipy.sparse as sparse from karateclub.estimator import Estimator def _weighted_directed_degree(node: int, graph: nx.classes.graph.Graph) -> float: out = graph.degree(node, weight="weight") ...
Gets the function to calculate the graph node degree
19,888
import random from functools import partial from typing import List, Callable import numpy as np import networkx as nx def _check_value(value, name): try: _ = 1 / value except ZeroDivisionError: raise ValueError( f"The value of {name} is too small " f"or zero to be used in 1/{name}...
null
19,889
import random from functools import partial from typing import List, Callable import numpy as np import networkx as nx def _undirected(node, graph) -> List[tuple]: def _directed(node, graph) -> List[tuple]: def _get_edge_fn(graph) -> Callable: fn = _directed if nx.classes.function.is_directed(graph) else _undirect...
null
19,890
import random from functools import partial from typing import List, Callable import numpy as np import networkx as nx def _unweighted(edges: List[tuple]) -> np.ndarray: return np.ones(len(edges)) def _weighted(edges: List[tuple]) -> np.ndarray: weights = map(lambda edge: edge[-1]["weight"], edges) return n...
null
19,891
import argparse import torch import re import time import gradio as gr from moondream import detect_device, LATEST_REVISION from threading import Thread from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM def img_change(img): global latest_img latest_img = img
null
19,892
import argparse import torch import re import time import gradio as gr from moondream import detect_device, LATEST_REVISION from threading import Thread from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM def prompt_change(prompt): global latest_prompt latest_prompt = pro...
null
19,893
import argparse import torch import re import time import gradio as gr from moondream import detect_device, LATEST_REVISION from threading import Thread from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM def answer_question(img, prompt): def live_video(): while True: ...
null
19,894
import torch The provided code snippet includes necessary dependencies for implementing the `detect_device` function. Write a Python function `def detect_device()` to solve the following problem: Detects the appropriate device to run on, and return the device and dtype. Here is the function: def detect_device(): ...
Detects the appropriate device to run on, and return the device and dtype.
19,895
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCac...
null
19,896
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCac...
Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices ...
19,897
import math from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCac...
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
19,898
import argparse import torch import re import gradio as gr from moondream import detect_device, LATEST_REVISION from threading import Thread from transformers import TextIteratorStreamer, AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained(model_id, revision=LATEST_REVISION) moondream = AutoMo...
null
19,899
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple from . import vgg19_loss as vgg19 import gin.tf import numpy as np import tensorflow as tf def create_losses( loss_names: List[str], loss_weight_schedules: List[ tf.keras.optimizers.schedules.LearningRateSchedule] ) -> Dict[str, Tuple[Ca...
Creates the training loss functions and loss weight schedules.
19,900
from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple from . import vgg19_loss as vgg19 import gin.tf import numpy as np import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `aggregate_batch_losses` function. Write a Python function `def aggregate_batc...
Averages per batch losses into single dictionary for the whole epoch. As an example, if the batch_losses contained per batch losses: batch_losses = { {'l1': 0.2, 'ssim': 0.9}, {'l1': 0.3, 'ssim': 0.8}} The returned dictionary would look like: { 'l1': 0.25, 'ssim': 0.95 } Args: batch_losses: A list of dictionary objects...
19,901
from typing import Callable, Dict, Text from ..losses import losses import tensorflow as tf class TrainLossMetric(tf.keras.metrics.Metric): """Compute training loss for our example and prediction format. The purpose of this is to ensure that we always include a loss that is exactly like the training loss into the...
Create evaluation metrics. L1 and total training loss are added by default. The rest are the configured by the test_losses item via gin. Returns: A dictionary from metric name to Keras Metric object.
19,902
import os from typing import Sequence from . import model_lib from absl import app from absl import flags from absl import logging import gin.tf import tensorflow as tf tf.get_logger().setLevel('ERROR') The provided code snippet includes necessary dependencies for implementing the `_build_saved_model` function. Write ...
Builds a saved model based on the checkpoint directory.
19,903
from typing import Dict, Mapping, Text from absl import logging import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `_collect_tensors` function. Write a Python function `def _collect_tensors(tensors: tf.Tensor) -> tf.Tensor` to solve the following problem: Collect ten...
Collect tensors of the different replicas into a list.
19,904
from typing import Dict, Mapping, Text from absl import logging import tensorflow as tf def _distributed_eval_step(strategy: tf.distribute.Strategy, batch: Dict[Text, tf.Tensor], model: tf.keras.Model, metrics: Dict[Text, tf.keras.metrics.Metric], ...
Eval function that is strategy agnostic. Args: strategy: A Tensorflow distributed strategy. eval_base_folder: A path to where the summaries event files and checkpoints will be saved. model: A function that returns the model. metrics: A function that returns the metrics dictionary. datasets: A dict of tf.data.Dataset to...
19,905
import functools from typing import Any, Callable, Dict, Text, Tuple from absl import logging import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `get_strategy` function. Write a Python function `def get_strategy(mode) -> tf.distribute.Strategy` to solve the following...
Creates a distributed strategy.
19,906
from typing import Callable, Dict, List, Optional from absl import logging import gin.tf import tensorflow as tf def _create_from_sharded_tfrecord(batch_size, train_mode, file, augmentation_fns, ...
Creates the training dataset. The given tfrecord should contain data in a format produced by frame_interpolation/datasets/create_*_tfrecord.py Args: batch_size: The number of images to batch per example. file: (deprecated) A path to a sharded tfrecord in <tfrecord>@N format. Deprecated. Use 'files' instead. files: A li...
19,907
from typing import Callable, Dict, List import gin.tf import numpy as np import tensorflow as tf import tensorflow.math as tfm import tensorflow_addons.image as tfa_image _PI = 3.141592653589793 def _rotate_flow_vectors(flow: tf.Tensor, angle_rad: float) -> tf.Tensor: r"""Rotate the (u,v) vector of each pixel with an...
Rotates a flow by a multiple of 90 degrees. Args: flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees. k: The multiplier factor. Returns: A flow image of the same shape as the input rotated by multiples of 90 degrees.
19,908
from typing import Callable, Dict, List import gin.tf import numpy as np import tensorflow as tf import tensorflow.math as tfm import tensorflow_addons.image as tfa_image def _rotate_flow_vectors(flow: tf.Tensor, angle_rad: float) -> tf.Tensor: r"""Rotate the (u,v) vector of each pixel with angle in radians. Flow m...
Rotates a flow by a the provided angle in radians. Args: flow: The flow image shaped (H, W, 2) to rotate by multiples of 90 degrees. angle_rad: The angle to ratate the flow in radians. Returns: A flow image of the same shape as the input rotated by the provided angle in radians.
19,909
from typing import Callable, Dict, List import gin.tf import numpy as np import tensorflow as tf import tensorflow.math as tfm import tensorflow_addons.image as tfa_image The provided code snippet includes necessary dependencies for implementing the `flow_flip` function. Write a Python function `def flow_flip(flow: tf...
Flips a flow left to right. Args: flow: The flow image shaped (H, W, 2) to flip left to right. Returns: A flow image of the same shape as the input flipped left to right.
19,910
from typing import Callable, Dict, List import gin.tf import numpy as np import tensorflow as tf import tensorflow.math as tfm import tensorflow_addons.image as tfa_image def random_image_rot90(images: Dict[str, tf.Tensor]) -> Dict[str, tf.Tensor]: """Rotates a stack of images by a random multiples of 90 degrees. A...
Creates the data augmentation functions. Args: names: The list of augmentation function names. Returns: A dictionary of Callables to the augmentation functions, keyed by their names.
19,911
import io import os from typing import Any, List, Mapping, Optional from absl import logging import apache_beam as beam import numpy as np import PIL.Image import six from skimage import transform import tensorflow as tf def _resample_image(image: np.ndarray, resample_image_width: int, resample_imag...
Generates and serializes a tf.train.Example proto from an image triplet. Default setting creates a triplet Example with the input images unchanged. Images are processed in the order of center-crop then downscale. Args: triplet_dict: A dict of image key to filepath of the triplet images. scale_factor: An integer scale f...
19,912
from typing import List from . import options import tensorflow as tf def _relu(x: tf.Tensor) -> tf.Tensor: return tf.nn.leaky_relu(x, alpha=0.2)
null
19,913
from typing import List from . import options import tensorflow as tf def _relu(x: tf.Tensor) -> tf.Tensor: return tf.nn.leaky_relu(x, alpha=0.2) def _conv(filters: int, name: str): return tf.keras.layers.Conv2D( name=name, filters=filters, kernel_size=3, padding='same', activation=_r...
null
19,914
from typing import List from . import options from . import util import tensorflow as tf def _relu(x: tf.Tensor) -> tf.Tensor: return tf.nn.leaky_relu(x, alpha=0.2)
null
19,915
import os import shutil from typing import Generator, Iterable, List, Optional from . import interpolator as interpolator_lib import numpy as np import tensorflow as tf from tqdm import tqdm def read_image(filename: str) -> np.ndarray: """Reads an sRgb 8-bit image. Args: filename: The input filename to read. ...
Generates interpolated frames by repeatedly interpolating the midpoint. Loads the files on demand and uses the yield paradigm to return the frames to allow streamed processing of longer videos. Recursive interpolation is useful if the interpolator is trained to predict frames at midpoint only and is thus expected to pe...
19,916
import os import shutil from typing import Generator, Iterable, List, Optional from . import interpolator as interpolator_lib import numpy as np import tensorflow as tf from tqdm import tqdm def _recursive_generator( frame1: np.ndarray, frame2: np.ndarray, num_recursions: int, interpolator: interpolator_lib.Int...
Generates interpolated frames by repeatedly interpolating the midpoint. This is functionally equivalent to interpolate_recursively_from_files(), but expects the inputs frames in memory, instead of loading them on demand. Recursive interpolation is useful if the interpolator is trained to predict frames at midpoint only...
19,917
import os import shutil from typing import Generator, Iterable, List, Optional from . import interpolator as interpolator_lib import numpy as np import tensorflow as tf from tqdm import tqdm _CONFIG_FFMPEG_NAME_OR_PATH = 'ffmpeg' def get_ffmpeg_path() -> str: path = shutil.which(_CONFIG_FFMPEG_NAME_OR_PATH) if not...
null
19,918
import functools import os from typing import List, Sequence from . import interpolator as interpolator_lib from . import util from absl import app from absl import flags from absl import logging import apache_beam as beam import mediapy as media import natsort import numpy as np import tensorflow as tf from tqdm.auto ...
Writes PNG-images to a directory. If frames_dir doesn't exist, it is created. If frames_dir contains existing PNG-files, they are removed before saving the new ones. Args: frames: List of images to save. frames_dir: The output directory to save the images.
19,919
import functools import os from typing import List, Sequence from . import interpolator as interpolator_lib from . import util from absl import app from absl import flags from absl import logging import apache_beam as beam import mediapy as media import natsort import numpy as np import tensorflow as tf from tqdm.auto ...
null
19,920
import collections import os from typing import Any, Dict from . import util from absl import app from absl import flags from absl import logging import gin.tf from ..losses import losses import numpy as np import tensorflow as tf from ..training import data_lib The provided code snippet includes necessary dependencie...
Fetches the gin config.
19,921
import collections import os from typing import Any, Dict from . import util from absl import app from absl import flags from absl import logging import gin.tf from ..losses import losses import numpy as np import tensorflow as tf from ..training import data_lib _MODE = flags.DEFINE_enum('mode', 'gpu', ['cpu', 'gpu'], ...
Set the visible devices according to running mode.
19,922
import collections import os from typing import Any, Dict from . import util from absl import app from absl import flags from absl import logging import gin.tf from ..losses import losses import numpy as np import tensorflow as tf from ..training import data_lib _OUTPUT_FRAMES = flags.DEFINE_boolean( name='output_f...
Runs the eval loop for examples in the tfrecord. The evaluation is run for the first 'max_examples' number of examples, and resulting images are stored into the given output_dir. Any tensor that appears like an image is stored with its name -- this may include intermediate results, depending on what the model outputs. ...
19,923
from typing import List, Optional import numpy as np import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `_pad_to_align` function. Write a Python function `def _pad_to_align(x, align)` to solve the following problem: Pad image batch x so width and height divide by ali...
Pad image batch x so width and height divide by align. Args: x: Image batch to align. align: Number to align to. Returns: 1) An image padded so width % align == 0 and height % align == 0. 2) A bounding box that can be fed readily to tf.image.crop_to_bounding_box to undo the padding.
19,924
from typing import List, Optional import numpy as np import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `image_to_patches` function. Write a Python function `def image_to_patches(image: np.ndarray, block_shape: List[int]) -> np.ndarray` to solve the following problem...
Folds an image into patches and stacks along the batch dimension. Args: image: The input image of shape [B, H, W, C]. block_shape: The number of patches along the height and width to extract. Each patch is shaped (H/block_shape[0], W/block_shape[1]) Returns: The extracted patches shaped [num_blocks, patch_height, patch...
19,925
from typing import List, Optional import numpy as np import tensorflow as tf The provided code snippet includes necessary dependencies for implementing the `patches_to_image` function. Write a Python function `def patches_to_image(patches: np.ndarray, block_shape: List[int]) -> np.ndarray` to solve the following probl...
Unfolds patches (stacked along batch) into an image. Args: patches: The input patches, shaped [num_patches, patch_H, patch_W, C]. block_shape: The number of patches along the height and width to unfold. Each patch assumed to be shaped (H/block_shape[0], W/block_shape[1]). Returns: The unfolded image shaped [B, H, W, C]...
19,926
import os import os.path as osp import shutil import sys import warnings from setuptools import find_packages, setup import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) def readme(): with open('README.md', encoding='utf-8') as f: ...
null
19,927
import os import os.path as osp import shutil import sys import warnings from setuptools import find_packages, setup import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) version_file = 'mmtrack/version.py' def get_version(): with op...
null
19,928
import os import os.path as osp import shutil import sys import warnings from setuptools import find_packages, setup import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) def make_cuda_ext(name, module, sources, sources_cuda=[]): de...
null
19,929
import os import os.path as osp import shutil import sys import warnings from setuptools import find_packages, setup import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) The provided code snippet includes necessary dependencies for impl...
Parse the package dependencies listed in a requirements file but strips specific versioning information. Args: fname (str): path to requirements file with_version (bool, default=False): if True include version specs Returns: List[str]: list of requirements items CommandLine: python -c "import setup; print(setup.parse_r...
19,930
import os import os.path as osp import shutil import sys import warnings from setuptools import find_packages, setup import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) The provided code snippet includes necessary dependencies for impl...
Add extra files that are required to support MIM into the package. These files will be added by creating a symlink to the originals if the package is installed in `editable` mode (e.g. pip install -e .), or by copying from the originals otherwise.
19,931
import os import subprocess import sys import pytorch_sphinx_theme version_file = '../../mmtrack/version.py' def get_version(): with open(version_file, 'r') as f: exec(compile(f.read(), version_file, 'exec')) return locals()['__version__']
null
19,932
import os import subprocess import sys import pytorch_sphinx_theme def builder_inited_handler(app): subprocess.run(['./stat.py']) def setup(app): app.connect('builder-inited', builder_inited_handler)
null
19,935
version_info = parse_version_info(__version__) def parse_version_info(version_str): version_info = [] for x in version_str.split('.'): if x.isdigit(): version_info.append(int(x)) elif x.find('rc') != -1: patch_version = x.split('rc') version_info.append(int(p...
null
19,936
import os import numpy as np import torch import torch.distributed as dist from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, build_optimizer, get_dist_info) from mmcv.utils import build_from_cfg from mmdet.datasets import build_dataset from mmtrack.core import DistEvalHook,...
Initialize random seed. If the seed is not set, the seed will be automatically randomized, and then broadcast to all processes to prevent some potential bugs. Args: seed (int, Optional): The seed. Default to None. device (str): The device where the seed will be put on. Default to 'cuda'. Returns: int: Seed to be used.
19,937
import os import numpy as np import torch import torch.distributed as dist from mmcv.runner import (HOOKS, DistSamplerSeedHook, EpochBasedRunner, build_optimizer, get_dist_info) from mmcv.utils import build_from_cfg from mmdet.datasets import build_dataset from mmtrack.core import DistEvalHook,...
Train model entry function. Args: model (nn.Module): The model to be trained. dataset (:obj:`Dataset`): Train dataset. cfg (dict): The config dict for training. distributed (bool): Whether to use distributed training. Default: False. validate (bool): Whether to do evaluation. Default: False. timestamp (str | None): Loc...
19,938
import logging import os import tempfile import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.datasets.pipelines import Compose from mmtrack.models import build_model The provided code snippet includes nec...
Initialize a model from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. Default as None. cfg_options (dict, optional): Options to override some settings in the used config. Default to None. verbose_init_params (bool, optional): W...
19,939
import logging import os import tempfile import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.datasets.pipelines import Compose from mmtrack.models import build_model The provided code snippet includes nec...
Inference image(s) with the mot model. Args: model (nn.Module): The loaded mot model. img (str | ndarray): Either image name or loaded image. frame_id (int): frame id. Returns: dict[str : ndarray]: The tracking results.
19,940
import logging import os import tempfile import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.datasets.pipelines import Compose from mmtrack.models import build_model The provided code snippet includes nec...
Inference image with the single object tracker. Args: model (nn.Module): The loaded tracker. image (ndarray): Loaded images. init_bbox (ndarray): The target needs to be tracked. frame_id (int): frame id. Returns: dict[str : ndarray]: The tracking results.
19,941
import logging import os import tempfile import mmcv import numpy as np import torch from mmcv.ops import RoIPool from mmcv.parallel import collate, scatter from mmcv.runner import load_checkpoint from mmdet.datasets.pipelines import Compose from mmtrack.models import build_model The provided code snippet includes nec...
Inference image with the video object detector. Args: model (nn.Module): The loaded detector. image (ndarray): Loaded images. frame_id (int): Frame id. ref_img_sampler (dict): The configuration for sampling reference images. Only used under video detector of fgfa style. Defaults to dict(frame_stride=2, num_left_ref_img...
19,942
import torch from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `quad2bbox` function. Write a Python function `def quad2bbox(quad)` to solve the following problem: Convert quadrilateral to axis aligned box in [cx, cy, w, h] format. ...
Convert quadrilateral to axis aligned box in [cx, cy, w, h] format. Args: quad (Tensor): of shape (N, 8), (8, ), (N, 4) or (4, ). The coordinates are in [x1, y1, x2, y2, x3, y3, x4, y4] or [tl_x, tl_y, br_x, br_y] format. Returns: Tensor: in [cx, cy, w, h] format.
19,943
import torch from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `bbox_cxcywh_to_x1y1wh` function. Write a Python function `def bbox_cxcywh_to_x1y1wh(bbox)` to solve the following problem: Convert bbox coordinates from (cx, cy, w, h)...
Convert bbox coordinates from (cx, cy, w, h) to (x1, y1, w, h). Args: bbox (Tensor): Shape (n, 4) or (4, ) for bboxes. Returns: Tensor: Converted bboxes.
19,944
import torch from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `bbox_xyxy_to_x1y1wh` function. Write a Python function `def bbox_xyxy_to_x1y1wh(bbox)` to solve the following problem: Convert bbox coordinates from (x1, y1, x2, y2) t...
Convert bbox coordinates from (x1, y1, x2, y2) to (x1, y1, w, h). Args: bbox (Tensor): Shape (n, 4) or (4, ) for bboxes. Returns: Tensor: Converted bboxes.
19,945
import torch from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `bbox_xyxy_to_cxcyah` function. Write a Python function `def bbox_xyxy_to_cxcyah(bboxes)` to solve the following problem: Convert bbox coordinates from (x1, y1, x2, y2)...
Convert bbox coordinates from (x1, y1, x2, y2) to (cx, cy, ratio, h). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes.
19,946
import torch from mmdet.core.bbox.transforms import bbox_xyxy_to_cxcywh The provided code snippet includes necessary dependencies for implementing the `bbox_cxcyah_to_xyxy` function. Write a Python function `def bbox_cxcyah_to_xyxy(bboxes)` to solve the following problem: Convert bbox coordinates from (cx, cy, ratio, ...
Convert bbox coordinates from (cx, cy, ratio, h) to (x1, y1, x2, y2). Args: bbox (Tensor): Shape (n, 4) for bboxes. Returns: Tensor: Converted bboxes.
19,947
def calculate_region_overlap(*args, **kwargs): if calculate_overlap is None: raise ImportError( 'Please run' 'pip install git+https://github.com/votchallenge/toolkit.git' 'to manually install vot-toolkit') return calculate_overlap(*args, **kwargs)
null
19,948
import math import numpy as np from mmcv.runner.hooks import HOOKS, LrUpdaterHook The provided code snippet includes necessary dependencies for implementing the `step_lr_interval` function. Write a Python function `def step_lr_interval(start_lr_factor, end_lr_factor, start_epoch, end_epoch)` to solve the following pro...
Exponentially varying learning rate. Generator learning rate factor exponentially varying from `start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch` epochs. Args: start_lr_factor (float): Start learning rate factor. end_lr_factor (float): End learning rate factor. start_epoch (int): Start epoch. end_e...
19,949
import math import numpy as np from mmcv.runner.hooks import HOOKS, LrUpdaterHook The provided code snippet includes necessary dependencies for implementing the `log_lr_interval` function. Write a Python function `def log_lr_interval(start_lr_factor, end_lr_factor, start_epoch, end_epoch)` to solve the following probl...
Logarithmically varying learning rate. Generator learning rate factor logarithmically varying from `start_lr_factor` to `end_lr_factor` in total `end_epoch - start_epoch` epochs. Args: start_lr_factor (float): Start learning rate factor. end_lr_factor (float): End learning rate factor. start_epoch (int): Start epoch. e...
19,950
import numpy as np try: import vot from vot.analysis import is_special from vot.region import Polygon, Rectangle, Special from vot.region import calculate_overlaps as calculate_region_overlaps except ImportError: vot = None def count_failures(trajectory): """count the number of failed frame in a...
Calculate accuracy and robustness over all tracking sequences. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray have two cases: - bbox: denotes the normal tracking box in [x1, y1, w, h] ...
19,951
import numpy as np try: import vot from vot.analysis import is_special from vot.region import Polygon, Rectangle, Special from vot.region import calculate_overlaps as calculate_region_overlaps except ImportError: vot = None def trajectory2region(trajectory): """Convert bbox trajectory to Rectang...
Calculate EAO socre over all tracking sequences. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray have two cases: - bbox: denotes the normal tracking box in [x1, y1, w, h] format. - spec...
19,952
import copy import itertools import json import sys import time from collections import defaultdict import numpy as np from pycocotools import mask as maskUtils def _isArrayLike(obj): return hasattr(obj, '__iter__') and hasattr(obj, '__len__')
null
19,953
import time from multiprocessing import Pool import motmetrics as mm import numpy as np import pandas as pd from mmcv.utils import print_log from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps from motmetrics.lap import linear_sum_assignment from motmetrics.math_util import quiet_divide from mmtrack.core.trac...
Evaluation CLEAR MOT metrics. Args: results (list[list[list[ndarray]]]): The first list indicates videos, The second list indicates images. The third list indicates categories. The ndarray indicates the tracking results. annotations (list[list[dict]]): The first list indicates videos, The second list indicates images. ...
19,954
import contextlib import io from collections import OrderedDict from mmcv.utils import print_log from .ytvis import YTVIS from .ytviseval import YTVISeval class YTVIS: def __init__(self, annotation_file=None): """Constructor of Microsoft COCO helper class for reading and visualizing annotations. ...
Evaluation on VIS metrics. Args: test_results (dict(list[dict])): Testing results of the VIS dataset. vis_anns (dict(list[dict])): The annotation in the format of YouTube-VIS. logger (logging.Logger | str | None): Logger used for printing related information during evaluation. Default: None. Returns: dict[str, float]: ...
19,955
import numpy as np from mmdet.core.evaluation.bbox_overlaps import bbox_overlaps def success_overlap(gt_bboxes, pred_bboxes, iou_th, video_length): """Evaluation based on iou. Args: gt_bboxes (ndarray): of shape (video_length, 4) in [tl_x, tl_y, br_x, br_y] format. pred_bboxes (ndarr...
Evaluation in OPE protocol. Args: results (list[list[ndarray]]): The first list contains the tracking results of each video. The second list contains the tracking results of each frame in one video. The ndarray denotes the tracking box in [tl_x, tl_y, br_x, br_y] format. annotations (list[ndarray]): The list contains t...
19,956
import torch The provided code snippet includes necessary dependencies for implementing the `flow_warp_feats` function. Write a Python function `def flow_warp_feats(x, flow)` to solve the following problem: Use flow to warp feature map. Args: x (Tensor): of shape (N, C, H_x, W_x). flow (Tensor): of shape (N, C, H_f, W...
Use flow to warp feature map. Args: x (Tensor): of shape (N, C, H_x, W_x). flow (Tensor): of shape (N, C, H_f, W_f). Returns: Tensor: The warpped feature map with shape (N, C, H_x, W_x).
19,957
import mmcv import numpy as np import torch from mmdet.core import bbox2result def _imrenormalize(img, img_norm_cfg, new_img_norm_cfg): """Re-normalize the image.""" img_norm_cfg = img_norm_cfg.copy() new_img_norm_cfg = new_img_norm_cfg.copy() for k, v in img_norm_cfg.items(): if (k == 'mean' or...
Re-normalize the image. Args: img (Tensor | ndarray): Input image. If the input is a Tensor, the shape is (1, C, H, W). If the input is a ndarray, the shape is (H, W, C). img_norm_cfg (dict): Original configuration for the normalization. new_img_norm_cfg (dict): New configuration for the normalization. Returns: Tensor ...
19,958
import mmcv import numpy as np import torch from mmdet.core import bbox2result The provided code snippet includes necessary dependencies for implementing the `outs2results` function. Write a Python function `def outs2results(bboxes=None, labels=None, masks=None, ids=N...
Convert tracking/detection results to a list of numpy arrays. Args: bboxes (torch.Tensor | np.ndarray): shape (n, 5) labels (torch.Tensor | np.ndarray): shape (n, ) masks (torch.Tensor | np.ndarray): shape (n, h, w) ids (torch.Tensor | np.ndarray): shape (n, ) num_classes (int): class number, not including background c...
19,959
import mmcv import numpy as np import torch from mmdet.core import bbox2result The provided code snippet includes necessary dependencies for implementing the `results2outs` function. Write a Python function `def results2outs(bbox_results=None, mask_results=None, mask_shape=None, ...
Restore the results (list of results of each category) into the results of the model forward. Args: bbox_results (list[np.ndarray]): Each list denotes bboxes of one category. mask_results (list[list[np.ndarray]]): Each outer list denotes masks of one category. Each inner list denotes one mask belonging to the category....
19,960
import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `depthwise_correlation` function. Write a Python function `def depthwise_correlation(x, kernel)` to solve the following problem: Depthwise cross correlation. This function is proposed in `SiamRPN++ <https://a...
Depthwise cross correlation. This function is proposed in `SiamRPN++ <https://arxiv.org/abs/1812.11703>`_. Args: x (Tensor): of shape (N, C, H_x, W_x). kernel (Tensor): of shape (N, C, H_k, W_k). Returns: Tensor: of shape (N, C, H_o, W_o). H_o = H_x - H_k + 1. So does W_o.
19,961
import torch import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `embed_similarity` function. Write a Python function `def embed_similarity(key_embeds, ref_embeds, method='dot_product', temperature...
Calculate feature similarity from embeddings. Args: key_embeds (Tensor): Shape (N1, C). ref_embeds (Tensor): Shape (N2, C). method (str, optional): Method to calculate the similarity, options are 'dot_product' and 'cosine'. Defaults to 'dot_product'. temperature (int, optional): Softmax temperature. Defaults to -1. Ret...
19,962
import numpy as np def _interpolate_track(track, track_id, max_num_frames=20): """Interpolate a track linearly to make the track more complete. Args: track (ndarray): With shape (N, 7). Each row denotes (frame_id, track_id, x1, y1, x2, y2, score). max_num_frames (int, optional): The ...
Interpolate tracks linearly to make tracks more complete. This function is proposed in "ByteTrack: Multi-Object Tracking by Associating Every Detection Box." `ByteTrack<https://arxiv.org/abs/2110.06864>`_. Args: tracks (ndarray): With shape (N, 7). Each row denotes (frame_id, track_id, x1, y1, x2, y2, score). min_num_f...
19,963
import cv2 import numpy as np The provided code snippet includes necessary dependencies for implementing the `crop_image` function. Write a Python function `def crop_image(image, crop_region, crop_size, padding=(0, 0, 0))` to solve the following problem: Crop image based on `crop_region` and `crop_size`. Args: image (...
Crop image based on `crop_region` and `crop_size`. Args: image (ndarray): of shape (H, W, 3). crop_region (ndarray): of shape (4, ) in [x1, y1, x2, y2] format. crop_size (int): Crop size. padding (tuple | ndarray): of shape (3, ) denoting the padding values. Returns: ndarray: Cropped image of shape (crop_size, crop_siz...
19,964
import os.path as osp import random import cv2 import matplotlib import matplotlib.pyplot as plt import mmcv import numpy as np import seaborn as sns from matplotlib.patches import Rectangle from mmcv.utils import mkdir_or_exist def _cv2_show_tracks(img, bboxes, labels, ...
Show the tracks on the input image.
19,965
import os.path as osp import random import cv2 import matplotlib import matplotlib.pyplot as plt import mmcv import numpy as np import seaborn as sns from matplotlib.patches import Rectangle from mmcv.utils import mkdir_or_exist def _cv2_show_wrong_tracks(img, bboxes, ...
Show the wrong tracks on the input image. Args: backend (str, optional): Backend of visualization. Defaults to 'cv2'.
19,966
import collections.abc as container_abcs import multiprocessing as mp import os import platform import warnings from itertools import repeat import cv2 def setup_multi_processes(cfg): # set multi-process start method as `fork` to speed up the training if platform.system() != 'Windows': mp_start_method ...
null
19,967
import collections.abc as container_abcs import multiprocessing as mp import os import platform import warnings from itertools import repeat import cv2 def ntuple(n): def parse(x): if isinstance(x, container_abcs.Iterable): return x return tuple(repeat(x, n)) return parse
null
19,968
import random import warnings from functools import partial import numpy as np import torch from mmcv.parallel import collate from mmcv.runner import get_dist_info from mmcv.utils import TORCH_VERSION, digit_version from mmdet.datasets.samplers import (DistributedGroupSampler, Distr...
Build PyTorch DataLoader. In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs. Args: dataset (Dataset): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (int): Ho...
19,969
import numpy as np import torch import torch.nn as nn from mmdet.models import LOSSES, weighted_loss The provided code snippet includes necessary dependencies for implementing the `l2_loss` function. Write a Python function `def l2_loss(pred, target)` to solve the following problem: L2 loss. Args: pred (torch.Tensor):...
L2 loss. Args: pred (torch.Tensor): The prediction. target (torch.Tensor): The learning target of the prediction. Returns: torch.Tensor: Calculated loss
19,970
from mmcv.cnn import MODELS as MMCV_MODELS from mmcv.utils import Registry TRACKERS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_tracker` function. Write a Python function `def build_tracker(cfg)` to solve the following problem: Build tracker. Here is the function: d...
Build tracker.
19,971
from mmcv.cnn import MODELS as MMCV_MODELS from mmcv.utils import Registry MOTION = MODELS The provided code snippet includes necessary dependencies for implementing the `build_motion` function. Write a Python function `def build_motion(cfg)` to solve the following problem: Build motion model. Here is the function: ...
Build motion model.
19,972
from mmcv.cnn import MODELS as MMCV_MODELS from mmcv.utils import Registry REID = MODELS The provided code snippet includes necessary dependencies for implementing the `build_reid` function. Write a Python function `def build_reid(cfg)` to solve the following problem: Build reid model. Here is the function: def buil...
Build reid model.
19,973
from mmcv.cnn import MODELS as MMCV_MODELS from mmcv.utils import Registry AGGREGATORS = MODELS The provided code snippet includes necessary dependencies for implementing the `build_aggregator` function. Write a Python function `def build_aggregator(cfg)` to solve the following problem: Build aggregator model. Here i...
Build aggregator model.
19,974
from mmcv.cnn import MODELS as MMCV_MODELS from mmcv.utils import Registry MODELS = Registry('models', parent=MMCV_MODELS) The provided code snippet includes necessary dependencies for implementing the `build_model` function. Write a Python function `def build_model(cfg, train_cfg=None, test_cfg=None)` to solve the fo...
Build model.
19,975
from mmcv.utils import collect_env as collect_base_env from mmcv.utils import get_git_hash import mmtrack The provided code snippet includes necessary dependencies for implementing the `collect_env` function. Write a Python function `def collect_env()` to solve the following problem: Collect the information of the run...
Collect the information of the running environments.
19,976
import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel dp_factory = {'cuda': MMDataParallel, 'cpu': MMDataParallel} The provided code snippet includes necessary dependencies for implementing the `build_dp` function. Write a Python function `def build_dp(model, device='cuda', dim=0, *args, **k...
build DataParallel module by device type. if device is cuda, return a MMDataParallel model; if device is npu, return a NPUDataParallel model. Args: model (:class:`nn.Module`): model to be parallelized. device (str): device type, cuda, cpu or npu. Defaults to cuda. dim (int): Dimension used to scatter the data. Defaults...
19,977
import torch from mmcv.parallel import MMDataParallel, MMDistributedDataParallel ddp_factory = {'cuda': MMDistributedDataParallel} The provided code snippet includes necessary dependencies for implementing the `build_ddp` function. Write a Python function `def build_ddp(model, device='cuda', *args, **kwargs)` to solve...
Build DistributedDataParallel module by device type. If device is cuda, return a MMDistributedDataParallel model; if device is npu, return a NPUDistributedDataParallel model. Args: model (:class:`nn.Module`): module to be parallelized. device (str): device type, npu or cuda. Returns: :class:`nn.Module`: the module to b...