id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
3,869
from setuptools import find_packages, setup import os import subprocess import sys import time import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) version_file = 'basicsr/version.py' def get_hash(): def write_version_py(): content ...
null
3,870
from setuptools import find_packages, setup import os import subprocess import sys import time import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) version_file = 'basicsr/version.py' def get_version(): with open(version_file, 'r') ...
null
3,871
from setuptools import find_packages, setup import os import subprocess import sys import time import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) def make_cuda_ext(name, module, sources, sources_cuda=None): if sources_cuda is None...
null
3,872
from setuptools import find_packages, setup import os import subprocess import sys import time import torch from torch.utils.cpp_extension import (BuildExtension, CppExtension, CUDAExtension) def get_requirements(filename='requirements.txt'): return [] here = os.path.dirn...
null
3,873
import argparse import datetime import logging import math import random import time import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.data.data_sampler import EnlargedSampler from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher from ba...
null
3,874
import argparse import datetime import logging import math import random import time import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.data.data_sampler import EnlargedSampler from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher from ba...
null
3,875
import argparse import datetime import logging import math import random import time import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.data.data_sampler import EnlargedSampler from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher from ba...
null
3,876
import cv2 import math import numpy as np from scipy.ndimage.filters import convolve from scipy.special import gamma from basicsr.metrics.metric_util import reorder_image, to_y_channel def niqe(img, mu_pris_param, cov_pris_param, gaussian_window, block_size_h=96, block_size_...
Calculate NIQE (Natural Image Quality Evaluator) metric. Ref: Making a "Completely Blind" Image Quality Analyzer. This implementation could produce almost the same results as the official MATLAB codes: http://live.ece.utexas.edu/research/quality/niqe_release.zip We use the official params estimated from the pristine da...
3,877
import numpy as np import torch import torch.nn as nn from scipy import linalg from tqdm import tqdm from basicsr.models.archs.inception import InceptionV3 def load_patched_inception_v3(device='cuda', resize_input=True, normalize_input=False): # we may no...
null
3,878
import numpy as np import torch import torch.nn as nn from scipy import linalg from tqdm import tqdm from basicsr.models.archs.inception import InceptionV3 The provided code snippet includes necessary dependencies for implementing the `extract_inception_features` function. Write a Python function `def extract_inceptio...
Extract inception features. Args: data_generator (generator): A data generator. inception (nn.Module): Inception model. len_generator (int): Length of the data_generator to show the progressbar. Default: None. device (str): Device. Default: cuda. Returns: Tensor: Extracted features.
3,879
import numpy as np import torch import torch.nn as nn from scipy import linalg from tqdm import tqdm from basicsr.models.archs.inception import InceptionV3 The provided code snippet includes necessary dependencies for implementing the `calculate_fid` function. Write a Python function `def calculate_fid(mu1, sigma1, mu...
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. Args: mu1 (np.array): The sample mean over activations. sigma1 (np.array):...
3,880
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel from skimage.metrics import structural_similarity import torch def calculate_psnr(img1, img2, crop_border, input_order='HWC', test_y_channel=False...
null
3,881
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel from skimage.metrics import structural_similarity import torch def prepare_for_ssim(img, k): import torch with torch.no_grad(): img = torch.from_numpy(img).unsqueeze(0).unsqueeze(0).float() conv = ...
null
3,882
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel from skimage.metrics import structural_similarity import torch def prepare_for_ssim_rgb(img, k): import torch with torch.no_grad(): img = torch.from_numpy(img).float() #HxWx3 conv = torch.nn.Conv2...
null
3,883
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel from skimage.metrics import structural_similarity import torch def calculate_ssim(img1, img2, crop_border, input_order='HWC', test_y_channel=False...
null
3,884
import cv2 import numpy as np from basicsr.metrics.metric_util import reorder_image, to_y_channel from skimage.metrics import structural_similarity import torch def calculate_skimage_ssim(img1, img2): return structural_similarity(img1, img2, multichannel=True) def calculate_skimage_ssim_left(img1, img2): img1 ...
null
3,885
import cv2 import random from cv2 import rotate import numpy as np The provided code snippet includes necessary dependencies for implementing the `paired_random_crop` function. Write a Python function `def paired_random_crop(img_gts, img_lqs, gt_patch_size, scale, gt_path)` to solve the following problem: Paired rando...
Paired random crop. It crops lists of lq and gt images with corresponding locations. Args: img_gts (list[ndarray] | ndarray): GT images. Note that all images should have the same shape. If the input is an ndarray, it will be transformed to a list containing itself. img_lqs (list[ndarray] | ndarray): LQ images. Note tha...
3,886
import cv2 import random from cv2 import rotate import numpy as np The provided code snippet includes necessary dependencies for implementing the `paired_random_crop_hw` function. Write a Python function `def paired_random_crop_hw(img_gts, img_lqs, gt_patch_size_h, gt_patch_size_w, scale, gt_path)` to solve the follow...
Paired random crop. It crops lists of lq and gt images with corresponding locations. Args: img_gts (list[ndarray] | ndarray): GT images. Note that all images should have the same shape. If the input is an ndarray, it will be transformed to a list containing itself. img_lqs (list[ndarray] | ndarray): LQ images. Note tha...
3,887
import cv2 import random from cv2 import rotate import numpy as np The provided code snippet includes necessary dependencies for implementing the `augment` function. Write a Python function `def augment(imgs, hflip=True, rotation=True, flows=None, return_status=False, vflip=False)` to solve the following problem: Augm...
Augment: horizontal flips OR rotate (0, 90, 180, 270 degrees). We use vertical flip and transpose for rotation implementation. All the images in the list use the same augmentation. Args: imgs (list[ndarray] | ndarray): Images to be augmented. If the input is an ndarray, it will be transformed to a list. hflip (bool): H...
3,888
import cv2 import random from cv2 import rotate import numpy as np The provided code snippet includes necessary dependencies for implementing the `img_rotate` function. Write a Python function `def img_rotate(img, angle, center=None, scale=1.0)` to solve the following problem: Rotate image. Args: img (ndarray): Image ...
Rotate image. Args: img (ndarray): Image to be rotated. angle (float): Rotation angle in degrees. Positive values mean counter-clockwise rotation. center (tuple[int]): Rotation center. If the center is None, initialize it as the center of the image. Default: None. scale (float): Isotropic scale factor. Default: 1.0.
3,889
import cv2 import numpy as np import torch from os import path as osp from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir def mod_crop(img, scale): """Mod crop images, used during testing. Args: img (ndarray): Input image. ...
Read a sequence of images from a given folder path. Args: path (list[str] | str): List of image paths or image folder path. require_mod_crop (bool): Require mod crop for each image. Default: False. scale (int): Scale factor for mod_crop. Default: 1. Returns: Tensor: size (t, c, h, w), RGB, [0, 1].
3,891
import cv2 import numpy as np import torch from os import path as osp from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_lmdb` function. Write a...
Generate paired paths from lmdb files. Contents of lmdb. Taking the `lq.lmdb` for example, the file structure is: lq.lmdb ├── data.mdb ├── lock.mdb ├── meta_info.txt The data.mdb and lock.mdb are standard lmdb files and you can refer to https://lmdb.readthedocs.io/en/release/ for more details. The meta_info.txt is a sp...
3,892
import cv2 import numpy as np import torch from os import path as osp from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_meta_info_file` functio...
Generate paired paths from an meta information file. Each line in the meta information file contains the image names and image shape (usually for gt), separated by a white space. Example of an meta information file: ``` 0001_s001.png (480,480,3) 0001_s002.png (480,480,3) ``` Args: folders (list[str]): A list of folder ...
3,893
import cv2 import numpy as np import torch from os import path as osp from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir The provided code snippet includes necessary dependencies for implementing the `paired_paths_from_folder` function. Write...
Generate paired paths from folders. Args: folders (list[str]): A list of folder path. The order of list should be [input_folder, gt_folder]. keys (list[str]): A list of keys identifying folders. The order should be in consistent with folders, e.g., ['lq', 'gt']. filename_tmpl (str): Template for each filename. Note tha...
3,896
import cv2 import numpy as np import torch from os import path as osp from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir def generate_gaussian_kernel(kernel_size=13, sigma=1.6): """Generate Gaussian kernel used in `duf_downsample`. Arg...
Downsamping with Gaussian kernel used in the DUF official code. Args: x (Tensor): Frames to be downsampled, with shape (b, t, c, h, w). kernel_size (int): Kernel size. Default: 13. scale (int): Downsampling factor. Supported scale: (2, 3, 4). Default: 4. Returns: Tensor: DUF downsampled frames.
3,897
import functools from torch.nn import functional as F def weight_reduce_loss(loss, weight=None, reduction='mean'): """Apply element-wise weight and reduce loss. Args: loss (Tensor): Element-wise loss. weight (Tensor): Element-wise weights. Default: None. reduction (str): Same as built-in...
Create a weighted version of a given loss function. To use this decorator, the loss function must have the signature like `loss_func(pred, target, **kwargs)`. The function only needs to compute element-wise loss without any reduction. This decorator will add weight and reduction arguments to the function. The decorated...
3,898
import torch from torch import nn as nn from torch.nn import functional as F import numpy as np from basicsr.models.losses.loss_util import weighted_loss def l1_loss(pred, target): return F.l1_loss(pred, target, reduction='none')
null
3,899
import torch from torch import nn as nn from torch.nn import functional as F import numpy as np from basicsr.models.losses.loss_util import weighted_loss def mse_loss(pred, target): return F.mse_loss(pred, target, reduction='none')
null
3,900
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class AvgPool2d(nn.Module): def __init__(self, kernel_size=None, base_size=None, auto_pad=True, fast_imp=False, train_size=None): super().__init__() self.kernel_size = kernel_size self.base_size = base_size...
null
3,901
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger import time The provided code snippet includes necessary dependencies for implementing the `default_init...
Initialize network weights. Args: module_list (list[nn.Module] | nn.Module): Modules to be initialized. scale (float): Scale initialized weights, especially for residual blocks. Default: 1. bias_fill (float): The value to fill bias. Default: 0 kwargs (dict): Other arguments for initialization function.
3,902
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger import time The provided code snippet includes necessary dependencies for implementing the `make_layer` ...
Make layers by stacking the same blocks. Args: basic_block (nn.module): nn.module class for basic block. num_basic_block (int): number of blocks. Returns: nn.Sequential: Stacked blocks in nn.Sequential.
3,903
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger import time The provided code snippet includes necessary dependencies for implementing the `flow_warp` f...
Warp an image or feature map with optical flow. Args: x (Tensor): Tensor with size (n, c, h, w). flow (Tensor): Tensor with size (n, h, w, 2), normal value. interp_mode (str): 'nearest' or 'bilinear'. Default: 'bilinear'. padding_mode (str): 'zeros' or 'border' or 'reflection'. Default: 'zeros'. align_corners (bool): B...
3,904
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger import time The provided code snippet includes necessary dependencies for implementing the `resize_flow`...
Resize a flow according to ratio or shape. Args: flow (Tensor): Precomputed flow. shape [N, 2, H, W]. size_type (str): 'ratio' or 'shape'. sizes (list[int | float]): the ratio for resizing or the final output shape. 1) The order of ratio should be [ratio_h, ratio_w]. For downsampling, the ratio should be smaller than 1...
3,905
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger import time The provided code snippet includes necessary dependencies for implementing the `pixel_unshuf...
Pixel unshuffle. Args: x (Tensor): Input feature with shape (b, c, hh, hw). scale (int): Downsample ratio. Returns: Tensor: the pixel unshuffled feature.
3,906
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger import time def measure_inference_speed(model, data, max_iter=200, log_interval=50): model.eval() ...
null
3,909
import math import requests from tqdm import tqdm from .misc import sizeof_fmt def get_confirm_token(response): for key, value in response.cookies.items(): if key.startswith('download_warning'): return value return None def save_response_content(response, destinatio...
Download files from google drive. Ref: https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive # noqa E501 Args: file_id (str): File id. save_path (str): Save path.
3,910
import math import numpy as np import torch def calculate_weights_indices(in_length, out_length, scale, kernel, kernel_width, antialiasing): """Calculate weights and indices, used for imresize function. Args: in_length (int): Input length. out_length (int): Output l...
imresize function same as MATLAB. It now only supports bicubic. The same scale applies for both height and width. Args: img (Tensor | Numpy array): Tensor: Input image with shape (c, h, w), [0, 1] range. Numpy: Input image with shape (h, w, c), [0, 1] range. scale (float): Scale factor. The same scale applies for both ...
3,911
import math import numpy as np import torch def _convert_input_type_range(img): """Convert the type and range of the input image. It converts the input image to np.float32 type and range of [0, 1]. It is mainly used for pre-processing the input image in colorspace convertion functions such as rgb2ycbcr ...
Convert a RGB image to YCbCr image. This function produces the same results as Matlab's `rgb2ycbcr` function. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor:...
3,912
import math import numpy as np import torch def _convert_input_type_range(img): """Convert the type and range of the input image. It converts the input image to np.float32 type and range of [0, 1]. It is mainly used for pre-processing the input image in colorspace convertion functions such as rgb2ycbcr ...
Convert a YCbCr image to RGB image. This function produces the same results as Matlab's ycbcr2rgb function. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `...
3,913
import math import numpy as np import torch def _convert_input_type_range(img): """Convert the type and range of the input image. It converts the input image to np.float32 type and range of [0, 1]. It is mainly used for pre-processing the input image in colorspace convertion functions such as rgb2ycbcr ...
Convert a YCbCr image to BGR image. The bgr version of ycbcr2rgb. It implements the ITU-R BT.601 conversion for standard-definition television. See more details in https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion. It differs from a similar function in cv2.cvtColor: `YCrCb <-> BGR`. In OpenCV, it implements a...
3,914
import argparse from os import path as osp from basicsr.utils import scandir from basicsr.utils.lmdb_util import make_lmdb_from_imgs def prepare_keys(folder_path, suffix='png'): def make_lmdb_from_imgs(data_path, lmdb_path, img_path_list, keys, ...
null
3,915
import argparse from os import path as osp from basicsr.utils import scandir from basicsr.utils.lmdb_util import make_lmdb_from_imgs def prepare_keys(folder_path, suffix='png'): """Prepare image path list and keys for DIV2K dataset. Args: folder_path (str): Folder path. Returns: list[str]: I...
null
3,916
import argparse from os import path as osp from basicsr.utils import scandir from basicsr.utils.lmdb_util import make_lmdb_from_imgs def prepare_keys(folder_path, suffix='png'): """Prepare image path list and keys for DIV2K dataset. Args: folder_path (str): Folder path. Returns: list[str]: I...
null
3,917
import argparse from os import path as osp from basicsr.utils import scandir from basicsr.utils.lmdb_util import make_lmdb_from_imgs def prepare_keys(folder_path, suffix='png'): """Prepare image path list and keys for DIV2K dataset. Args: folder_path (str): Folder path. Returns: list[str]: I...
folder_path = './datasets/SIDD/val/input_crops' lmdb_path = './datasets/SIDD/val/input_crops.lmdb' mat_path = './datasets/SIDD/ValidationNoisyBlocksSrgb.mat' if not osp.exists(folder_path): os.makedirs(folder_path) assert osp.exists(mat_path) data = scio.loadmat(mat_path)['ValidationNoisyBlocksSrgb'] N, B, H ,W, C = da...
3,918
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid The provided code snippet includes necessary dependencies for implementing the `img2tensor` function. Write a Python function `def img2tensor(imgs, bgr2rgb=True, float32=True)` to solve the following problem: Numpy...
Numpy array to tensor. Args: imgs (list[ndarray] | ndarray): Input images. bgr2rgb (bool): Whether to change bgr to rgb. float32 (bool): Whether to change to float32. Returns: list[tensor] | tensor: Tensor images. If returned results only have one element, just return tensor.
3,919
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid The provided code snippet includes necessary dependencies for implementing the `tensor2img` function. Write a Python function `def tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1))` to solve the f...
Convert torch Tensors into image numpy arrays. After clamping to [min, max], values will be normalized to [0, 1]. Args: tensor (Tensor or list[Tensor]): Accept shapes: 1) 4D mini-batch Tensor of shape (B x 3/1 x H x W); 2) 3D Tensor of shape (3/1 x H x W); 3) 2D Tensor of shape (H x W). Tensor channel should be in RGB ...
3,920
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid The provided code snippet includes necessary dependencies for implementing the `imfrombytes` function. Write a Python function `def imfrombytes(content, flag='color', float32=False)` to solve the following problem:...
Read an image from bytes. Args: content (bytes): Image bytes got from files or other streams. flag (str): Flags specifying the color type of a loaded image, candidates are `color`, `grayscale` and `unchanged`. float32 (bool): Whether to change to float32., If True, will also norm to [0, 1]. Default: False. Returns: nda...
3,921
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid def padding(img_lq, img_gt, gt_size): h, w, _ = img_lq.shape h_pad = max(0, gt_size - h) w_pad = max(0, gt_size - w) if h_pad == 0 and w_pad == 0: return img_lq, img_gt img_lq = c...
null
3,922
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid The provided code snippet includes necessary dependencies for implementing the `imwrite` function. Write a Python function `def imwrite(img, file_path, params=None, auto_mkdir=True)` to solve the following problem:...
Write image to file. Args: img (ndarray): Image array to be written. file_path (str): Image file path. params (None or list): Same as opencv's :func:`imwrite` interface. auto_mkdir (bool): If the parent folder of `file_path` does not exist, whether to create it automatically. Returns: bool: Successful or not.
3,923
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid The provided code snippet includes necessary dependencies for implementing the `crop_border` function. Write a Python function `def crop_border(imgs, crop_border)` to solve the following problem: Crop borders of im...
Crop borders of images. Args: imgs (list[ndarray] | ndarray): Images with shape (h, w, c). crop_border (int): Crop border for each end of height and weight. Returns: list[ndarray]: Cropped images.
3,924
import numpy as np import os import random import time import torch from os import path as osp from .dist_util import master_only from .logger import get_root_logger The provided code snippet includes necessary dependencies for implementing the `set_random_seed` function. Write a Python function `def set_random_seed(s...
Set random seeds.
3,925
import numpy as np import os import random import time import torch from os import path as osp from .dist_util import master_only from .logger import get_root_logger def mkdir_and_rename(path): """mkdirs. If path exists, rename it with timestamp and create a new one. Args: path (str): Folder path. "...
Make dirs for experiments.
3,926
import numpy as np import os import random import time import torch from os import path as osp from .dist_util import master_only from .logger import get_root_logger def scandir(dir_path, suffix=None, recursive=False, full_path=False): """Scan a directory to find the interested files. Args: dir_path (st...
Scan a directory to find the interested files. Args: dir_path (str): Path of the directory. keywords (str | tuple(str), optional): File keywords that we are interested in. Default: None. recursive (bool, optional): If set to True, recursively scan the directory. Default: False. full_path (bool, optional): If set to Tru...
3,927
import numpy as np import os import random import time import torch from os import path as osp from .dist_util import master_only from .logger import get_root_logger def get_root_logger(logger_name='basicsr', log_level=logging.INFO, log_file=None): """Get the root logger. ...
Check resume states and pretrain_network paths. Args: opt (dict): Options. resume_iter (int): Resume iteration.
3,928
import cv2 import numpy as np import os def dequantize_flow(dx, dy, max_val=0.02, denorm=True): """Recover from quantized flow. Args: dx (ndarray): Quantized dx. dy (ndarray): Quantized dy. max_val (float): Maximum value used when quantizing. denorm (bool): Whether to multiply fl...
Read an optical flow map. Args: flow_path (ndarray or str): Flow path. quantize (bool): whether to read quantized pair, if set to True, remaining args will be passed to :func:`dequantize_flow`. concat_axis (int): The axis that dx and dy are concatenated, can be either 0 or 1. Ignored if quantize is False. Returns: ndar...
3,929
import cv2 import numpy as np import os def quantize_flow(flow, max_val=0.02, norm=True): """Quantize flow to [0, 255]. After this step, the size of flow will be much smaller, and can be dumped as jpeg images. Args: flow (ndarray): (h, w, 2) array of optical flow. max_val (float): Maximu...
Write optical flow to file. If the flow is not quantized, it will be saved as a .flo file losslessly, otherwise a jpeg image which is lossy but of much smaller size. (dx and dy will be concatenated horizontally into a single image if quantize is True.) Args: flow (ndarray): (h, w, 2) array of optical flow. filename (st...
3,931
import datetime import logging import time from .dist_util import get_dist_info, master_only The provided code snippet includes necessary dependencies for implementing the `init_wandb_logger` function. Write a Python function `def init_wandb_logger(opt)` to solve the following problem: We now only use wandb to sync te...
We now only use wandb to sync tensorboard log.
3,932
import datetime import logging import time from .dist_util import get_dist_info, master_only __version__ = '1.2.0+386ca20' The provided code snippet includes necessary dependencies for implementing the `get_env_info` function. Write a Python function `def get_env_info()` to solve the following problem: Get environmen...
Get environment information. Currently, only log the software version.
3,933
import torch from basicsr.models import create_model from basicsr.utils import FileClient, imfrombytes, img2tensor, padding, tensor2img, imwrite, set_random_seed import argparse from basicsr.utils.options import dict2str, parse from basicsr.utils.dist_util import get_dist_info, init_dist import random def parse(opt_pa...
null
3,934
import torch from basicsr.models import create_model from basicsr.utils import FileClient, imfrombytes, img2tensor, padding, tensor2img, imwrite, set_random_seed import argparse from basicsr.utils.options import dict2str, parse from basicsr.utils.dist_util import get_dist_info, init_dist import random def imread(img_p...
null
3,935
import torch import numpy as np import cv2 import tempfile import matplotlib.pyplot as plt from cog import BasePredictor, Path, Input, BaseModel from basicsr.models import create_model from basicsr.utils import img2tensor as _img2tensor, tensor2img, imwrite from basicsr.utils.options import parse def imread(img_path):...
null
3,936
import torch import numpy as np import cv2 import tempfile import matplotlib.pyplot as plt from cog import BasePredictor, Path, Input, BaseModel from basicsr.models import create_model from basicsr.utils import img2tensor as _img2tensor, tensor2img, imwrite from basicsr.utils.options import parse def img2tensor(img, b...
null
3,937
import torch import numpy as np import cv2 import tempfile import matplotlib.pyplot as plt from cog import BasePredictor, Path, Input, BaseModel from basicsr.models import create_model from basicsr.utils import img2tensor as _img2tensor, tensor2img, imwrite from basicsr.utils.options import parse def single_image_infe...
null
3,938
import torch import numpy as np import cv2 import tempfile import matplotlib.pyplot as plt from cog import BasePredictor, Path, Input, BaseModel from basicsr.models import create_model from basicsr.utils import img2tensor as _img2tensor, tensor2img, imwrite from basicsr.utils.options import parse def stereo_image_infe...
null
3,939
import cv2 import numpy as np import os import sys from multiprocessing import Pool from os import path as osp from tqdm import tqdm from basicsr.utils import scandir_SIDD from basicsr.utils.create_lmdb import create_lmdb_for_SIDD def worker(path, opt): """Worker for each process. Args: path (str): Imag...
Crop images to subimages. Args: opt (dict): Configuration dict. It contains: input_folder (str): Path to the input folder. save_folder (str): Path to save folder. n_thread (int): Thread number.
3,940
import cv2 import numpy as np import os import sys from multiprocessing import Pool from os import path as osp from tqdm import tqdm from basicsr.utils import scandir from basicsr.utils.create_lmdb import create_lmdb_for_gopro def worker(path, opt): """Worker for each process. Args: path (str): Image pa...
Crop images to subimages. Args: opt (dict): Configuration dict. It contains: input_folder (str): Path to the input folder. save_folder (str): Path to save folder. n_thread (int): Thread number.
3,941
import os import time from basicsr.utils.create_lmdb import create_lmdb_for_reds def make_val_300(folder, dst): if not os.path.exists(dst): os.mkdir(dst) templates = '*9.*' cp_command = 'cp {} {}'.format(os.path.join(folder, templates), dst) os.system(cp_command)
null
3,942
import os import time from basicsr.utils.create_lmdb import create_lmdb_for_reds def flatten_folders(folder): for vid in range(300): vidfolder_path = '{:03}'.format(vid) if not os.path.exists(os.path.join(folder, vidfolder_path)): continue print('working on .. {} .. {}'.format...
null
3,943
from datetime import datetime import time import requests import sys import json from azure.identity import AzureCliCredential import logging from azure.ai.ml import MLClient from sseclient import SSEClient logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) logger.addHandler(handler) def apply_delta(ba...
null
3,944
import os import re from io import open from typing import Any, List, Match, cast from setuptools import find_namespace_packages, setup with open(os.path.join(PACKAGE_FOLDER_PATH, "version.txt"), "r") as fd: version_content = fd.read() print(version_content) version = cast(Match[Any], re.search(r'^VERSION\s...
null
3,945
from openai import OpenAIError from promptflow.exceptions import ErrorTarget, SystemErrorException, UserErrorException openai_error_code_ref_message = "Error reference: https://platform.openai.com/docs/guides/error-codes/api-errors" def to_openai_error_message(e: Exception) -> str: ex_type = type(e).__name__ e...
null
3,946
from enum import Enum from typing import Union from promptflow.tools.common import handle_openai_error, init_openai_client, init_azure_openai_client from promptflow.tools.exception import InvalidConnectionType from promptflow._internal import tool from promptflow.connections import AzureOpenAIConnection, OpenAIConnecti...
null
3,947
from enum import Enum from typing import Dict, List, Union import json import requests from promptflow import tool, ToolProvider from promptflow.connections import AzureContentSafetyConnection from promptflow.tools.exception import AzureContentSafetyInputValueError, AzureContentSafetySystemError class TextCategorySensi...
null
3,948
from enum import Enum from typing import Dict, List, Union import json import requests from promptflow import tool, ToolProvider from promptflow.connections import AzureContentSafetyConnection from promptflow.tools.exception import AzureContentSafetyInputValueError, AzureContentSafetySystemError class TextCategorySensi...
null
3,949
from enum import Enum from typing import Dict, List, Union import json import requests from promptflow import tool, ToolProvider from promptflow.connections import AzureContentSafetyConnection from promptflow.tools.exception import AzureContentSafetyInputValueError, AzureContentSafetySystemError class Decision(object):...
null
3,950
from enum import Enum from promptflow.tools.common import render_jinja_template, handle_openai_error, \ parse_chat, to_bool, validate_functions, process_function_call, \ post_process_chat_api_response, init_openai_client from promptflow._internal import ToolProvider, tool, register_apis from promptflow.connecti...
null
3,951
from enum import Enum from promptflow.tools.common import render_jinja_template, handle_openai_error, \ parse_chat, to_bool, validate_functions, process_function_call, \ post_process_chat_api_response, init_openai_client from promptflow._internal import ToolProvider, tool, register_apis from promptflow.connecti...
null
3,952
import json from promptflow.tools.common import render_jinja_template, handle_openai_error, parse_chat, to_bool, \ validate_functions, process_function_call, post_process_chat_api_response, init_azure_openai_client from promptflow._internal import enable_cache, ToolProvider, tool, register_apis from promptflow.conn...
null
3,953
import json from promptflow.tools.common import render_jinja_template, handle_openai_error, parse_chat, to_bool, \ validate_functions, process_function_call, post_process_chat_api_response, init_azure_openai_client from promptflow._internal import enable_cache, ToolProvider, tool, register_apis from promptflow.conn...
null
3,954
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,955
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,956
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,957
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,958
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,959
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,960
import functools import json import os import re import requests import sys import time import tempfile from abc import abstractmethod from datetime import datetime, timedelta from enum import Enum from typing import Any, Dict, List, Tuple, Optional, Union from promptflow._core.tool import ToolProvider, tool from promp...
null
3,961
from typing import List, Dict from promptflow.tools.common import render_jinja_template, handle_openai_error, parse_chat, \ preprocess_template_string, find_referenced_image_set, convert_to_chat_list, init_azure_openai_client, \ post_process_chat_api_response, list_deployment_connections, build_deployment_dict,...
null
3,962
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,963
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,964
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
A decorator function that used to handle OpenAI error. OpenAI Error falls into retriable vs non-retriable ones. For retriable error, the decorator use below parameters to control its retry activity with exponential backoff: `tries` : max times for the function invocation, type is int 'delay': base delay seconds for exp...
3,965
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,966
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,967
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,968
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
Remove the image input decorator from the template string and place the image input in a new line.
3,969
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,970
import functools import json import os import re import sys import time from typing import List, Mapping from jinja2 import Template from openai import APIConnectionError, APIStatusError, OpenAIError, RateLimitError, APITimeoutError, BadRequestError from promptflow.tools.exception import ChatAPIInvalidRole, WrappedOpen...
null
3,971
import json import sys from enum import Enum import requests from promptflow._internal import ToolProvider, tool from promptflow.connections import SerpConnection from promptflow.exceptions import PromptflowException from promptflow.tools.exception import SerpAPIUserError, SerpAPISystemError class SafeMode(str, Enum): ...
null
3,972
from pathlib import Path from ruamel.yaml import YAML def collect_tools_from_directory(base_dir) -> dict: tools = {} yaml = YAML() for f in Path(base_dir).glob("**/*.yaml"): with open(f, "r") as f: tools_in_file = yaml.load(f) for identifier, tool in tools_in_file.items(): ...
List package tools
3,973
from promptflow._internal import tool from promptflow.tools.common import render_jinja_template def render_jinja_template(prompt, trim_blocks=True, keep_trailing_newline=True, **kwargs): try: return Template(prompt, trim_blocks=trim_blocks, keep_trailing_newline=keep_trailing_newline).render(**kwargs) ...
null
3,974
from dataclasses import dataclass from datetime import datetime from itertools import chain from typing import Any, List, Mapping from promptflow._utils.exception_utils import ExceptionPresenter, RootErrorCode from promptflow._utils.openai_metrics_calculator import OpenAIMetricsCalculator from promptflow.contracts.run_...
null