id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
33,838 | import os
import re
import uuid
import cv2
import torch
import requests
import io, base64
import numpy as np
import gradio as gr
from PIL import Image
from omegaconf import OmegaConf
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoMod... | null |
33,839 | import os
import re
import uuid
import cv2
import torch
import requests
import io, base64
import numpy as np
import gradio as gr
from PIL import Image
from omegaconf import OmegaConf
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoMod... | null |
33,840 | import os
import re
import uuid
import cv2
import torch
import requests
import io, base64
import numpy as np
import gradio as gr
from PIL import Image
from omegaconf import OmegaConf
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoMod... | null |
33,841 | import os
import re
import uuid
import cv2
import torch
import requests
import io, base64
import numpy as np
import gradio as gr
from PIL import Image
from omegaconf import OmegaConf
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoMod... | null |
33,842 | import os
import re
import uuid
import cv2
import torch
import requests
import io, base64
import numpy as np
import gradio as gr
from PIL import Image
from omegaconf import OmegaConf
from transformers import pipeline, BlipProcessor, BlipForConditionalGeneration, BlipForQuestionAnswering
from transformers import AutoMod... | null |
33,843 |
def preload(parser):
parser.add_argument(
"--controlnet-dir",
type=str,
help="Path to directory with ControlNet models",
default=None,
)
parser.add_argument(
"--controlnet-annotator-models-path",
type=str,
help="Path to directory with annotator model... | null |
33,844 | import argparse
import torch
from safetensors.torch import load_file, save_file
def remove_first_and_cond(sd):
keys = list(sd.keys())
for key in keys:
is_first_stage, _ = get_node_name(key, 'first_stage_model')
is_cond_stage, _ = get_node_name(key, 'cond_stage_model')
... | null |
33,845 | import launch
import pkg_resources
import sys
import os
import shutil
import platform
from pathlib import Path
from typing import Tuple, Optional
def comparable_version(version: str) -> Tuple:
return tuple(version.split("."))
def get_installed_version(package: str) -> Optional[str]:
try:
return pkg_reso... | null |
33,846 | import launch
import pkg_resources
import sys
import os
import shutil
import platform
from pathlib import Path
from typing import Tuple, Optional
def comparable_version(version: str) -> Tuple:
return tuple(version.split("."))
def get_installed_version(package: str) -> Optional[str]:
try:
return pkg_reso... | null |
33,847 | import launch
import pkg_resources
import sys
import os
import shutil
import platform
from pathlib import Path
from typing import Tuple, Optional
def get_installed_version(package: str) -> Optional[str]:
try:
return pkg_resources.get_distribution(package).version
except Exception:
return None
T... | Attempt to install insightface library. The library is necessary to use ip-adapter faceid. Note: Building insightface library from source requires compiling C++ code, which should be avoided in principle. Here the solution is to download a precompiled wheel. |
33,848 | import launch
import pkg_resources
import sys
import os
import shutil
import platform
from pathlib import Path
from typing import Tuple, Optional
repo_root = Path(__file__).parent
The provided code snippet includes necessary dependencies for implementing the `try_remove_legacy_submodule` function. Write a Python funct... | Try remove annotators/hand_refiner_portable submodule dir. |
33,849 | import re
import subprocess
def get_current_version(filename):
version_pattern = r"version_flag\s*=\s*'v(\d+\.\d+\.\d+)'"
with open(filename, "r") as file:
content = file.read()
match = re.search(version_pattern, content)
if match:
return match.group(1)
else:
raise ValueEr... | null |
33,850 | import re
import subprocess
def increment_version(version):
major, minor, patch = map(int, version.split("."))
patch += 1 # Increment the patch number
return f"{major}.{minor}.{patch}" | null |
33,851 | import re
import subprocess
def update_version_file(filename, new_version):
with open(filename, "r") as file:
content = file.read()
new_content = re.sub(
r"version_flag = 'v\d+\.\d+\.\d+'", f"version_flag = 'v{new_version}'", content
)
with open(filename, "w") as file:
file.wr... | null |
33,852 | import re
import subprocess
def git_commit_and_tag(filename, new_version):
commit_message = f":memo: Update to version v{new_version}"
tag_name = f"v{new_version}"
# Commit the changes
subprocess.run(["git", "add", filename], check=True)
subprocess.run(["git", "commit", "-m", commit_message], chec... | null |
33,853 | import numpy as np
import cv2
import os
The provided code snippet includes necessary dependencies for implementing the `load_model` function. Write a Python function `def load_model(filename: str, remote_url: str, model_dir: str) -> str` to solve the following problem:
Load the model from the specified filename and re... | Load the model from the specified filename and remote URL if it doesn't exist locally. Args: filename (str): The filename of the model. remote_url (str): The remote URL of the model. |
33,854 | import numpy as np
import cv2
import os
def make_noise_disk(H, W, C, F):
noise = np.random.uniform(low=0, high=1, size=((H // F) + 2, (W // F) + 2, C))
noise = cv2.resize(noise, (W + 2 * F, H + 2 * F), interpolation=cv2.INTER_CUBIC)
noise = noise[F: F + H, F: F + W]
noise -= np.min(noise)
noise /= ... | null |
33,855 | import numpy as np
import cv2
import os
def min_max_norm(x):
x -= np.min(x)
x /= np.maximum(np.max(x), 1e-5)
return x | null |
33,856 | import numpy as np
import cv2
import os
def safe_step(x, step=2):
y = x.astype(np.float32) * float(step + 1)
y = y.astype(np.int32).astype(np.float32) / float(step)
return y | null |
33,857 | from typing import Mapping
import mediapipe as mp
import numpy
mp_drawing = mp.solutions.drawing_utils
mp_face_mesh = mp.solutions.face_mesh
min_face_size_pixels: int = 64
face_connection_spec = {}
iris_landmark_spec = {468: right_iris_draw, 473: left_iris_draw}
def draw_pupils(image, landmark_list, drawing_spec, half... | Find up to 'max_faces' inside the provided input image. If min_face_size_pixels is provided and nonzero it will be used to filter faces that occupy less than this many pixels in the image. |
33,866 | 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. |
33,867 | 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. |
33,874 | from modules import devices
from modules.shared import opts
from torchvision.transforms import transforms
from operator import getitem
import torch, gc
import cv2
import numpy as np
import skimage.measure
def impatch(image, rect):
# Extract the given patch pixels from a given image.
w1 = rect[0]
h1 = rect[... | null |
33,875 | from modules import devices
from modules.shared import opts
from torchvision.transforms import transforms
from operator import getitem
import torch, gc
import cv2
import numpy as np
import skimage.measure
whole_size_threshold = 1600
pix2pixsize = 1024
def generatemask(size):
# Generates a Guassian mask
mask = ... | # 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(max_res * img.shape[1] / img.shape[0]) else: a = round(max_res * img.shape[0] / img.shape[1]) b = max_res b = int(b) a = int(a) |
33,876 | import torch
import torch.nn as nn
import torch.nn.init as init
from . 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__(self... | null |
33,877 | import torch
import torch.nn as nn
import torch.nn.init as init
from . 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__(self... | null |
33,881 | import cv2
import torch
import torch.nn as nn
import os
from annotator.annotator_path import models_path
from torchvision.transforms import Compose
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, No... | Overwrite model.train with this function to make sure train/eval mode does not change anymore. |
33,882 | import cv2
import torch
import torch.nn as nn
import os
from annotator.annotator_path import models_path
from torchvision.transforms import Compose
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, No... | null |
33,883 | import cv2
import torch
import torch.nn as nn
import os
from annotator.annotator_path import models_path
from torchvision.transforms import Compose
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, No... | null |
33,900 | import os
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 normaliz... | 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 |
33,901 | import os
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 |
33,905 | import os
import glob
import torch
import utils
import cv2
import argparse
import time
import numpy as np
from imutils.video import VideoStream
from midas.model_loader import default_models, load_model
def process(device, model, model_type, image, input_size, target_size, optimize, use_camera):
"""
Run the infe... | Run MonoDepthNN to compute depth maps. Args: input_path (str): path to input folder output_path (str): path to output folder model_path (str): path to saved model model_type (str): the model type optimize (bool): optimize the model to half-floats on CUDA? side (bool): RGB and depth side by side in output images? height... |
33,910 | import timm
import torch.nn as nn
from pathlib import Path
from .utils import activations, forward_default, get_activation
from ..external.next_vit.classification.nextvit import *
def forward_default(pretrained, x, function_name="forward_features"):
exec(f"pretrained.model.{function_name}(x)")
layer_1 = pretr... | null |
33,913 | 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_levit,
forward_vit,
)
from .backbones.levit import stem_b4_transpose
from timm.models.layers import get_act_la... | null |
33,914 | 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 |
33,917 | import os
import glob
import utils
import cv2
import argparse
import tensorflow as tf
from transforms import Resize, NormalizeImage, PrepareForNet
class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True... | Run MonoDepthNN to compute depth maps. Args: input_path (str): path to input folder output_path (str): path to output folder model_path (str): path to saved model |
33,918 | import os
import ntpath
import glob
import torch
import utils
import cv2
import numpy as np
from torchvision.transforms import Compose, Normalize
from torchvision import transforms
from shutil import copyfile
import fileinput
import sys
from midas.midas_net import MidasNet
from midas.transforms import Resize, Normalize... | null |
33,919 | import os
import ntpath
import glob
import torch
import utils
import cv2
import numpy as np
from torchvision.transforms import Compose, Normalize
from torchvision import transforms
from shutil import copyfile
import fileinput
import sys
from midas.midas_net import MidasNet
from midas.transforms import Resize, Normalize... | null |
33,920 | import os
import ntpath
import glob
import torch
import utils
import cv2
import numpy as np
from torchvision.transforms import Compose, Normalize
from torchvision import transforms
from shutil import copyfile
import fileinput
import sys
from midas.midas_net import MidasNet
from midas.transforms import Resize, Normalize... | Run MonoDepthNN to compute depth maps. Args: model_path (str): path to saved model |
33,921 | import os
import glob
import utils
import cv2
import sys
import numpy as np
import argparse
import onnx
import onnxruntime as rt
from transforms import Resize, NormalizeImage, PrepareForNet
class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,... | Run MonoDepthNN to compute depth maps. Args: input_path (str): path to input folder output_path (str): path to output folder model_path (str): path to saved model |
33,922 | import roslib
import sys
import rospy
import cv2
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
def talker():
rospy.init_node('talker', anonymous=True)
use_camera = rospy.get_param('~use_camera', False)
input_video_file = rospy.get_param... | null |
33,923 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_BEiT_L_512 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,924 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_BEiT_L_384 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,925 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_BEiT_B_384 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,926 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_SwinV2_L_384 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,927 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_SwinV2_B_384 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,928 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_SwinV2_T_256 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,929 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_Swin_L_384 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,930 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_Next_ViT_L_384 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,931 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT_LeViT_224 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,932 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT-Large model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,933 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class DPTDepthModel(DPT):
def __init__(self, path=None, non_negative=True, **kwargs):
features = kwargs["features"] if "features" in kwargs else 256
head_fea... | # This docstring shows up in hub.help() MiDaS DPT-Hybrid model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,934 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class MidasNet(BaseModel):
"""Network for monocular depth estimation.
"""
def __init__(self, path=None, features=256, non_negative=True):
"""Init.
... | # This docstring shows up in hub.help() MiDaS v2.1 model for monocular depth estimation pretrained (bool): load pretrained weights into model |
33,935 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class MidasNet_small(BaseModel):
"""Network for monocular depth estimation.
"""
def __init__(self, path=None, features=64, backbone="efficientnet_lite3", non_negati... | # This docstring shows up in hub.help() MiDaS v2.1 small model for monocular depth estimation on resource-constrained devices pretrained (bool): load pretrained weights into model |
33,936 | import torch
from midas.dpt_depth import DPTDepthModel
from midas.midas_net import MidasNet
from midas.midas_net_custom import MidasNet_small
class Resize(object):
"""Resize sample to given size (width, height).
"""
def __init__(
self,
width,
height,
resize_target=True,
... | null |
33,937 | from importlib import import_module
from .depth_model import DepthModel
class DepthModel(nn.Module):
def __init__(self):
super().__init__()
self.device = 'cpu'
def to(self, device) -> nn.Module:
self.device = device
return super().to(device)
def forward(self, x, *a... | Builds a model from a config. The model is specified by the model name and version in the config. The model is then constructed using the build_from_config function of the model interface. This function should be used to construct models for training and evaluation. Args: config (dict): Config dict. Config is construct... |
33,938 | import json
import os
from .easydict import EasyDict as edict
from .arg_utils import infer_type
import pathlib
import platform
COMMON_CONFIG = {
"save_dir": os.path.expanduser("~/shortcuts/monodepth3_checkpoints"),
"project": "ZoeDepth",
"tags": '',
"notes": "",
"gpu": None,
"root": ".",
"ui... | Main entry point to get the config for the model. Args: model_name (str): name of the desired model. mode (str, optional): "train" or "infer". Defaults to 'train'. dataset (str, optional): If specified, the corresponding dataset configuration is loaded as well. Defaults to None. Keyword Args: key-value pairs of argumen... |
33,939 | import json
import os
from .easydict import EasyDict as edict
from .arg_utils import infer_type
import pathlib
import platform
DATASETS_CONFIG = {
"kitti": {
"dataset": "kitti",
"min_depth": 0.001,
"max_depth": 80,
"data_path": os.path.join(HOME_DIR, "shortcuts/datasets/kitti/raw"),
... | null |
33,940 | from scipy import ndimage
import base64
import math
import re
from io import BytesIO
import matplotlib
import matplotlib.cm
import numpy as np
import requests
import torch
import torch.distributed as dist
import torch.nn
import torch.nn as nn
import torch.utils.data.distributed
from PIL import Image
from torchvision.tr... | 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 |
33,941 | from scipy import ndimage
import base64
import math
import re
from io import BytesIO
import matplotlib
import matplotlib.cm
import numpy as np
import requests
import torch
import torch.distributed as dist
import torch.nn
import torch.nn as nn
import torch.utils.data.distributed
from PIL import Image
from torchvision.tr... | Converts a depth map to a color image. Args: value (torch.Tensor, numpy.ndarry): Input depth map. Shape: (H, W) or (1, H, W) or (1, 1, H, W). All singular dimensions are squeezed vmin (float, optional): vmin-valued entries are mapped to start color of cmap. If None, value.min() is used. Defaults to None. vmax (float, o... |
33,944 | from scipy import ndimage
import base64
import math
import re
from io import BytesIO
import matplotlib
import matplotlib.cm
import numpy as np
import requests
import torch
import torch.distributed as dist
import torch.nn
import torch.nn as nn
import torch.utils.data.distributed
from PIL import Image
from torchvision.tr... | null |
33,946 | from scipy import ndimage
import base64
import math
import re
from io import BytesIO
import matplotlib
import matplotlib.cm
import numpy as np
import requests
import torch
import torch.distributed as dist
import torch.nn
import torch.nn as nn
import torch.utils.data.distributed
from PIL import Image
from torchvision.tr... | null |
33,948 | from scipy import ndimage
import base64
import math
import re
from io import BytesIO
import matplotlib
import matplotlib.cm
import numpy as np
import requests
import torch
import torch.distributed as dist
import torch.nn
import torch.nn as nn
import torch.utils.data.distributed
from PIL import Image
from torchvision.tr... | null |
33,949 | import numpy as np
def get_intrinsics(H,W):
"""
Intrinsics for a pinhole camera model.
Assume fov of 55 degrees and central principal point.
"""
f = 0.5 * W / np.tan(0.5 * 55 * np.pi / 180.0)
cx = 0.5 * W
cy = 0.5 * H
return np.array([[f, 0, cx],
[0, f, cy],
... | null |
33,950 | import numpy as np
The provided code snippet includes necessary dependencies for implementing the `create_triangles` function. Write a Python function `def create_triangles(h, w, mask=None)` to solve the following problem:
Reference: https://github.com/google-research/google-research/blob/e96197de06613f1b027d20328e06d... | Reference: https://github.com/google-research/google-research/blob/e96197de06613f1b027d20328e06d69829fa5a89/infinite_nature/render_utils.py#L68 Creates mesh triangle indices from a given pixel grid size. This function is not and need not be differentiable as triangle indices are fixed. Args: h: (int) denoting the heigh... |
33,951 | def infer_type(x):
def parse_unknown(unknown_args):
clean = []
for a in unknown_args:
if "=" in a:
k, v = a.split("=")
clean.extend([k, v])
else:
clean.append(a)
keys = clean[::2]
values = clean[1::2]
return {k.replace("--", ""): infer_type(v) fo... | null |
33,952 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
def smart_resize(x, s):
Ht, Wt = s
if x.ndim == 2:
Ho, Wo = x.shape
Co = 1
else:
Ho, Wo, Co = x.shape
if Co == 3 or Co == 1:
... | null |
33,953 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
def smart_resize_k(x, fx, fy):
if x.ndim == 2:
Ho, Wo = x.shape
Co = 1
else:
Ho, Wo, Co = x.shape
Ht, Wt = Ho * fy, Wo * fx
if Co ==... | null |
33,954 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
def padRightDownCorner(img, stride, padValue):
h = img.shape[0]
w = img.shape[1]
pad = 4 * [None]
pad[0] = 0 # up
pad[1] = 0 # left
pad[2] = 0 if (... | null |
33,955 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
def transfer(model, model_weights):
transfered_model_weights = {}
for weights_name in model.state_dict().keys():
transfered_model_weights[weights_name] = mo... | null |
33,956 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
def is_normalized(keypoints: List[Optional[Keypoint]]) -> bool:
point_normalized = [
0 <= abs(k.x) <= 1 and 0 <= abs(k.y) <= 1
for k in keypoints
... | Draw keypoints and limbs representing body pose on a given canvas. Args: canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the body pose. keypoints (List[Keypoint]): A list of Keypoint objects representing the body keypoints to be drawn. Returns: np.ndarray: A 3D numpy array represe... |
33,957 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
eps = 0.01
def is_normalized(keypoints: List[Optional[Keypoint]]) -> bool:
point_normalized = [
0 <= abs(k.x) <= 1 and 0 <= abs(k.y) <= 1
for k in keypo... | Draw keypoints and connections representing hand pose on a given canvas. Args: canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the hand pose. keypoints (List[Keypoint]| None): A list of Keypoint objects representing the hand keypoints to be drawn or None if no keypoints are presen... |
33,958 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
eps = 0.01
def is_normalized(keypoints: List[Optional[Keypoint]]) -> bool:
point_normalized = [
0 <= abs(k.x) <= 1 and 0 <= abs(k.y) <= 1
for k in keypo... | Draw keypoints representing face pose on a given canvas. Args: canvas (np.ndarray): A 3D numpy array representing the canvas (image) on which to draw the face pose. keypoints (List[Keypoint]| None): A list of Keypoint objects representing the face keypoints to be drawn or None if no keypoints are present. Returns: np.n... |
33,959 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
The provided code snippet includes necessary dependencies for implementing the `handDetect` function. Write a Python function `def handDetect(body: BodyResult, oriImg) -> L... | Detect hands in the input body pose keypoints and calculate the bounding box for each hand. Args: body (BodyResult): A BodyResult object containing the detected body pose keypoints. oriImg (numpy.ndarray): A 3D numpy array representing the original input image. Returns: List[Tuple[int, int, int, bool]]: A list of tuple... |
33,960 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
The provided code snippet includes necessary dependencies for implementing the `faceDetect` function. Write a Python function `def faceDetect(body: BodyResult, oriImg) -> U... | Detect the face in the input body pose keypoints and calculate the bounding box for the face. Args: body (BodyResult): A BodyResult object containing the detected body pose keypoints. oriImg (numpy.ndarray): A 3D numpy array representing the original input image. Returns: Tuple[int, int, int] | None: A tuple containing... |
33,961 | import math
import numpy as np
import matplotlib
import cv2
from typing import List, Tuple, Union, Optional
from .body import BodyResult, Keypoint
def npmax(array):
arrayindex = array.argmax(1)
arrayvalue = array.max(1)
i = arrayvalue.argmax()
j = arrayindex[i]
return i, j | null |
33,962 | from typing import List, Tuple
import cv2
import numpy as np
def preprocess(
img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Do preprocessing for DWPose model inference.
Args:
img (np.ndarray): Input image in shape.
input... | null |
33,964 | import cv2
import numpy as np
def multiclass_nms(boxes, scores, nms_thr, score_thr):
"""Multiclass NMS implemented in Numpy. Class-aware version."""
final_dets = []
num_classes = scores.shape[1]
for cls_ind in range(num_classes):
cls_scores = scores[:, cls_ind]
valid_score_mask = cls_sco... | null |
33,965 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def check_and_warn_input_range(tensor, min_value, max_value, name):
actual_min = tensor.min()
actual_max = tensor.max()
... | null |
33,966 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def sum_dict_with_prefix(target, cur_dict, prefix, default=0):
for k, v in cur_dict.items():
target_key = prefix + k
... | null |
33,967 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def add_prefix_to_keys(dct, prefix):
return {prefix + k: v for k, v in dct.items()} | null |
33,968 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def set_requires_grad(module, value):
for param in module.parameters():
param.requires_grad = value | null |
33,969 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def flatten_dict(dct):
result = {}
for k, v in dct.items():
if isinstance(k, tuple):
k = '_'.join(k)
... | null |
33,970 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
class LinearRamp:
def __init__(self, start_value=0, end_value=1, start_iter=-1, end_iter=0):
self.start_value = start_va... | null |
33,971 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
LOGGER = logging.getLogger(__name__)
def print_traceback_handler(sig, frame):
def register_debug_signal_handlers(sig=None, handler=... | null |
33,972 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def handle_deterministic_config(config):
seed = dict(config).get('seed', None)
if seed is None:
return False
s... | null |
33,973 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def get_shape(t):
if torch.is_tensor(t):
return tuple(t.shape)
elif isinstance(t, dict):
return {n: get_sha... | null |
33,974 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def get_has_ddp_rank():
def handle_ddp_subprocess():
def main_decorator(main_func):
@functools.wraps(main_func)
... | null |
33,975 | import bisect
import functools
import logging
import numbers
import os
import signal
import sys
import traceback
import warnings
import torch
from pytorch_lightning import seed_everything
def get_has_ddp_rank():
master_port = os.environ.get('MASTER_PORT', None)
node_rank = os.environ.get('NODE_RANK', None)
... | null |
33,976 | import collections
from functools import partial
import functools
import logging
from collections import defaultdict
import numpy as np
import torch.nn as nn
from annotator.lama.saicinpainting.training.modules.base import BaseDiscriminator, deconv_factory, get_conv_block_ctor, get_norm_layer, get_activation
from annota... | null |
33,977 | import abc
from typing import Tuple, List
import torch
import torch.nn as nn
from annotator.lama.saicinpainting.training.modules.depthwise_sep_conv import DepthWiseSeperableConv
from annotator.lama.saicinpainting.training.modules.multidilated_conv import MultidilatedConv
class DepthWiseSeperableConv(nn.Module):
de... | null |
33,978 | import abc
from typing import Tuple, List
import torch
import torch.nn as nn
from annotator.lama.saicinpainting.training.modules.depthwise_sep_conv import DepthWiseSeperableConv
from annotator.lama.saicinpainting.training.modules.multidilated_conv import MultidilatedConv
def get_norm_layer(kind='bn'):
if not isins... | null |
33,979 | import abc
from typing import Tuple, List
import torch
import torch.nn as nn
from annotator.lama.saicinpainting.training.modules.depthwise_sep_conv import DepthWiseSeperableConv
from annotator.lama.saicinpainting.training.modules.multidilated_conv import MultidilatedConv
def get_activation(kind='tanh'):
if kind ==... | null |
33,980 | import abc
from typing import Tuple, List
import torch
import torch.nn as nn
from annotator.lama.saicinpainting.training.modules.depthwise_sep_conv import DepthWiseSeperableConv
from annotator.lama.saicinpainting.training.modules.multidilated_conv import MultidilatedConv
class DepthWiseSeperableConv(nn.Module):
de... | null |
33,981 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from annotator.lama.saicinpainting.training.losses.perceptual import IMAGENET_STD, IMAGENET_MEAN
def get_gauss_kernel(kernel_size, width_factor=1):
coords = torch.stack(torch.meshgrid(torch.arange(kernel_size),
... | null |
33,982 | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from annotator.lama.saicinpainting.training.losses.perceptual import IMAGENET_STD, IMAGENET_MEAN
def dummy_distance_weighter(real_img, pred_img, mask):
return mask
class BlurMask(nn.Module):
def __init__(self, kernel_size=5, w... | null |
33,988 | import math
import random
import hashlib
import logging
from enum import Enum
import cv2
import numpy as np
from annotator.lama.saicinpainting.utils import LinearRamp
class DrawMethod(Enum):
LINE = 'line'
CIRCLE = 'circle'
SQUARE = 'square'
def make_random_irregular_mask(shape, max_angle=4, max_len=60, max... | null |
33,989 | import math
import random
import hashlib
import logging
from enum import Enum
import cv2
import numpy as np
from annotator.lama.saicinpainting.utils import LinearRamp
def make_random_rectangle_mask(shape, margin=10, bbox_min_size=30, bbox_max_size=100, min_times=0, max_times=3):
height, width = shape
mask = np... | null |
33,990 | import math
import random
import hashlib
import logging
from enum import Enum
import cv2
import numpy as np
from annotator.lama.saicinpainting.utils import LinearRamp
def make_random_superres_mask(shape, min_step=2, max_step=4, min_width=1, max_width=3):
height, width = shape
mask = np.zeros((height, width), n... | null |
33,991 | import math
import random
import hashlib
import logging
from enum import Enum
import cv2
import numpy as np
from annotator.lama.saicinpainting.utils import LinearRamp
class DumbAreaMaskGenerator:
min_ratio = 0.1
max_ratio = 0.35
default_ratio = 0.225
def __init__(self, is_training):
#Parameters:... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.