code stringlengths 17 6.64M |
|---|
@pytest.mark.unit
@pytest.mark.convert
def test_filter_on_extension_with_predicate():
'Test convert.filter_on_extension with a predicate argument'
test_files = ['file_one.fits', 'file_two.fits', 'file_three.exclude']
extensions = ['fits']
expected_list = test_files[:1]
predicate = (lambda f: (f ==... |
@pytest.mark.unit
@pytest.mark.convert
def test_make_dirs():
'Test convert.make_dirs'
helpers.setup()
out_dir = helpers.TEST_PATH
expected_dirs = set(list(map((lambda f: os.path.join(out_dir, f)), ['0/0', '1/0', '1/1', '2/0', '2/1', '2/2', '2/3'])))
convert.make_dirs(out_dir, 0, 2)
dirs_exists... |
@pytest.mark.unit
@pytest.mark.convert
def test_get_zoom_range():
'Test convert.get_zoom_range'
in_shape = [10000, 10000]
tile_size = [256, 256]
expected_min = 0
expected_max = 5
(actual_min, acutal_max) = convert.get_zoom_range(in_shape, tile_size)
assert (expected_min == actual_min)
... |
@pytest.mark.unit
@pytest.mark.convert
def test_get_total_tiles():
'Test convert.get_total_tiles'
(min_zoom, max_zoom) = (0, 2)
expected_number = 21
actual_number = convert.get_total_tiles(min_zoom, max_zoom)
assert (expected_number == actual_number)
|
@pytest.mark.unit
@pytest.mark.convert
def test_imread_default():
'Test convert.imread_default() with valid path'
helpers.setup(with_data=True)
test_file = os.path.join(helpers.TEST_PATH, 'test_tiling_image.jpg')
expected_array = np.flipud(Image.open(test_file))
empty_array = np.zeros([256, 256])
... |
@pytest.mark.unit
@pytest.mark.convert
def test_imread_default_invalid_path():
'Test convert.imread_default() with valid path'
helpers.setup(with_data=True)
test_file = os.path.join(helpers.TEST_PATH, 'doesnt_exist.jpg')
empty_array = np.zeros([256, 256])
actual_array = convert.imread_default(test... |
@pytest.mark.unit
@pytest.mark.convert
def test_get_map_layer_name():
'Test convert.get_map_layer_name'
test_file_name = './test/test_file.png'
expected_layer_name = 'test_file'
actual_layer_name = convert.get_map_layer_name(test_file_name)
assert (expected_layer_name == actual_layer_name)
|
@pytest.mark.unit
@pytest.mark.convert
def test_get_marker_file_name():
'Test convert.get_marker_file_names'
test_file_name = './test/test_file.cat'
expected_marker_file_name = 'test_file.cat.js'
actual_marker_file_name = convert.get_marker_file_name(test_file_name)
assert (expected_marker_file_na... |
@pytest.mark.unit
@pytest.mark.convert
def test_line_to_cols():
'Test convert.line_to_cols'
line = ['ID', 'RA', 'dec', 'test1', 'test2']
actual_cols = convert.line_to_cols(line)
expected_cols = line
expected_cols[0] = 'id'
expected_cols[1] = 'ra'
assert (expected_cols == actual_cols)
|
@pytest.mark.unit
@pytest.mark.convert
def test_line_to_cols_with_hash():
'Test convert.line_to_cols'
line = ['#', 'ID', 'RA', 'dec', 'test1', 'test2']
actual_cols = convert.line_to_cols(line)
expected_cols = line[1:]
expected_cols[0] = 'id'
expected_cols[1] = 'ra'
assert (expected_cols ==... |
@pytest.mark.unit
@pytest.mark.convert
def test_line_to_json_xy():
'Test convert.line_to_json with x/y'
helpers.setup()
in_wcs = None
columns = ['id', 'x', 'y', 'col1', 'col2']
catalog_assets_path = os.path.join(helpers.TEST_PATH, 'catalog_assets')
os.mkdir(catalog_assets_path)
in_line = [... |
@pytest.mark.unit
@pytest.mark.convert
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_line_to_json_ra_dec():
'Test convert.line_to_json with ra/dec'
helpers.setup(with_data=True)
in_wcs = WCS(fits.getheader(os.path.join(helpers.TEST_PATH, 'test_image.fits')))
co... |
@pytest.mark.unit
@pytest.mark.convert
def test_tile_img_pil_serial():
'Test convert.tile_img'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
out_dir = helpers.TEST_PATH
test_image = os.path.join(out_dir, 'test_tiling_image.jpg')
pbar_ref = [0, queue.Queue()]
convert.tile_img(test_im... |
@pytest.mark.unit
@pytest.mark.convert
def test_tile_img_pil_serial_png_from_tiff():
'Test convert.tile_img using a converted TIFF->PNG image, has only 2 dims'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
out_dir = helpers.TEST_PATH
test_image = os.path.join(out_dir, 'test_png_from_tiff.pn... |
@pytest.mark.unit
@pytest.mark.convert
def test_tile_img_mpl_fits_serial():
'Test convmax_percentert.tile_img'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
out_dir = helpers.TEST_PATH
test_image = os.path.join(out_dir, 'test_img_for_map.fits')
pbar_ref = [0, queue.Queue()]
convert.... |
@pytest.mark.unit
@pytest.mark.convert
def test_tile_img_mpl_fits_serial_with_fname_kwargs():
'Test convmax_percentert.tile_img'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
out_dir = helpers.TEST_PATH
test_image = os.path.join(out_dir, 'test_img_for_map.fits')
pbar_ref = [0, queue.Que... |
def test_simplify_mixed_ws():
'Test convert._simplify_mixed_ws'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
test_lines = ['a b c\n', 'test\tdata stuff\n', 'to test\tstuff\n']
out_file = os.path.join(helpers.DATA_DIR, 'test.cat')
with open(out_file, 'w') as f:
f.writeline... |
@pytest.mark.unit
@pytest.mark.convert
def test_tile_img_pil_parallel():
'Test convert.tile_img'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
out_dir = helpers.TEST_PATH
test_image = os.path.join(out_dir, 'test_tiling_image.jpg')
pbar_ref = [0, queue.Queue()]
convert.tile_img(test_... |
@pytest.mark.unit
@pytest.mark.convert
def test_tile_img_mpl_parallel():
'Test convert.tile_img'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
out_dir = helpers.TEST_PATH
test_image = os.path.join(out_dir, 'test_img_for_map.fits')
pbar_ref = [0, queue.Queue()]
convert.tile_img(test_... |
@pytest.mark.unit
@pytest.mark.convert
@pytest.mark.skipif(condition=(not sys.platform.startswith('linux')), reason='temp fix, need osx/windows artififacts for cbor/pbf files')
def test_version_not_hard_coded():
'Tests that the version in the testing artifacts is not hard coded'
helpers.disbale_tqdm()
hel... |
@pytest.mark.integration
@pytest.mark.convert
@pytest.mark.skipif(condition=(not sys.platform.startswith('linux')), reason='temp fix, need osx/windows artififacts for cbor/pbf files')
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_files_to_map():
'Integration test for makin... |
@pytest.mark.integration
@pytest.mark.convert
@pytest.mark.skipif(condition=(not sys.platform.startswith('linux')), reason='temp fix, need osx/windows artififacts for cbor/pbf files')
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_files_to_map_ellipse_markers():
'Integratio... |
@pytest.mark.integration
@pytest.mark.convert
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_files_to_map_fails_file_not_found():
'Integration test for making files into map'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
with_path = (lambda f: os.path.joi... |
@pytest.mark.integration
@pytest.mark.convert
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_dir_to_map_fails_no_files():
'Integration test for making files into map'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
with_path = (lambda f: os.path.join(helper... |
@pytest.mark.integration
@pytest.mark.convert
@pytest.mark.skipif(condition=(not sys.platform.startswith('linux')), reason='temp fix, need osx/windows artififacts for cbor/pbf files')
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_dir_to_map():
'Integration test for making ... |
@pytest.mark.integration
@pytest.mark.convert
@pytest.mark.filterwarnings('ignore:.*:astropy.io.fits.verify.VerifyWarning')
def test_dir_to_map_no_markers():
'Integration test for making files into map'
helpers.disbale_tqdm()
helpers.setup(with_data=True)
with_path = (lambda f: os.path.join(helpers.TE... |
@pytest.mark.unit
def test_build_digit_to_string():
'test cartographer.build_digit_to_string'
digits = range(10)
strings = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
for (expected, actual) in zip(strings, map(u.digit_to_string, digits)):
assert (expected =... |
@pytest.mark.unit
def test_build_digit_to_string_fails():
'test cartographer.build_digit_to_string'
digit = (- 1)
with pytest.raises(ValueError) as excinfo:
u.digit_to_string(digit)
assert ('Only digits 0-9 are supported' in str(excinfo.value))
|
@pytest.mark.unit
def test_make_fname_js_safe_digit():
'Test the cartographer.make_fname_js_safe functions.'
unsafe = '123'
expected = 'one23'
assert (expected == u.make_fname_js_safe(unsafe))
|
@pytest.mark.unit
def test_make_fname_js_safe_dot_dash():
'Test the cartographer.make_fname_js_safe functions.'
unsafe = 'a.b-c'
expected = 'a_dot_b_c'
assert (expected == u.make_fname_js_safe(unsafe))
|
@pytest.mark.unit
def test_make_fname_js_safe_no_change():
'Test the cartographer.make_fname_js_safe functions.'
safe = 'abc'
expected = 'abc'
assert (expected == u.make_fname_js_safe(safe))
|
@pytest.mark.unit
def test_MockQueue():
'Test the MockQueue class.'
bar = tqdm()
q = u.MockQueue(bar)
q.put(100)
assert (q.bar.n == 100)
|
@pytest.mark.unit
def test_backpressure_queue():
'Test backpressure_queue.'
helpers.setup()
pbar_ref = (0, u.MockQueue(helpers.MockTQDM()))
n_parallel_jobs = 1
f_args = [[None], [None], [None]]
hit_all_queue = [False, False, False]
wait_one = [True]
def wait_f(in_progress: List[Any]):... |
def digit_to_string(digit: int) -> str:
'Converts an integer into its word representation'
if (digit == 0):
return 'zero'
elif (digit == 1):
return 'one'
elif (digit == 2):
return 'two'
elif (digit == 3):
return 'three'
elif (digit == 4):
return 'four'
... |
def make_fname_js_safe(fname: str) -> str:
'Converts a string filename to a javascript safe identifier.'
if (fname[0] in string.digits):
adj_for_digit = (digit_to_string(int(fname[0])) + fname[1:])
else:
adj_for_digit = fname
return adj_for_digit.replace('.', '_dot_').replace('-', '_')... |
def get_fits_image_size(fits_file: str) -> Tuple[(int, int)]:
'Returns image size (x, y)\n\n Args:\n fits_file (str): fits file path\n\n Returns:\n Tuple[int, int]: returns the x and y dims of the input file\n '
hdr = fits.getheader(fits_file)
return (hdr['NAXIS1'], hdr['NAXIS2'])
|
def get_standard_image_size(image_file: str) -> Tuple[(int, int)]:
'Returns image size (x, y)\n\n Args:\n image_file (str): image file path\n\n Returns:\n Tuple[int, int]: returns the x and y dims of the input file\n '
with Image.open(image_file) as f:
size = f.size
return s... |
def peek_image_info(img_file_names: List[str]) -> Tuple[(int, int)]:
'Gets image size values given passed image file names\n\n Args:\n img_file_names (List[str]): Input image files that are being tiled\n\n Returns:\n Tuple[int, int]: The `max x`, and `max y`\n '
fits_sizes = list(map(ge... |
def get_version():
with open(os.path.join(fitsmap.__path__[0], '__version__.py'), 'r') as f:
return f.readline().strip().replace('"', '')
|
def backpressure_queue(wait_f: Callable, work_f: Callable, f_args: List[List[Any]], pbar_ref: Tuple[(int, queue.Queue)], n_parallel_jobs: int, batch_size: int=1) -> None:
'A queue that will limit things processed in parallel.\n\n Args:\n wait_f (Callable): A function that will block until a process is f... |
class MockQueue():
def __init__(self, bar):
self.bar = bar
def put(self, n):
self.bar.update(n=n)
|
def read(fname):
'Helper for README file.'
return open(os.path.join(os.path.dirname(__file__), fname)).read()
|
def parse_args():
modify_args()
parser = argparse.ArgumentParser(description='Generation demo')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('img_path', help='path to input image file')
parser.add_argu... |
def main():
args = parse_args()
model = init_model(args.config, args.checkpoint, device=torch.device('cuda', args.device))
output = generation_inference(model, args.img_path, args.unpaired_path)
mmcv.imwrite(output, args.save_path)
if args.imshow:
mmcv.imshow(output, 'predicted generation ... |
def parse_args():
parser = argparse.ArgumentParser(description='Matting demo')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('img_path', help='path to input image file')
parser.add_argument('trimap_path', h... |
def main():
args = parse_args()
model = init_model(args.config, args.checkpoint, device=torch.device('cuda', args.device))
pred_alpha = (matting_inference(model, args.img_path, args.trimap_path) * 255)
mmcv.imwrite(pred_alpha, args.save_path)
if args.imshow:
mmcv.imshow(pred_alpha, 'predic... |
def parse_args():
modify_args()
parser = argparse.ArgumentParser(description='Restoration demo')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('img-path', help='path to input image file')
parser.add_arg... |
def main():
args = parse_args()
if (not os.path.isfile(args.img_path)):
raise ValueError('It seems that you did not input a valid "image_path". Please double check your input, or you may want to use "restoration_video_demo.py" for video restoration.')
if (args.ref_path and (not os.path.isfile(args... |
def parse_args():
modify_args()
parser = argparse.ArgumentParser(description='Restoration demo')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('img_path', help='path to input image file')
parser.add_arg... |
def main():
args = parse_args()
if (not os.path.isfile(args.img_path)):
raise ValueError('It seems that you did not input a valid "image_path". Please double check your input, or you may want to use "restoration_video_demo.py" for video restoration.')
model = init_model(args.config, args.checkpoin... |
def parse_args():
modify_args()
parser = argparse.ArgumentParser(description='Restoration demo')
parser.add_argument('config', help='test config file path')
parser.add_argument('checkpoint', help='checkpoint file')
parser.add_argument('input_dir', help='directory of the input video')
parser.ad... |
def main():
" Demo for video interpolation models.\n\n Note that we accept video as input(output), when 'input_dir'('output_dir')\n is set to the path to the video. But using videos introduces video\n compression, which lower the visual quality. If you want actual quality,\n please save them as separa... |
def builder_inited_handler(app):
subprocess.run(['bash', './merge_docs.sh'])
subprocess.run(['python', './stat.py'])
|
def setup(app):
app.connect('builder-inited', builder_inited_handler)
|
def anchor(name):
return re.sub('-+', '-', re.sub('[^a-zA-Z0-9\\+]', '-', name.strip().lower())).strip('-')
|
def builder_inited_handler(app):
subprocess.run(['./merge_docs.sh'])
subprocess.run(['./stat.py'])
|
def setup(app):
app.connect('builder-inited', builder_inited_handler)
|
def anchor(name):
return re.sub('-+', '-', re.sub('[^a-zA-Z0-9\\+]', '-', name.strip().lower())).strip('-')
|
def generation_inference(model, img, img_unpaired=None):
'Inference image with the model.\n\n Args:\n model (nn.Module): The loaded model.\n img (str): File path of input image.\n img_unpaired (str, optional): File path of the unpaired image.\n If not None, perform unpaired imag... |
def inpainting_inference(model, masked_img, mask):
'Inference image with the model.\n\n Args:\n model (nn.Module): The loaded model.\n masked_img (str): File path of image with mask.\n mask (str): Mask file path.\n\n Returns:\n Tensor: The predicted inpainting result.\n '
... |
def init_model(config, checkpoint=None, device='cuda:0'):
"Initialize a model from config file.\n\n Args:\n config (str or :obj:`mmcv.Config`): Config file path or the config\n object.\n checkpoint (str, optional): Checkpoint path. If left as None, the model\n will not load ... |
def matting_inference(model, img, trimap):
'Inference image(s) with the model.\n\n Args:\n model (nn.Module): The loaded model.\n img (str): Image file path.\n trimap (str): Trimap file path.\n\n Returns:\n np.ndarray: The predicted alpha matte.\n '
cfg = model.cfg
dev... |
def restoration_inference(model, img, ref=None):
'Inference image with the model.\n\n Args:\n model (nn.Module): The loaded model.\n img (str): File path of input image.\n ref (str | None): File path of reference image. Default: None.\n\n Returns:\n Tensor: The predicted restorat... |
def single_gpu_test(model, data_loader, save_image=False, save_path=None, iteration=None):
'Test model with a single gpu.\n\n This method tests model with a single gpu and displays test progress bar.\n\n Args:\n model (nn.Module): Model to be tested.\n data_loader (nn.Dataloader): Pytorch data... |
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False, save_image=False, save_path=None, iteration=None, empty_cache=False):
"Test model with multiple gpus.\n\n This method tests model with multiple gpus and collects the results\n under two different modes: gpu and cpu modes. By setting 'gpu... |
def collect_results_cpu(result_part, size, tmpdir=None):
"Collect results in cpu mode.\n\n It saves the results on different gpus to 'tmpdir' and collects\n them by the rank 0 worker.\n\n Args:\n result_part (list): Results to be collected\n size (int): Result size.\n tmpdir (str): P... |
def collect_results_gpu(result_part, size):
'Collect results in gpu mode.\n\n It encodes results to gpu tensors and use gpu communication for results\n collection.\n\n Args:\n result_part (list): Results to be collected\n size (int): Result size.\n\n Returns:\n list: Ordered resul... |
def init_random_seed(seed=None, device='cuda'):
"Initialize random seed.\n If the seed is not set, the seed will be automatically randomized,\n and then broadcast to all processes to prevent some potential bugs.\n Args:\n seed (int, Optional): The seed. Default to None.\n device (str): The ... |
def set_random_seed(seed, deterministic=False):
'Set random seed.\n\n Args:\n seed (int): Seed to be used.\n deterministic (bool): Whether to set the deterministic option for\n CUDNN backend, i.e., set `torch.backends.cudnn.deterministic`\n to True and `torch.backends.cudnn.... |
def train_model(model, dataset, cfg, distributed=False, validate=False, timestamp=None, meta=None):
'Train model entry function.\n\n Args:\n model (nn.Module): The model to be trained.\n dataset (:obj:`Dataset`): Train dataset.\n cfg (dict): The config dict for training.\n distribut... |
def _dist_train(model, dataset, cfg, validate=False, logger=None, timestamp=None, meta=None):
'Distributed training function.\n\n Args:\n model (nn.Module): The model to be trained.\n dataset (:obj:`Dataset`): Train dataset.\n cfg (dict): The config dict for training.\n validate (bo... |
def _non_dist_train(model, dataset, cfg, validate=False, logger=None, timestamp=None, meta=None):
'Non-Distributed training function.\n\n Args:\n model (nn.Module): The model to be trained.\n dataset (:obj:`Dataset`): Train dataset.\n cfg (dict): The config dict for training.\n vali... |
def read_image(filepath):
'Read image from file.\n\n Args:\n filepath (str): File path.\n\n Returns:\n image (np.array): Image.\n '
img_bytes = FILE_CLIENT.get(filepath)
image = mmcv.imfrombytes(img_bytes, flag='color', channel_order='rgb', backend='pillow')
return image
|
def read_frames(source, start_index, num_frames, from_video, end_index):
'Read frames from file or video.\n\n Args:\n source (list | mmcv.VideoReader): Source of frames.\n start_index (int): Start index of frames.\n num_frames (int): frames number to be read.\n from_video (bool): We... |
def video_interpolation_inference(model, input_dir, output_dir, start_idx=0, end_idx=None, batch_size=4, fps_multiplier=0, fps=0, filename_tmpl='{:08d}.png'):
"Inference image with the model.\n\n Args:\n model (nn.Module): The loaded model.\n input_dir (str): Directory of the input video.\n ... |
@MODULE_WRAPPERS.register_module()
class DistributedDataParallelWrapper(nn.Module):
"A DistributedDataParallel wrapper for models in MMediting.\n\n In MMedting, there is a need to wrap different modules in the models\n with separate DistributedDataParallel. Otherwise, it will cause\n errors for GAN train... |
class EvalIterHook(Hook):
'Non-Distributed evaluation hook for iteration-based runner.\n\n This hook will regularly perform evaluation in a given interval when\n performing in non-distributed environment.\n\n Args:\n dataloader (DataLoader): A PyTorch dataloader.\n interval (int): Evaluatio... |
class DistEvalIterHook(EvalIterHook):
'Distributed evaluation hook.\n\n Args:\n dataloader (DataLoader): A PyTorch dataloader.\n interval (int): Evaluation interval. Default: 1.\n tmpdir (str | None): Temporary directory to save the results of all\n processes. Default: None.\n ... |
def gaussian(x, sigma):
'Gaussian function.\n\n Args:\n x (array_like): The independent variable.\n sigma (float): Standard deviation of the gaussian function.\n\n Return:\n ndarray or scalar: Gaussian value of `x`.\n '
return (np.exp(((- (x ** 2)) / (2 * (sigma ** 2)))) / (sigma... |
def dgaussian(x, sigma):
'Gradient of gaussian.\n\n Args:\n x (array_like): The independent variable.\n sigma (float): Standard deviation of the gaussian function.\n\n Return:\n ndarray or scalar: Gradient of gaussian of `x`.\n '
return (((- x) * gaussian(x, sigma)) / (sigma ** 2... |
def gauss_filter(sigma, epsilon=0.01):
'Gradient of gaussian.\n\n Args:\n sigma (float): Standard deviation of the gaussian kernel.\n epsilon (float): Small value used when calculating kernel size.\n Default: 1e-2.\n\n Return:\n tuple[ndarray]: Gaussian filter along x and y a... |
def gauss_gradient(img, sigma):
'Gaussian gradient.\n\n From https://www.mathworks.com/matlabcentral/mlc-downloads/downloads/\n submissions/8060/versions/2/previews/gaussgradient/gaussgradient.m/\n index.html\n\n Args:\n img (ndarray): Input image.\n sigma (float): Standard deviation of ... |
def inference_with_session(sess, io_binding, output_names, input_tensor):
device_type = input_tensor.device.type
device_id = input_tensor.device.index
device_id = (0 if (device_id is None) else device_id)
io_binding.bind_input(name='input', device_type=device_type, device_id=device_id, element_type=np... |
class ONNXRuntimeMattor(nn.Module):
def __init__(self, sess, io_binding, output_names, base_model):
super(ONNXRuntimeMattor, self).__init__()
self.sess = sess
self.io_binding = io_binding
self.output_names = output_names
self.base_model = base_model
def forward(self, ... |
class RestorerGenerator(nn.Module):
def __init__(self, sess, io_binding, output_names):
super(RestorerGenerator, self).__init__()
self.sess = sess
self.io_binding = io_binding
self.output_names = output_names
def forward(self, x):
pred = inference_with_session(self.se... |
class ONNXRuntimeRestorer(nn.Module):
def __init__(self, sess, io_binding, output_names, base_model):
super(ONNXRuntimeRestorer, self).__init__()
self.sess = sess
self.io_binding = io_binding
self.output_names = output_names
self.base_model = base_model
restorer_ge... |
class ONNXRuntimeEditing(nn.Module):
def __init__(self, onnx_file, cfg, device_id):
super(ONNXRuntimeEditing, self).__init__()
ort_custom_op_path = ''
try:
from mmcv.ops import get_onnxruntime_op_path
ort_custom_op_path = get_onnxruntime_op_path()
except (I... |
@HOOKS.register_module()
class ExponentialMovingAverageHook(Hook):
"Exponential Moving Average Hook.\n\n Exponential moving average is a trick that widely used in current GAN\n literature, e.g., PGGAN, StyleGAN, and BigGAN. This general idea of it is\n maintaining a model with the same architecture, but ... |
def build_optimizers(model, cfgs):
"Build multiple optimizers from configs.\n\n If `cfgs` contains several dicts for optimizers, then a dict for each\n constructed optimizers will be returned.\n If `cfgs` only contains one optimizer config, the constructed optimizer\n itself will be returned.\n\n F... |
@HOOKS.register_module()
class LinearLrUpdaterHook(LrUpdaterHook):
"Linear learning rate scheduler for image generation.\n\n In the beginning, the learning rate is 'base_lr' defined in mmcv.\n We give a target learning rate 'target_lr' and a start point 'start'\n (iteration / epoch). Before 'start', we f... |
def sync_random_seed(seed=None, device='cuda'):
"Make sure different ranks share the same seed.\n All workers must call this function, otherwise it will deadlock.\n This method is generally used in `DistributedSampler`,\n because the seed should be identical across all processes\n in the distributed g... |
class BaseDataset(Dataset, metaclass=ABCMeta):
'Base class for datasets.\n\n All datasets should subclass it.\n All subclasses should overwrite:\n\n ``load_annotations``, supporting to load information and generate\n image lists.\n\n Args:\n pipeline (list[dict | callable]): A sequen... |
class BaseGenerationDataset(BaseDataset):
'Base class for generation datasets.'
@staticmethod
def scan_folder(path):
'Obtain image path list (including sub-folders) from a given folder.\n\n Args:\n path (str | :obj:`Path`): Folder path.\n\n Returns:\n list[str]... |
@DATASETS.register_module()
class BaseMattingDataset(BaseDataset):
'Base image matting dataset.\n '
def __init__(self, ann_file, pipeline, data_prefix=None, test_mode=False):
super().__init__(pipeline, test_mode)
self.ann_file = str(ann_file)
self.data_prefix = str(data_prefix)
... |
class BaseSRDataset(BaseDataset):
'Base class for super resolution datasets.\n '
def __init__(self, pipeline, scale, test_mode=False):
super().__init__(pipeline, test_mode)
self.scale = scale
@staticmethod
def scan_folder(path):
'Obtain image path list (including sub-folde... |
class BaseVFIDataset(BaseDataset):
'Base class for video frame interpolation datasets.\n '
def __init__(self, pipeline, folder, ann_file, test_mode=False):
super().__init__(pipeline, test_mode)
self.folder = str(folder)
self.ann_file = str(ann_file)
def __getitem__(self, idx):... |
def _concat_dataset(cfg, default_args=None):
'Concat datasets with different ann_file but the same type.\n\n Args:\n cfg (dict): The config of dataset.\n default_args (dict, optional): Default initialization arguments.\n Default: None.\n\n Returns:\n Dataset: The concatenated... |
def build_dataset(cfg, default_args=None):
'Build a dataset from config dict.\n\n It supports a variety of dataset config. If ``cfg`` is a Sequential (list\n or dict), it will be a concatenated dataset of the datasets specified by\n the Sequential. If it is a ``RepeatDataset``, then it will repeat the\n ... |
def build_dataloader(dataset, samples_per_gpu, workers_per_gpu, num_gpus=1, dist=True, shuffle=True, seed=None, drop_last=False, pin_memory=True, persistent_workers=True, **kwargs):
'Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, ther... |
def worker_init_fn(worker_id, num_workers, rank, seed):
'Function to initialize each worker.\n\n The seed of each worker equals to\n ``num_worker * rank + worker_id + user_seed``.\n\n Args:\n worker_id (int): Id for each worker.\n num_workers (int): Number of workers.\n rank (int): R... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.