id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
150,792 | import argparse
import json
import logging
import os
import time
import torch
from . import decoder, logger, network, show, visualizer, __version__
from .predictor import Predictor
from .stream import Stream
LOG = logging.getLogger(__name__)
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
... | null |
150,793 | import logging
from .animation_frame import AnimationFrame
from .canvas import Canvas
from .painters import KeypointPainter
class AnimationFrame:
def __init__(self, *,
fig_width=8.0,
fig_init_args=None,
video_output=None,
second_v... | null |
150,794 | import logging
from .animation_frame import AnimationFrame
from .canvas import Canvas
from .painters import KeypointPainter
class AnimationFrame:
def __init__(self, *,
fig_width=8.0,
fig_init_args=None,
video_output=None,
second_v... | null |
150,795 | import logging
import numpy as np
try:
import matplotlib
import matplotlib.animation
import matplotlib.collections
import matplotlib.patches
except ImportError:
matplotlib = None
def margins(ax, vector_field, *,
confidence_field=None, step=1, threshold=0.5,
xy_scale=1.0, uv_... | null |
150,796 | import logging
import numpy as np
def quiver(ax, vector_field, *,
confidence_field=None, step=1, threshold=0.5,
xy_scale=1.0, uv_is_offset=False,
reg_uncertainty=None, **kwargs):
x, y, u, v, c, r = [], [], [], [], [], []
for j in range(0, vector_field.shape[1], step):
fo... | null |
150,797 | import logging
import numpy as np
def boxes_wh(ax, w_field, h_field, *, confidence_field=None, regression_field=None,
xy_scale=1.0, step=1, threshold=0.5,
regression_field_is_offset=False,
cmap='viridis_r', clim=(0.5, 1.0), linewidth=1, **kwargs):
def boxes(ax, sigma_field, **kwa... | null |
150,798 | import logging
import numpy as np
try:
import matplotlib
import matplotlib.animation
import matplotlib.collections
import matplotlib.patches
except ImportError:
matplotlib = None
def circles(ax, radius_field, *, confidence_field=None, regression_field=None,
xy_scale=1.0, step=1, thresho... | null |
150,799 | from contextlib import contextmanager
import logging
import os
import numpy as np
def white_screen(ax, alpha=0.9):
ax.add_patch(
plt.Rectangle((0, 0), 1, 1, transform=ax.transAxes, alpha=alpha,
facecolor='white')
) | null |
150,800 | import argparse
import torch
import openpifpaf
try:
import thop
except ImportError:
thop = None
def count(model):
if thop is None:
raise RuntimeError('thop not found. Run "pip3 install thop".')
dummy_input = torch.randn(1, 3, 641, 641)
gmacs, params = thop.profile(model, inputs=(dummy_input... | null |
150,801 | import argparse
import glob
import json
import logging
import os
import torch
from . import decoder, logger, network, show, visualizer, __version__
from .predictor import Predictor
LOG = logging.getLogger(__name__)
class Predictor:
"""Convenience class to predict from various inputs with a common configuration."""... | null |
150,802 | import argparse
import glob
import json
import logging
import os
import torch
from . import decoder, logger, network, show, visualizer, __version__
from .predictor import Predictor
The provided code snippet includes necessary dependencies for implementing the `out_name` function. Write a Python function `def out_name(... | Determine an output name from args, input name and extension. arg can be: - none: return none (e.g. show image but don't store it) - True: activate this output and determine a default name - string: - not a directory: use this as the output file name - is a directory: use directory name and input name to form an output |
150,803 | import argparse
import logging
import PIL
import torch
import openpifpaf
from .export_onnx import image_size_warning
try:
import coremltools
except ImportError:
coremltools = None
def image_size_warning(basenet_stride, input_w, input_h):
def apply(model, outfile, *, input_w=129, input_h=97, minimum_deployment... | null |
150,804 | import argparse
import logging
import PIL
import torch
import openpifpaf
from .export_onnx import image_size_warning
try:
import coremltools
except ImportError:
coremltools = None
def print_preprocessing_spec(out_name):
spec = coremltools.models.utils.load_spec(out_name)
print(spec.neuralNetwork.prepro... | null |
150,805 | import logging
from .annrescaler import AnnRescaler
from .caf import Caf
from .cif import Cif
class AnnRescaler():
suppress_selfhidden = True
suppress_invisible = False
suppress_collision = False
def __init__(self, stride, pose=None):
self.stride = stride
self.pose = pose
self... | null |
150,806 | import logging
from .annrescaler import AnnRescaler
from .caf import Caf
from .cif import Cif
class AnnRescaler():
suppress_selfhidden = True
suppress_invisible = False
suppress_collision = False
def __init__(self, stride, pose=None):
self.stride = stride
self.pose = pose
self... | null |
150,807 | import logging
import json
import zipfile
import numpy as np
from .base import Base
def new_prepare(instance):
instance._original_prepare() # pylint: disable=protected-access
for gts in instance._gts.values(): # pylint: disable=protected-access
for gt in gts:
if 'area' not... | null |
150,808 | import argparse
from collections import defaultdict
import datetime
import json
import logging
import os
from pprint import pprint
import numpy as np
import pysparkling
from . import logger, metric, show, __version__
LOG = logging.getLogger(__name__)
def optionally_shaded(ax, x, y, *, color, label, **kwargs):
epoc... | null |
150,809 | import argparse
from collections import defaultdict
import datetime
import json
import logging
import os
from pprint import pprint
import numpy as np
import pysparkling
from . import logger, metric, show, __version__
The provided code snippet includes necessary dependencies for implementing the `fractional_epoch` func... | Given a data row, compute the fractional epoch taking batch into account. Example: Epoch 1 at batch 30 out of 100 batches per epoch would return epoch 1.3. |
150,810 | import argparse
from collections import namedtuple
from dataclasses import dataclass
import datetime
import json
import logging
import os
import subprocess
from typing import List
import pysparkling
from . import __version__
LOG = logging.getLogger(__name__)
DEFAULT_CHECKPOINTS = [
'resnet50',
'shufflenetv2k16'... | null |
150,811 | import argparse
from collections import defaultdict
import glob
import json
import logging
import os
import sys
import time
import typing as t
import PIL.Image
import torch
from . import datasets, decoder, logger, network, show, visualizer, __version__
from .configurable import Configurable
from .predictor import Predi... | null |
150,812 | import argparse
from collections import defaultdict
import glob
import json
import logging
import os
import sys
import time
import typing as t
import PIL.Image
import torch
from . import datasets, decoder, logger, network, show, visualizer, __version__
from .configurable import Configurable
from .predictor import Predi... | null |
150,813 | import copy
import logging
import math
import numpy as np
import PIL
import torch
from .pad import CenterPad
from .preprocess import Preprocess
from .. import utils
try:
import scipy
except ImportError:
scipy = None
LOG = logging.getLogger(__name__)
def rotate(image, anns, meta, angle):
meta = copy.deepcop... | null |
150,814 | import copy
import logging
import math
import numpy as np
import PIL
import torch
from .pad import CenterPad
from .preprocess import Preprocess
from .. import utils
LOG = logging.getLogger(__name__)
class CenterPad(Preprocess):
"""Pad to a square of given size."""
def __init__(self, target_size: t.Union[int, ... | null |
150,815 | import copy
import logging
import warnings
import numpy as np
import PIL.Image
import torch
from .preprocess import Preprocess
try:
import cv2
except ImportError:
cv2 = None
try:
import scipy.ndimage
except ImportError:
scipy = None # pylint: disable=invalid-name
LOG = logging.getLogger(__name__)
The ... | target_w and target_h as integers Internally, resample in Pillow are aliases: PIL.Image.Resampling.BILINEAR = 2 PIL.Image.Resampling.BICUBIC = 3 |
150,816 | import logging
import torch
def cli(parser):
group = parser.add_argument_group('optimizer')
group.add_argument('--momentum', type=float, default=0.9,
help='SGD momentum, beta1 in Adam')
group.add_argument('--beta2', type=float, default=0.999,
help='beta2 for Ad... | null |
150,817 | import logging
import torch
LOG = logging.getLogger(__name__)
def factory_optimizer(args, parameters):
if args.amsgrad:
args.adam = True
if args.adam:
LOG.info('Adam optimizer')
optimizer = torch.optim.Adam(
(p for p in parameters if p.requires_grad),
lr=args.lr... | null |
150,818 | import logging
import torch
LOG = logging.getLogger(__name__)
class LearningRateLambda():
def __init__(self, decay_schedule, *,
decay_factor=0.1,
decay_epochs=1.0,
warm_up_start_epoch=0,
warm_up_epochs=2.0,
warm_up_factor=0.01,
... | null |
150,819 | import torch
def collate_images_anns_meta(batch):
anns = [b[-2] for b in batch]
metas = [b[-1] for b in batch]
if len(batch[0]) == 4:
# raw images are also in this batch
images = [b[0] for b in batch]
processed_images = torch.utils.data.dataloader.default_collate([b[1] for b in bat... | null |
150,820 | import torch
def collate_images_targets_meta(batch):
images = torch.utils.data.dataloader.default_collate([b[0] for b in batch])
targets = torch.utils.data.dataloader.default_collate([b[1] for b in batch])
metas = [b[2] for b in batch]
return images, targets, metas | null |
150,821 | import torch
def collate_tracking_images_targets_meta(batch):
images = torch.utils.data.dataloader.default_collate([
im for group in batch for im in group[0]])
targets = torch.utils.data.dataloader.default_collate([b[1] for b in batch])
metas = [b[2] for b in batch]
return images, targets, me... | null |
150,822 | from .module import DataModule
from .multiloader import MultiLoader
from .multimodule import MultiDataModule
DATAMODULES = {}
class MultiDataModule(DataModule):
"""Emulates a single DataModule but contains multiple DataModules."""
def __init__(self, datamodules: List[DataModule]):
self.datamodules = d... | null |
150,823 | from .module import DataModule
from .multiloader import MultiLoader
from .multimodule import MultiDataModule
DATAMODULES = {}
class DataModule:
def set_loader_workers(cls, value):
def loader_workers(self):
def cli(cls, parser: argparse.ArgumentParser):
def configure(cls, args: argparse.Namespace):
... | null |
150,824 | from .module import DataModule
from .multiloader import MultiLoader
from .multimodule import MultiDataModule
DATAMODULES = {}
class DataModule:
"""
Base class to extend OpenPifPaf with custom data.
This class gives you all the handles to train OpenPifPaf on a new dataset.
Create a new class that inher... | null |
150,825 | from . import heads, tracking_heads
from .nets import model_defaults
from .tracking_base import TrackingBase
from ..signal import Signal
MODEL_MIGRATION = set()
MODEL_MIGRATION.add(fix_feature_cache)
MODEL_MIGRATION.add(subscribe_cache_reset)
MODEL_MIGRATION.add(tcaf_shared_preprocessing)
def model_defaults(net_cpu):
... | null |
150,826 | from . import heads, tracking_heads
from .nets import model_defaults
from .tracking_base import TrackingBase
from ..signal import Signal
class TrackingBase(BaseNetwork):
cached_items = [0, -1]
def __init__(self, single_image_backbone):
super().__init__(
't' + single_image_backbone.name,
... | null |
150,827 | from . import heads, tracking_heads
from .nets import model_defaults
from .tracking_base import TrackingBase
from ..signal import Signal
class TrackingBase(BaseNetwork):
cached_items = [0, -1]
def __init__(self, single_image_backbone):
super().__init__(
't' + single_image_backbone.name,
... | null |
150,828 | from . import heads, tracking_heads
from .nets import model_defaults
from .tracking_base import TrackingBase
from ..signal import Signal
def tcaf_shared_preprocessing(model):
for m in model.modules():
if not isinstance(m, tracking_heads.Tcaf):
continue
# pylint: disable=protected-acces... | null |
150,829 | import argparse
import logging
import os
from typing import Callable, Dict, Set, Tuple, Type
import warnings
import torch
import torchvision
from .. import headmeta
from ..configurable import Configurable
from . import basenetworks, heads, model_migration, nets, tracking_heads
from .tracking_base import TrackingBase
if... | null |
150,830 | import argparse
import functools
import logging
import math
import typing as t
import torch
from .. import headmeta
def index_field_torch(shape: t.Tuple[int, int],
device: torch.device,
unsqueeze: t.Tuple[int, int] = (0, 0)) -> torch.Tensor:
assert len(shape) == 2
xy... | null |
150,831 | import argparse
import logging
import socket
import sys
import torch
def cli(parser: argparse.ArgumentParser):
group = parser.add_argument_group('logger')
group.add_argument('-q', '--quiet', default=False, action='store_true',
help='only show warning messages or above')
group.add_arg... | null |
150,832 | import argparse
import logging
import socket
import sys
import torch
LOG = logging.getLogger(__name__)
def versions():
return {name: getattr(m, '__version__', 'unknown')
for name, m in REGISTERED.items()
if not name.startswith('openpifpaf.plugins.')}
def train_configure(args):
if torch... | null |
150,833 | from collections import defaultdict
from typing import List, Tuple
def skeleton_mapping(kps_mapping):
"""Map the subset of keypoints from 0 to n-1"""
map_sk = defaultdict(lambda: 100) # map to 100 the keypoints not used
for i, j in zip(kps_mapping, range(len(kps_mapping))):
map_sk[i] = j
return... | Transform the original apollo skeleton of 66 joints into a skeleton from 1 to n |
150,834 | import glob
import os
import time
from shutil import copyfile
import json
import argparse
import numpy as np
from PIL import Image
from .constants import CAR_KEYPOINTS_24, CAR_SKELETON_24, \
CAR_KEYPOINTS_66, CAR_SKELETON_66, KPS_MAPPING
from .transforms import skeleton_mapping
def cli():
parser = argparse.Arg... | null |
150,835 | import glob
import os
import time
from shutil import copyfile
import json
import argparse
import numpy as np
from PIL import Image
from .constants import CAR_KEYPOINTS_24, CAR_SKELETON_24, \
CAR_KEYPOINTS_66, CAR_SKELETON_66, KPS_MAPPING
from .transforms import skeleton_mapping
def histogram(cnt_kps):
bins = n... | null |
150,836 | import os
import numpy as np
import openpifpaf
from .transforms import transform_skeleton
CAR_KEYPOINTS_24 = [
'front_up_right', # 1
'front_up_left', # 2
'front_light_right', # 3
'front_light_left', # 4
'front_low_right', # 5
'front_low_left', # 6
'central_up_l... | null |
150,837 | import os
import numpy as np
import openpifpaf
from .transforms import transform_skeleton
assert not np.any(CAR_POSE_66 == np.nan)
def draw_ann(ann, *, keypoint_painter, filename=None, margin=0.5, aspect=None, **kwargs):
from openpifpaf import show # pylint: disable=import-outside-toplevel
bbox = ann.bbox()
... | null |
150,838 | import os
import numpy as np
import openpifpaf
from .transforms import transform_skeleton
assert not np.any(CAR_POSE_66 == np.nan)
def plot3d_red(ax_2D, p3d, skeleton):
skeleton = [(bone[0] - 1, bone[1] - 1) for bone in skeleton]
rot_p90_x = np.array([[1, 0, 0], [0, 0, 1], [0, 1, 0]])
p3d = p3d @ rot_p90_... | null |
150,839 | import os
import numpy as np
import openpifpaf
from .transforms import transform_skeleton
CAR_KEYPOINTS_24 = [
'front_up_right', # 1
'front_up_left', # 2
'front_light_right', # 3
'front_light_left', # 4
'front_low_right', # 5
'front_low_left', # 6
'central_up_l... | null |
150,840 | import logging
import numpy as np
from openpifpaf.metric.base import Base
from openpifpaf.annotation import Annotation
try:
import scipy
except ImportError:
scipy = None
def hungarian_matching(gts, predictions, thresh=0.5):
cost = np.zeros((len(gts), len(predictions)))
for i, (dg, vg) in enumerate(gts... | null |
150,841 | import logging
import numpy as np
from openpifpaf.metric.base import Base
from openpifpaf.annotation import Annotation
The provided code snippet includes necessary dependencies for implementing the `average` function. Write a Python function `def average(my_list, *, empty_value=0.0)` to solve the following problem:
ca... | calculate mean of a list |
150,842 | import os
import glob
import argparse
import time
import json
from collections import defaultdict
from shutil import copyfile
import xml.etree.ElementTree as ET
import numpy as np
from PIL import Image
from openpifpaf.plugins.animalpose.constants import \
_CATEGORIES, ANIMAL_KEYPOINTS, ALTERNATIVE_NAMES, ANIMAL_SKE... | Map the two names to 0 n-1 |
150,843 | import os
import glob
import argparse
import time
import json
from collections import defaultdict
from shutil import copyfile
import xml.etree.ElementTree as ET
import numpy as np
from PIL import Image
from openpifpaf.plugins.animalpose.constants import \
_CATEGORIES, ANIMAL_KEYPOINTS, ALTERNATIVE_NAMES, ANIMAL_SKE... | null |
150,844 | import os
import glob
import argparse
import time
import json
from collections import defaultdict
from shutil import copyfile
import xml.etree.ElementTree as ET
import numpy as np
from PIL import Image
from openpifpaf.plugins.animalpose.constants import \
_CATEGORIES, ANIMAL_KEYPOINTS, ALTERNATIVE_NAMES, ANIMAL_SKE... | null |
150,845 | import os
import glob
import argparse
import time
import json
from collections import defaultdict
from shutil import copyfile
import xml.etree.ElementTree as ET
import numpy as np
from PIL import Image
from openpifpaf.plugins.animalpose.constants import \
_CATEGORIES, ANIMAL_KEYPOINTS, ALTERNATIVE_NAMES, ANIMAL_SKE... | It works with partial names, like do for dogs |
150,846 | import os
import numpy as np
ANIMAL_KEYPOINTS = [
'Nose', # 1
'L_eye', # 2
'R_eye', # 3
'L_ear', # 4
'R_ear', # 5
'Throat', # 6
'Tail', # 7
'withers', # 8
'L_F_elbow', # 9
'R_F_elbow', # 10
'L_B_elbow', # 11
... | null |
150,847 | import os
import numpy as np
ANIMAL_KEYPOINTS = [
'Nose', # 1
'L_eye', # 2
'R_eye', # 3
'L_ear', # 4
'R_ear', # 5
'Throat', # 6
'Tail', # 7
'withers', # 8
'L_F_elbow', # 9
'R_F_elbow', # 10
'L_B_elbow', # 11
... | null |
150,848 | import numpy as np
COCO_PERSON_SKELETON = [
(16, 14), (14, 12), (17, 15), (15, 13), (12, 13), (6, 12), (7, 13),
(6, 7), (6, 8), (7, 9), (8, 10), (9, 11), (2, 3), (1, 2), (1, 3),
(2, 4), (3, 5), (4, 6), (5, 7),
]
KINEMATIC_TREE_SKELETON = [
(1, 2), (2, 4), # left head
(1, 3), (3, 5),
(1, 6),
... | null |
150,849 | import numpy as np
COCO_PERSON_SKELETON = [
(16, 14), (14, 12), (17, 15), (15, 13), (12, 13), (6, 12), (7, 13),
(6, 7), (6, 8), (7, 9), (8, 10), (9, 11), (2, 3), (1, 2), (1, 3),
(2, 4), (3, 5), (4, 6), (5, 7),
]
COCO_KEYPOINTS = [
'nose', # 1
'left_eye', # 2
'right_eye', ... | null |
150,850 | import copy
import numpy as np
WHOLEBODY_SKELETON = body_foot_skeleton + face_skeleton + lefthand_skeleton + righthand_skeleton
WHOLEBODY_KEYPOINTS = body_kps + foot_kps + face_kps + lefth_kps + righth_kps
WHOLEBODY_SIGMAS = body + foot + face + lefthand + righthand
WHOLEBODY_SCORE_WEIGHTS = [100.0] * 3 + [1.0] * (len(... | null |
150,851 | import copy
import numpy as np
WHOLEBODY_SKELETON = body_foot_skeleton + face_skeleton + lefthand_skeleton + righthand_skeleton
WHOLEBODY_KEYPOINTS = body_kps + foot_kps + face_kps + lefth_kps + righth_kps
def print_associations():
for j1, j2 in WHOLEBODY_SKELETON:
print(WHOLEBODY_KEYPOINTS[j1 - 1], '-', W... | null |
150,852 | import copy
import numpy as np
def rotate(pose, angle=45, axis=2):
sin = np.sin(np.radians(angle))
cos = np.cos(np.radians(angle))
pose_copy = np.copy(pose)
pose_copy[:, 2] = pose_copy[:, 2] - 2 # COOS at human center
if axis == 0:
rot_mat = np.array([[1, 0, 0],
... | null |
150,853 | import argparse
import logging
import os
import torch
import openpifpaf
LOG = logging.getLogger(__name__)
def cli():
parser = argparse.ArgumentParser(description=__doc__)
openpifpaf.plugin.register()
openpifpaf.logger.cli(parser)
openpifpaf.network.Factory.cli(parser)
parser.add_argument('-o', '-... | null |
150,854 | import argparse
from collections import namedtuple
import datetime
import logging
import os
import openpifpaf.benchmark
LOG = logging.getLogger(__name__)
DEFAULT_CHECKPOINTS = [
'tshufflenetv2k16',
]
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpForma... | null |
150,855 | import importlib
import os
import torch
def register_ops():
lib_dir = os.path.dirname(__file__)
if hasattr(os, 'add_dll_directory'): # for Windows
import ctypes # pylint: disable=import-outside-toplevel
kernel32 = ctypes.WinDLL('kernel32.dll', use_last_error=True)
if hasattr(kernel32... | null |
150,859 | import configparser
import errno
import json
import os
import re
import subprocess
import sys
from typing import Callable, Dict
import functools
class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""
def run_command(commands, args, cwd=None, verbose=False, hide_std... | Get version from 'git describe' in the root of the source tree. This only gets called if the git-archive 'subst' keywords were *not* expanded, and _version.py hasn't already been rewritten with a short version string, meaning we're inside a checked out source tree. |
150,861 | import configparser
import errno
import json
import os
import re
import subprocess
import sys
from typing import Callable, Dict
import functools
def get_root():
"""Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg... | Get the custom setuptools subclasses used by Versioneer. If the package uses a different cmdclass (e.g. one from numpy), it should be provide as an argument. |
150,862 | import configparser
import errno
import json
import os
import re
import subprocess
import sys
from typing import Callable, Dict
import functools
def get_root():
"""Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg... | Do main VCS-independent setup function for installing Versioneer. |
150,864 | import torch
import os
import argparse
import numpy as np
from im2scene.eval import (
calculate_activation_statistics, calculate_frechet_distance)
from torchvision.utils import save_image, make_grid
np.savez(out_dict_file, **out_dict)
def load_np_file(np_file):
ext = os.path.basename(np_file).split('.')[-1]
... | null |
150,866 | from collections import defaultdict
from torch import autograd
import torch.nn.functional as F
import numpy as np
def compute_grad2(d_out, x_in):
batch_size = x_in.size(0)
grad_dout = autograd.grad(
outputs=d_out.sum(), inputs=x_in,
create_graph=True, retain_graph=True, only_inputs=True
)[0... | null |
150,867 | from collections import defaultdict
from torch import autograd
import torch.nn.functional as F
import numpy as np
def toggle_grad(model, requires_grad):
def update_average(model_tgt, model_src, beta):
toggle_grad(model_src, False)
toggle_grad(model_tgt, False)
param_dict_src = dict(model_src.named_paramet... | null |
150,868 | from collections import defaultdict
from torch import autograd
import torch.nn.functional as F
import numpy as np
def compute_bce(d_out, target):
targets = d_out.new_full(size=d_out.size(), fill_value=target)
loss = F.binary_cross_entropy_with_logits(d_out, targets)
return loss | null |
150,869 | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def get_camera_mat(fov=49.13, invert=True):
# fov = 2 * arctan( sensor / (2 * focal))
# focal = (sensor / 2) * 1 / (tan(0.5 * fov))
# in our case, sensor = 2 as pixels are in [-1, 1]
focal = 1. / np.tan(0.5 * fov * np.... | null |
150,870 | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def sample_on_sphere(range_u=(0, 1), range_v=(0, 1), size=(1,),
to_pytorch=True):
u = np.random.uniform(*range_u, size=size)
v = np.random.uniform(*range_v, size=size)
sample = to_sphere(u, v)
if to_... | null |
150,871 | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def sample_on_sphere(range_u=(0, 1), range_v=(0, 1), size=(1,),
to_pytorch=True):
def look_at(eye, at=np.array([0, 0, 0]), up=np.array([0, 0, 1]), eps=1e-5,
to_pytorch=True):
def get_middle_pose(range_u... | null |
150,872 | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def sample_on_sphere(range_u=(0, 1), range_v=(0, 1), size=(1,),
to_pytorch=True):
u = np.random.uniform(*range_u, size=size)
v = np.random.uniform(*range_v, size=size)
sample = to_sphere(u, v)
if to_... | null |
150,873 | import numpy as np
import torch
from scipy.spatial.transform import Rotation as Rot
def get_rotation_matrix(axis='z', value=0., batch_size=32):
r = Rot.from_euler(axis, value * 2 * np.pi).as_dcm()
r = torch.from_numpy(r).reshape(1, 3, 3).repeat(batch_size, 1, 1)
return r | null |
150,874 | import os
import urllib
import torch
from torch.utils import model_zoo
import shutil
import datetime
The provided code snippet includes necessary dependencies for implementing the `is_url` function. Write a Python function `def is_url(url)` to solve the following problem:
Checks if input string is a URL. Args: url (st... | Checks if input string is a URL. Args: url (string): URL |
150,875 | import yaml
from im2scene import data
from im2scene import gan2d, giraffe
import logging
import os
def update_recursive(dict1, dict2):
''' Update two config dictionaries recursively.
Args:
dict1 (dict): first dictionary to be updated
dict2 (dict): second dictionary which entries should be used
... | Loads config file. Args: path (str): path to config file default_path (bool): whether to use default path |
150,876 | import yaml
from im2scene import data
from im2scene import gan2d, giraffe
import logging
import os
method_dict = {
'gan2d': gan2d,
'giraffe': giraffe,
}
The provided code snippet includes necessary dependencies for implementing the `get_model` function. Write a Python function `def get_model(cfg, device=None, ... | Returns the model instance. Args: cfg (dict): config dictionary device (device): pytorch device dataset (dataset): dataset |
150,877 | import yaml
from im2scene import data
from im2scene import gan2d, giraffe
import logging
import os
method_dict = {
'gan2d': gan2d,
'giraffe': giraffe,
}
def set_logger(cfg):
logfile = os.path.join(cfg['training']['out_dir'],
cfg['training']['logfile'])
logging.basicConfig(
... | Returns a trainer instance. Args: model (nn.Module): the model which is used optimizer (optimizer): pytorch optimizer cfg (dict): config dictionary device (device): pytorch device |
150,878 | import yaml
from im2scene import data
from im2scene import gan2d, giraffe
import logging
import os
method_dict = {
'gan2d': gan2d,
'giraffe': giraffe,
}
The provided code snippet includes necessary dependencies for implementing the `get_renderer` function. Write a Python function `def get_renderer(model, cfg, ... | Returns a render instance. Args: model (nn.Module): the model which is used cfg (dict): config dictionary device (device): pytorch device |
150,879 | import yaml
from im2scene import data
from im2scene import gan2d, giraffe
import logging
import os
The provided code snippet includes necessary dependencies for implementing the `get_dataset` function. Write a Python function `def get_dataset(cfg, **kwargs)` to solve the following problem:
Returns a dataset instance. ... | Returns a dataset instance. Args: cfg (dict): config dictionary mode (string): which mode is used (train / val /test / render) return_idx (bool): whether to return model index return_category (bool): whether to return model category |
150,880 | import os
from im2scene.discriminator import discriminator_dict
from im2scene.gan2d import models, training
from torch import randn
from copy import deepcopy
import numpy as np
discriminator_dict = {
'dc': conv.DCDiscriminator,
'resnet': conv.DiscriminatorResnet,
}
The provided code snippet includes necessary... | Returns the model. Args: cfg (dict): imported yaml config device (device): pytorch device len_dataset (int): length of dataset |
150,881 | import os
from im2scene.discriminator import discriminator_dict
from im2scene.gan2d import models, training
from torch import randn
from copy import deepcopy
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_traine... | Returns the trainer object. Args: model (nn.Module): the 2DGAN model optimizer (optimizer): pytorch optimizer object cfg (dict): imported yaml config device (device): pytorch device |
150,882 | import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
from im2scene.layers import ResnetBlock
def actvn(x):
out = F.leaky_relu(x, 2e-1)
return out | null |
150,883 | import os
from im2scene.discriminator import discriminator_dict
from im2scene.giraffe import models, training, rendering
from copy import deepcopy
import numpy as np
discriminator_dict = {
'dc': conv.DCDiscriminator,
'resnet': conv.DiscriminatorResnet,
}
The provided code snippet includes necessary dependenci... | Returns the giraffe model. Args: cfg (dict): imported yaml config device (device): pytorch device len_dataset (int): length of dataset |
150,884 | import os
from im2scene.discriminator import discriminator_dict
from im2scene.giraffe import models, training, rendering
from copy import deepcopy
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(model, op... | Returns the trainer object. Args: model (nn.Module): the GIRAFFE model optimizer (optimizer): generator optimizer object optimizer_d (optimizer): discriminator optimizer object cfg (dict): imported yaml config device (device): pytorch device |
150,885 | import os
from im2scene.discriminator import discriminator_dict
from im2scene.giraffe import models, training, rendering
from copy import deepcopy
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `get_renderer` function. Write a Python function `def get_renderer(model, ... | Returns the renderer object. Args: model (nn.Module): GIRAFFE model cfg (dict): imported yaml config device (device): pytorch device |
150,886 | import torch
import numpy as np
import logging
The provided code snippet includes necessary dependencies for implementing the `arange_pixels` function. Write a Python function `def arange_pixels(resolution=(128, 128), batch_size=1, image_range=(-1., 1.), subsample_to=None, invert_y_axis=False)` to so... | Arranges pixels for given resolution in range image_range. The function returns the unscaled pixel locations as integers and the scaled float values. Args: resolution (tuple): image resolution batch_size (int): batch size image_range (tuple): range of output points (default [-1, 1]) subsample_to (int): if integer and >... |
150,887 | import torch
import numpy as np
import logging
The provided code snippet includes necessary dependencies for implementing the `transform_to_camera_space` function. Write a Python function `def transform_to_camera_space(p_world, camera_mat, world_mat, scale_mat)` to solve the following problem:
Transforms world points ... | Transforms world points to camera space. Args: p_world (tensor): world points tensor of size B x N x 3 camera_mat (tensor): camera matrix world_mat (tensor): world matrix scale_mat (tensor): scale matrix |
150,888 | import torch
import numpy as np
import logging
The provided code snippet includes necessary dependencies for implementing the `origin_to_world` function. Write a Python function `def origin_to_world(n_points, camera_mat, world_mat, scale_mat=None, invert=False)` to solve the following problem:
Tran... | Transforms origin (camera location) to world coordinates. Args: n_points (int): how often the transformed origin is repeated in the form (batch_size, n_points, 3) camera_mat (tensor): camera matrix world_mat (tensor): world matrix scale_mat (tensor): scale matrix invert (bool): whether to invert the matrices (default: ... |
150,889 | import torch
import numpy as np
import logging
def transform_to_world(pixels, depth, camera_mat, world_mat, scale_mat=None,
invert=True, use_absolute_depth=True):
''' Transforms pixel positions p with given depth value d to world coordinates.
Args:
pixels (tensor): pixel tensor of... | Transforms points on image plane to world coordinates. In contrast to transform_to_world, no depth value is needed as points on the image plane have a fixed depth of 1. Args: image_points (tensor): image points tensor of size B x N x 2 camera_mat (tensor): camera matrix world_mat (tensor): world matrix scale_mat (tenso... |
150,890 | import torch
import numpy as np
import logging
def interpolate_sphere(z1, z2, t):
p = (z1 * z2).sum(dim=-1, keepdim=True)
p = p / z1.pow(2).sum(dim=-1, keepdim=True).sqrt()
p = p / z2.pow(2).sum(dim=-1, keepdim=True).sqrt()
omega = torch.acos(p)
s1 = torch.sin((1-t)*omega)/torch.sin(omega)
s2 =... | null |
150,891 | import numpy as np
import torch
from scipy import linalg
from torch.nn.functional import adaptive_avg_pool2d
from PIL import Image
from tqdm import tqdm
from im2scene.inception import InceptionV3
The provided code snippet includes necessary dependencies for implementing the `calculate_frechet_distance` function. Write... | Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params: -- mu1 : Numpy array containing the activations of a layer of the ... |
150,892 | import os
import pathlib
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import glob
import sys
from im2scene.eval import calculate_activation_statistics
import numpy as np
import torch
import cv2
from tqdm import tqdm
from PIL import Image
from torchvision import transforms
import lmdb
import rand... | Calculates the FID of two paths |
150,893 | from jellyfin_apiclient_python import JellyfinClient
from jellyfin_apiclient_python.connection_manager import CONNECTION_STATE
from .conf import settings
from . import conffile
from getpass import getpass
from .constants import CAPABILITIES, CLIENT_VERSION, USER_APP_NAME, USER_AGENT, APP_NAME
from .i18n import _
import... | null |
150,894 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | A decorator to place an instance based lock around a method. From: http://code.activestate.com/recipes/577105-synchronization-decorator-for-class-methods/ |
150,895 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
150,896 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
150,897 | import socket
import ipaddress
import requests
import urllib.parse
from threading import Lock
import logging
import sys
import os.path
import platform
from .conf import settings
from datetime import datetime
from functools import wraps
from .constants import USER_APP_NAME
from .i18n import _
from typing import TYPE_CHE... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.