id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
6,328 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,329 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,330 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,331 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,332 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,333 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,334 | import os
import glob
import cv2
import scipy.misc as misc
from skimage.transform import resize
import numpy as np
from functools import reduce
from operator import mul
import torch
from torch import nn
import matplotlib.pyplot as plt
import re
from scipy.ndimage import gaussian_filter
from skimage.feature import canny... | null |
6,335 | import os
import numpy as np
import networkx as netx
import matplotlib.pyplot as plt
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from vispy.visuals.filters import Alpha
import cv2
from moviepy.editor import ImageSequenceClip
from skimage.transform import resize
import time
... | null |
6,336 | import os
import numpy as np
import networkx as netx
import matplotlib.pyplot as plt
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from vispy.visuals.filters import Alpha
import cv2
from moviepy.editor import ImageSequenceClip
from skimage.transform import resize
import time
... | null |
6,337 | import os
import numpy as np
import networkx as netx
import matplotlib.pyplot as plt
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from vispy.visuals.filters import Alpha
import cv2
from moviepy.editor import ImageSequenceClip
from skimage.transform import resize
import time
... | null |
6,338 | import os
import numpy as np
import networkx as netx
import matplotlib.pyplot as plt
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from vispy.visuals.filters import Alpha
import cv2
from moviepy.editor import ImageSequenceClip
from skimage.transform import resize
import time
... | null |
6,339 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,340 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,341 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,342 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,343 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,344 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,345 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,346 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,347 | import os
import numpy as np
import json
import scipy.misc as misc
import scipy.signal as signal
import matplotlib.pyplot as plt
import cv2
import scipy.misc as misc
from skimage import io
from functools import partial
from vispy import scene, io
from vispy.scene import visuals
from functools import reduce
import scipy... | null |
6,348 | import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
def weights_init(init_type='gaussian'):
def init_fun(m):
classname = m.__class__.__name__
if (classname.find('Conv') == 0 or classname.find(
'Linear') == 0) and hasa... | null |
6,349 | import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
def spectral_norm(module, mode=True):
if mode:
return nn.utils.spectral_norm(module)
return module | null |
6,350 | import argparse
import os
import pathlib
import src.misc
The provided code snippet includes necessary dependencies for implementing the `maybe_chdir` function. Write a Python function `def maybe_chdir()` to solve the following problem:
Detects if DepthMap was installed as a stable-diffusion-webui script, but run witho... | Detects if DepthMap was installed as a stable-diffusion-webui script, but run without current directory set to the stable-diffusion-webui root. Changes current directory if needed. This is to avoid re-downloading models and putting results into a wrong folder. |
6,351 | import gc
import os.path
from operator import getitem
import cv2
import numpy as np
import skimage.measure
from PIL import Image
import torch
from torchvision.transforms import Compose, transforms
from dmidas.dpt_depth import DPTDepthModel
from dmidas.midas_net import MidasNet
from dmidas.midas_net_custom import MidasN... | null |
6,352 | import gc
import os.path
from operator import getitem
import cv2
import numpy as np
import skimage.measure
from PIL import Image
import torch
from torchvision.transforms import Compose, transforms
from dmidas.dpt_depth import DPTDepthModel
from dmidas.midas_net import MidasNet
from dmidas.midas_net_custom import MidasN... | null |
6,353 | import gc
import os.path
from operator import getitem
import cv2
import numpy as np
import skimage.measure
from PIL import Image
import torch
from torchvision.transforms import Compose, transforms
from dmidas.dpt_depth import DPTDepthModel
from dmidas.midas_net import MidasNet
from dmidas.midas_net_custom import MidasN... | # recompute a, b and saturate to max res. if max(a,b) > max_res: print('Default Res is higher than max-res: Reducing final resolution') if img.shape[0] > img.shape[1]: a = max_res b = round(option.max_res * img.shape[1] / img.shape[0]) else: a = round(option.max_res * img.shape[0] / img.shape[1]) b = max_res b = int(b)... |
6,354 | import numpy as np
from PIL import Image
def njit(parallel=False):
def Inner(func): return lambda *args, **kwargs: func(*args, **kwargs)
return Inner | null |
6,355 | import traceback
from pathlib import Path
import gradio as gr
from PIL import Image
from src import backbone, video_mode
from src.core import core_generation_funnel, unload_models, run_makevideo
from src.depthmap_generation import ModelHolder
from src.gradio_args_transport import GradioComponentBundle
from src.misc imp... | null |
6,356 | import traceback
from pathlib import Path
import gradio as gr
from PIL import Image
from src import backbone, video_mode
from src.core import core_generation_funnel, unload_models, run_makevideo
from src.depthmap_generation import ModelHolder
from src.gradio_args_transport import GradioComponentBundle
from src.misc imp... | null |
6,357 | import subprocess
import os
import pathlib
import builtins
def get_commit_hash():
try:
file_path = pathlib.Path(__file__).parent
return subprocess.check_output(
[os.environ.get("GIT", "git"), "rev-parse", "HEAD"],
cwd=file_path, shell=False, stderr=subprocess.DEVNULL, encodi... | null |
6,358 | import subprocess
import os
import pathlib
import builtins
def ensure_file_downloaded(filename, url, sha256_hash_prefix=None):
import torch
# Do not check the hash every time - it is somewhat time-consumin
if os.path.exists(filename):
return
if type(url) is not list:
url = [url]
fo... | null |
6,359 | import torchsparse.nn.functional as spf
from torchsparse.point_tensor import PointTensor
from torchsparse.utils.kernel_region import *
from torchsparse.utils.helpers import *
def initial_voxelize(z, init_res, after_res):
new_float_coord = torch.cat(
[(z.C[:, :3] * init_res) / after_res, z.C[:, -1].view(-1,... | null |
6,360 | import torchsparse.nn.functional as spf
from torchsparse.point_tensor import PointTensor
from torchsparse.utils.kernel_region import *
from torchsparse.utils.helpers import *
def point_to_voxel(x, z):
if z.additional_features is None or z.additional_features.get('idx_query') is None\
or z.additional_feature... | null |
6,361 | import torchsparse.nn.functional as spf
from torchsparse.point_tensor import PointTensor
from torchsparse.utils.kernel_region import *
from torchsparse.utils.helpers import *
def voxel_to_point(x, z, nearest=False):
if z.idx_query is None or z.weights is None or z.idx_query.get(
x.s) is None or z.weigh... | null |
6,362 | import importlib
import torch
import os
from collections import OrderedDict
The provided code snippet includes necessary dependencies for implementing the `get_func` function. Write a Python function `def get_func(func_name)` to solve the following problem:
Helper to return a function object by name. func_name must id... | Helper to return a function object by name. func_name must identify a function in this module or the path to a function relative to the base 'modeling' module. |
6,363 | import importlib
import torch
import os
from collections import OrderedDict
def strip_prefix_if_present(state_dict, prefix):
keys = sorted(state_dict.keys())
if not all(key.startswith(prefix) for key in keys):
return state_dict
stripped_state_dict = OrderedDict()
for key, value in state_dict.ite... | Load checkpoint. |
6,364 | import torch.nn as nn
import torch.nn as NN
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1)` to solve the following problem:
3x3 convolution with padding
Here is the function:
def conv3x3(in_plane... | 3x3 convolution with padding |
6,365 | import torch.nn as nn
import torch.nn as NN
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d
... | Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
6,366 | import torch.nn as nn
import torch.nn as NN
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride)
self.bn1 = NN.BatchNorm2d(planes) #NN.BatchNorm2d
... | Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
6,367 | import torch.nn as nn
import torch.nn as NN
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = NN.BatchNorm2d(planes)... | Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
6,368 | import torch.nn as nn
import torch.nn as NN
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = NN.BatchNorm2d(planes)... | Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
6,369 | import torch.nn as nn
import torch.nn as NN
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = NN.BatchNorm2d(planes)... | Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
6,370 | import torch
import torch.nn as nn
import torch.nn.init as init
from lib import Resnet, Resnext_torch
class DepthNet(nn.Module):
__factory = {
18: Resnet.resnet18,
34: Resnet.resnet34,
50: Resnet.resnet50,
101: Resnet.resnet101,
152: Resnet.resnet152
}
def __init__(se... | null |
6,371 | import torch
import torch.nn as nn
import torch.nn.init as init
from lib import Resnet, Resnext_torch
class DepthNet(nn.Module):
def __init__(self,
backbone='resnet',
depth=50,
upfactors=[2, 2, 2, 2]):
def forward(self, x):
def resnext101_stride3... | null |
6,372 | import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `conv3x3` function. Write a Python function `def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1)` to solve the following problem:
3x3 convolution with padding
Here is the function:
def conv3x3(in_plane... | 3x3 convolution with padding |
6,373 | import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `conv1x1` function. Write a Python function `def conv1x1(in_planes, out_planes, stride=1)` to solve the following problem:
1x1 convolution
Here is the function:
def conv1x1(in_planes, out_planes, stride=1):
"""1x... | 1x1 convolution |
6,374 | import torch.nn as nn
class Bottleneck(nn.Module):
# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
# while original implementation places the stride at the first 1x1 convolution(self.conv1)
# according to "Deep residual learning for image recognition"https://arx... | Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet |
6,375 | import numpy as np
import cv2
import math
The provided code snippet includes necessary dependencies for implementing the `apply_min_size` function. Write a Python function `def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA)` to solve the following problem:
Rezise the sample to ensure the given... | Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size |
6,376 | import timm
import torch
import types
import numpy as np
import torch.nn.functional as F
from .utils import forward_adapted_unflatten, make_backbone_default
from timm.models.beit import gen_relative_position_index
from torch.utils.checkpoint import checkpoint
from typing import Optional
def forward_adapted_unflatten(p... | null |
6,377 | import timm
import torch
import torch.nn as nn
import numpy as np
from .utils import activations, get_activation, Transpose
activations = {}
def forward_levit(pretrained, x):
pretrained.model.forward_features(x)
layer_1 = pretrained.activations["1"]
layer_2 = pretrained.activations["2"]
layer_3 = pre... | null |
6,378 | import timm
import torch
import torch.nn as nn
import numpy as np
from .utils import activations, get_activation, Transpose
class ConvTransposeNorm(nn.Sequential):
"""
Modification of
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: ConvNorm
such that ConvTranspose... | Modification of https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/levit.py: stem_b16 such that ConvTranspose2d is used instead of Conv2d and stem is also reduced to the half. |
6,379 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from functools import partial
import torch
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry ... | Merge pre BN to reduce inference runtime. |
6,380 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from functools import partial
import torch
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry ... | null |
6,381 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from functools import partial
import torch
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry ... | null |
6,382 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from functools import partial
import torch
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry ... | null |
6,383 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from functools import partial
import torch
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry ... | null |
6,384 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from functools import partial
import torch
import torch.utils.checkpoint as checkpoint
from einops import rearrange
from timm.models.layers import DropPath, trunc_normal_
from timm.models.registry ... | null |
6,385 | import torch
import torch.nn as nn
import timm
import types
import math
import torch.nn.functional as F
from .utils import (activations, forward_adapted_unflatten, get_activation, get_readout_oper,
make_backbone_default, Transpose)
def forward_adapted_unflatten(pretrained, x, function_name="forward... | null |
6,386 | import torch
import torch.nn as nn
import numpy as np
from .utils import activations, forward_default, get_activation, Transpose
def forward_default(pretrained, x, function_name="forward_features"):
exec(f"pretrained.model.{function_name}(x)")
layer_1 = pretrained.activations["1"]
layer_2 = pretrained.act... | null |
6,387 | import torch
import torch.nn as nn
from .base_model import BaseModel
from .blocks import (
FeatureFusionBlock_custom,
Interpolate,
_make_encoder,
forward_beit,
forward_swin,
forward_next_vit,
forward_levit,
forward_vit,
)
from .backbones.levit import stem_b4_transpose
from timm.models.la... | null |
6,388 | import torch
import torch.nn as nn
from .backbones.beit import (
_make_pretrained_beitl16_512,
_make_pretrained_beitl16_384,
_make_pretrained_beitb16_384,
forward_beit,
)
from .backbones.swin_common import (
forward_swin,
)
from .backbones.swin2 import (
_make_pretrained_swin2l24_384,
_make_... | null |
6,389 | import cv2
import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
from midas.transforms import Resize, NormalizeImage, PrepareForNet
from torchvision.transforms import Compose
The provided code snippet includes necessary dependencie... | Load the specified network. Args: device (device): the torch device used model_path (str): path to saved model model_type (str): the type of the model to be loaded optimize (bool): optimize the model to half-integer on CUDA? height (int): inference encoder image height square (bool): resize to a square resolution? Retu... |
6,390 | import torch
import torch.nn as nn
from .base_model import BaseModel
from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder
def fuse_model(m):
prev_previous_type = nn.Identity()
prev_previous_name = ''
previous_type = nn.Identity()
previous_name = ''
for name,... | null |
6,391 | import numpy as np
import random
import torch
The provided code snippet includes necessary dependencies for implementing the `seed_all` function. Write a Python function `def seed_all(seed: int = 0)` to solve the following problem:
Set random seeds of all components.
Here is the function:
def seed_all(seed: int = 0)... | Set random seeds of all components. |
6,392 | import torch
import math
bs_search_table = [
# tested on A100-PCIE-80GB
{"res": 768, "total_vram": 79, "bs": 35},
{"res": 1024, "total_vram": 79, "bs": 20},
# tested on A100-PCIE-40GB
{"res": 768, "total_vram": 39, "bs": 15},
{"res": 1024, "total_vram": 39, "bs": 8},
# tested on RTX3090, RTX... | Automatically search for suitable operating batch size. Args: ensemble_size (int): Number of predictions to be ensembled input_res (int): Operating resolution of the input image. Returns: int: Operating batch size |
6,393 | import numpy as np
import torch
from scipy.optimize import minimize
def inter_distances(tensors: torch.Tensor):
"""
To calculate the distance between each two depth maps.
"""
distances = []
for i, j in torch.combinations(torch.arange(tensors.shape[0])):
arr1 = tensors[i : i + 1]
arr2... | To ensemble multiple affine-invariant depth images (up to scale and shift), by aligning estimating the scale and shift |
6,394 | import matplotlib
import numpy as np
import torch
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `colorize_depth_maps` function. Write a Python function `def colorize_depth_maps( depth_map, min_depth, max_depth, cmap="Spectral", valid_mask=None )` to solve the ... | Colorize depth maps. |
6,395 | import matplotlib
import numpy as np
import torch
from PIL import Image
def chw2hwc(chw):
assert 3 == len(chw.shape)
if isinstance(chw, torch.Tensor):
hwc = torch.permute(chw, (1, 2, 0))
elif isinstance(chw, np.ndarray):
hwc = np.moveaxis(chw, 0, -1)
return hwc | null |
6,396 | import matplotlib
import numpy as np
import torch
from PIL import Image
The provided code snippet includes necessary dependencies for implementing the `resize_max_res` function. Write a Python function `def resize_max_res(img: Image.Image, max_edge_resolution: int) -> Image.Image` to solve the following problem:
Resiz... | Resize image to limit maximum edge length while keeping aspect ratio Args: img (Image.Image): Image to be resized max_edge_resolution (int): Maximum edge length (px). Returns: Image.Image: Resized image. |
6,397 | import launch
import platform
import sys
import importlib.metadata
if not launch.is_installed('packaging'):
launch.run_pip("install packaging", "packaging requirement for depthmap script")
from packaging.version import Version
if not launch.is_installed("moviepy"):
launch.run_pip('install "moviepy==1.0.2"', "mo... | null |
6,398 | import launch
import platform
import sys
import importlib.metadata
if not launch.is_installed('packaging'):
launch.run_pip("install packaging", "packaging requirement for depthmap script")
from packaging.version import Version
if not launch.is_installed("moviepy"):
launch.run_pip('install "moviepy==1.0.2"', "mo... | null |
6,399 | import os
import numpy as np
from fastapi import FastAPI, Body
from fastapi.exceptions import HTTPException
from PIL import Image
import gradio as gr
from typing import Dict, List
from modules.api import api
from src.core import core_generation_funnel, run_makevideo
from src.misc import SCRIPT_VERSION
from src import b... | null |
6,400 | import traceback
import gradio as gr
from modules import shared
import modules.scripts as scripts
from PIL import Image
from src import backbone
from src import common_ui
from src.core import core_generation_funnel
from src.gradio_args_transport import GradioComponentBundle
from src.misc import *
from modules import sc... | null |
6,401 | import os
import cv2
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class VKITTI2(Dataset):
def __init__(self, data_dir_root, do_kb_crop=True, split="test"):
import glob
# image paths are of the form <data_dir... | null |
6,402 | import os
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class DDAD(Dataset):
def __init__(self, data_dir_root, resize_shape):
def __getitem__(self, idx):
def __len__(self):
def get_ddad_loader(data_dir_root, resi... | null |
6,403 | import math
import random
import cv2
import numpy as np
The provided code snippet includes necessary dependencies for implementing the `apply_min_size` function. Write a Python function `def apply_min_size(sample, size, image_interpolation_method=cv2.INTER_AREA)` to solve the following problem:
Rezise the sample to en... | Rezise the sample to ensure the given size. Keeps aspect ratio. Args: sample (dict): sample size (tuple): image size Returns: tuple: new size |
6,404 | import os
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class SunRGBD(Dataset):
def __init__(self, data_dir_root):
# test_file_dirs = loadmat(train_test_file)['alltest'].squeeze()
# all_test = [t[0].replace("... | null |
6,405 | import numpy as np
from dataclasses import dataclass
from typing import Tuple, List
def get_white_border(rgb_image, value=255, **kwargs) -> CropParams:
"""Crops the white border of the RGB.
Args:
rgb: RGB image, shape (H, W, 3).
Returns:
Crop parameters.
"""
if value == 255:
... | Crops the white and black border of the RGB and depth images. Args: rgb: RGB image, shape (H, W, 3). This image is used to determine the border. other_images: The other images to crop according to the border of the RGB image. Returns: Cropped RGB and other images. |
6,406 | import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import os
from PIL import Image
import numpy as np
import cv2
class VKITTI(Dataset):
def __init__(self, data_dir_root, do_kb_crop=True):
import glob
# image paths are of the form <data_dir_root>/{HR, LR}... | null |
6,407 | import os
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms as T
class iBims(Dataset):
def __init__(self, config):
root_folder = config.ibims_root
with open(os.path.join(root_folder, "imagelist.txt"), 'r') as f:
... | null |
6,408 | import glob
import os
import h5py
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
def hypersim_distance_to_depth(npyDistance):
intWidth, intHeight, fltFocal = 1024, 768, 886.81
npyImageplaneX = np.linspace((-0.5 * intWid... | null |
6,409 | import glob
import os
import h5py
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class HyperSim(Dataset):
def __init__(self, data_dir_root):
# image paths are of the form <data_dir_root>/<scene>/images/scene_cam_#_fin... | null |
6,410 | import os
import numpy as np
import torch
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
class DIODE(Dataset):
def __init__(self, data_dir_root):
import glob
# image paths are of the form <data_dir_root>/scene_#/scan_#/*.png
self.ima... | null |
6,411 | import itertools
import os
import random
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.utils.data.distributed
from zoedepth.utils.easydict import EasyDict as edict
from PIL import Image, ImageOps
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from zoe... | null |
6,412 | import itertools
import os
import random
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.utils.data.distributed
from zoedepth.utils.easydict import EasyDict as edict
from PIL import Image, ImageOps
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from zoe... | null |
6,413 | import itertools
import os
import random
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.utils.data.distributed
from zoedepth.utils.easydict import EasyDict as edict
from PIL import Image, ImageOps
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from zoe... | null |
6,414 | import itertools
import os
import random
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.utils.data.distributed
from zoedepth.utils.easydict import EasyDict as edict
from PIL import Image, ImageOps
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from zoe... | cycles through iterables but sample wise first yield first sample from first iterable then first sample from second iterable and so on then second sample from first iterable then second sample from second iterable and so on If one iterable is shorter than the others, it is repeated until all iterables are exhausted rep... |
6,415 | import itertools
import os
import random
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.utils.data.distributed
from zoedepth.utils.easydict import EasyDict as edict
from PIL import Image, ImageOps
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from zoe... | null |
6,416 | import os
import uuid
import warnings
from datetime import datetime as dt
from typing import Dict
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import wandb
from tqdm import tqdm
from zoedepth.utils.config import flatte... | null |
6,417 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda.amp as amp
import numpy as np
def extract_key(prediction, key):
if isinstance(prediction, dict):
return prediction[key]
return prediction | null |
6,418 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda.amp as amp
import numpy as np
def grad(x):
# x.shape : n, c, h, w
diff_x = x[..., 1:, 1:] - x[..., 1:, :-1]
diff_y = x[..., 1:, 1:] - x[..., :-1, 1:]
mag = diff_x**2 + diff_y**2
# angle_ratio
angle = torch.atan... | null |
6,419 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda.amp as amp
import numpy as np
def grad_mask(mask):
return mask[..., 1:, 1:] & mask[..., 1:, :-1] & mask[..., :-1, 1:] | null |
6,420 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.cuda.amp as amp
import numpy as np
def compute_scale_and_shift(prediction, target, mask):
# system matrix: A = [[a_00, a_01], [a_10, a_11]]
a_00 = torch.sum(mask * prediction * prediction, (1, 2))
a_01 = torch.sum(mask * predic... | null |
6,421 | from importlib import import_module
The provided code snippet includes necessary dependencies for implementing the `get_trainer` function. Write a Python function `def get_trainer(config)` to solve the following problem:
Builds and returns a trainer based on the config. Args: config (dict): the config dict (typically ... | Builds and returns a trainer based on the config. Args: config (dict): the config dict (typically constructed using utils.config.get_config) config.trainer (str): the name of the trainer to use. The module named "{config.trainer}_trainer" must exist in trainers root module Raises: ValueError: If the specified trainer d... |
6,422 | import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `exp_attractor` function. Write a Python function `def exp_attractor(dx, alpha: float = 300, gamma: int = 2)` to solve the following problem:
Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where... | Exponential attractor: dc = exp(-alpha*|dx|^gamma) * dx , where dx = a - c, a = attractor point, c = bin center, dc = shift in bin centermmary for exp_attractor Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (float, optional): Proportional At... |
6,423 | import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `inv_attractor` function. Write a Python function `def inv_attractor(dx, alpha: float = 300, gamma: int = 2)` to solve the following problem:
Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a... | Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center This is the default one according to the accompanying paper. Args: dx (torch.Tensor): The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center. alpha (fl... |
6,424 | import torch
import torch.nn as nn
The provided code snippet includes necessary dependencies for implementing the `log_binom` function. Write a Python function `def log_binom(n, k, eps=1e-7)` to solve the following problem:
log(nCk) using stirling approximation
Here is the function:
def log_binom(n, k, eps=1e-7):
... | log(nCk) using stirling approximation |
6,425 | import torch
def load_wts(model, checkpoint_path):
ckpt = torch.load(checkpoint_path, map_location='cpu')
return load_state_dict(model, ckpt)
def load_state_dict_from_url(model, url, **kwargs):
state_dict = torch.hub.load_state_dict_from_url(url, map_location='cpu', **kwargs)
return load_state_dict(mode... | Loads weights to the model from a given resource. A resource can be of following types: 1. URL. Prefixed with "url::" e.g. url::http(s)://url.resource.com/ckpt.pt 2. Local path. Prefixed with "local::" e.g. local::/path/to/ckpt.pt Args: model (torch.nn.Module): Model resource (str): resource string Returns: torch.nn.Mo... |
6,426 | import torch
import torch.nn as nn
import numpy as np
from torchvision.transforms import Normalize
The provided code snippet includes necessary dependencies for implementing the `denormalize` function. Write a Python function `def denormalize(x)` to solve the following problem:
Reverses the imagenet normalization appl... | Reverses the imagenet normalization applied to the input. Args: x (torch.Tensor - shape(N,3,H,W)): input tensor Returns: torch.Tensor - shape(N,3,H,W): Denormalized input |
6,427 | import torch
import torch.nn as nn
import numpy as np
from torchvision.transforms import Normalize
def get_activation(name, bank):
def hook(model, input, output):
bank[name] = output
return hook | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.