code stringlengths 17 6.64M |
|---|
def write_infinite_segment_header(f):
f.write(ebml_element(408125543, '', (- 1)))
|
def random_uid():
def rint():
return int((random.random() * (256 ** 4)))
return (((ben(rint()) + ben(rint())) + ben(rint())) + ben(rint()))
|
def example():
write_ebml_header(sys.stdout, 'matroska', 2, 2)
write_infinite_segment_header(sys.stdout)
sys.stdout.write(ebml_element(357149030, (((('' + ebml_element(29604, random_uid())) + ebml_element(31657, 'mkvgen.py test')) + ebml_element(19840, 'mkvgen.py')) + ebml_element(22337, 'mkvgen.py'))))
... |
class MatroskaIndex(mkvparse.MatroskaHandler):
def __init__(self):
self.frameindex = []
def tracks_available(self):
(_, self.config_record) = self.tracks[1]['CodecPrivate']
def frame(self, track_id, timestamp, pos, length, more_laced_frames, duration, keyframe, invisible, discardable):
... |
def mkvindex(f):
handler = MatroskaIndex()
mkvparse.mkvparse(f, handler)
return (handler.config_record, handler.frameindex)
|
def simple_gen(of, config_record, w, h, framedata):
mkvgen.write_ebml_header(of, 'matroska', 2, 2)
mkvgen.write_infinite_segment_header(of)
of.write(ebml_element(374648427, ('' + ebml_element(174, (((((('' + ebml_element(215, ben(1))) + ebml_element(29637, ben(1))) + ebml_element(131, ben(1))) + ebml_elem... |
def get_major_bit_number(n):
'\n Takes uint8, returns number of the most significant bit plus the number with that bit cleared.\n Examples:\n 0b10010101 -> (0, 0b00010101)\n 0b00010101 -> (3, 0b00000101)\n 0b01111111 -> (1, 0b00111111)\n '
if (not n):
raise Except... |
def read_matroska_number(f, unmodified=False, signed=False):
'\n Read ebml number. Unmodified means don\'t clear the length bit (as in Element IDs)\n Returns the number and it\'s length as a tuple\n\n See examples in "parse_matroska_number" function\n '
if (unmodified and signed):
... |
def parse_matroska_number(data, pos, unmodified=False, signed=False):
'\n Parse ebml number from buffer[pos:]. Just like read_matroska_number.\n Unmodified means don\'t clear the length bit (as in Element IDs)\n Returns the number plus the new position in input buffer\n\n Examples:\n ... |
def parse_xiph_number(data, pos):
'\n Parse the Xiph lacing number from data[pos:]\n Returns the number plus the new position\n\n Examples:\n "\x01" -> (1, pos+1)\n "U" -> (0x55, pos+1)\n "ÿ\x04" -> (0x103, pos+2)\n "ÿÿ\x04" -> (0x202, pos+3)\n "ÿÿ\x00"... |
def parse_fixedlength_number(data, pos, length, signed=False):
'\n Read the big-endian number from data[pos:pos+length]\n Returns the number plus the new position\n\n Examples:\n "\x01" -> (0x1, pos+1)\n "U" -> (0x55, pos+1)\n "U" signed -> (0x55, pos+1)\n "ÿ\x0... |
def read_fixedlength_number(f, length, signed=False):
' Read length bytes and parse (parse_fixedlength_number) it.\n Returns only the number'
buf = f.read(length)
(r, pos) = parse_fixedlength_number(buf, 0, length, signed)
return r
|
def read_ebml_element_header(f):
'\n Read Element ID and size\n Returns id, element size and this header size\n '
(id_, n) = read_matroska_number(f, unmodified=True)
(size, n2) = read_matroska_number(f)
return (id_, size, (n + n2))
|
class EbmlElementType():
VOID = 0
MASTER = 1
UNSIGNED = 2
SIGNED = 3
TEXTA = 4
TEXTU = 5
BINARY = 6
FLOAT = 7
DATE = 8
JUST_GO_ON = 10
|
def read_simple_element(f, type_, size):
date = None
if (size == 0):
return ''
if (type_ == EET.UNSIGNED):
data = read_fixedlength_number(f, size, False)
elif (type_ == EET.SIGNED):
data = read_fixedlength_number(f, size, True)
elif (type_ == EET.TEXTA):
data = f.re... |
def read_ebml_element_tree(f, total_size):
"\n Build tree of elements, reading f until total_size reached\n Don't use for the whole segment, it's not Haskell\n\n Returns list of pairs (element_name, element_value).\n element_value can also be list of pairs\n "
childs = []
wh... |
class MatroskaHandler():
' User for mkvparse should override these methods '
def tracks_available(self):
pass
def segment_info_available(self):
pass
def frame(self, track_id, timestamp, data, more_laced_frames, duration, keyframe, invisible, discardable):
pass
def ebml_... |
def handle_block(buffer, buffer_pos, handler, cluster_timecode, timecode_scale=1000000, duration=None, header_removal_headers_for_tracks={}):
'\n Decode a block, handling all lacings, send it to handler with appropriate timestamp, track number\n '
pos = 0
(tracknum, pos) = parse_matroska_number(... |
def resync(f):
sys.stderr.write('mvkparse: Resyncing\n')
while True:
b = f.read(1)
if (b == b''):
return (None, None)
if (b == b'\x1f'):
b2 = f.read(3)
if (b2 == b'C\xb6u'):
(seglen, x) = read_matroska_number(f)
return... |
def mkvparse(f, handler):
'\n Read mkv file f and call handler methods when track or segment information is ready or when frame is read.\n Handles lacing, timecodes (except of per-track scaling)\n '
timecode_scale = 1000000
current_cluster_timecode = 0
resync_element_id = None
res... |
class PollableQueue(object):
'A Queue that you can poll().\n Only works with a single producer.\n '
def __init__(self, maxlen=None):
with open('/proc/sys/fs/pipe-max-size') as f:
max_maxlen = int(f.read().rstrip())
if (maxlen is None):
maxlen = max_maxlen
... |
class Route(object):
def __init__(self, route_name, data_dir):
self.route_name = route_name.replace('_', '|')
self._segments = self._get_segments(data_dir)
@property
def segments(self):
return self._segments
def log_paths(self):
max_seg_number = self._segments[(- 1)]... |
class RouteSegment(object):
def __init__(self, name, log_path, camera_path):
self._name = RouteSegmentName(name)
self.log_path = log_path
self.camera_path = camera_path
@property
def name(self):
return str(self._name)
@property
def canonical_name(self):
r... |
class RouteSegmentName(object):
def __init__(self, name_str):
self._segment_name_str = name_str
(self._route_name_str, num_str) = self._segment_name_str.rsplit('--', 1)
self._num = int(num_str)
@property
def segment_num(self):
return self._num
def __str__(self):
... |
class _FrameReaderDict(dict):
def __init__(self, camera_paths, cache_paths, framereader_kwargs, *args, **kwargs):
super(_FrameReaderDict, self).__init__(*args, **kwargs)
if (cache_paths is None):
cache_paths = {}
if (not isinstance(cache_paths, dict)):
cache_paths ... |
class RouteFrameReader(object):
'Reads frames across routes and route segments by frameId.'
def __init__(self, camera_paths, cache_paths, frame_id_lookup, **kwargs):
'Create a route framereader.\n\n Inputs:\n TODO\n\n kwargs: Forwarded to the FrameReader function. If cache_prefix ... |
def get_arg_parser():
parser = argparse.ArgumentParser(description='Unlogging and save to file', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('data_dir', nargs='?', help='Path to directory in which log and camera files are located.')
parser.add_argument('route_name', type=(l... |
def main(argv):
args = get_arg_parser().parse_args(sys.argv[1:])
if (not args.data_dir):
print('Data directory invalid.')
return
if (not args.route_name):
args.route_name = os.path.basename(args.data_dir)
args.data_dir = os.path.dirname(args.data_dir)
route = Route(args... |
def can_list_to_can_capnp(can_msgs, msgtype='can'):
dat = messaging.new_message()
dat.init(msgtype, len(can_msgs))
for (i, can_msg) in enumerate(can_msgs):
if (msgtype == 'sendcan'):
cc = dat.sendcan[i]
else:
cc = dat.can[i]
cc.address = can_msg[0]
c... |
def can_capnp_to_can_list(can, src_filter=None):
ret = []
for msg in can:
if ((src_filter is None) or (msg.src in src_filter)):
ret.append((msg.address, msg.busTime, msg.dat, msg.src))
return ret
|
def can_health():
while 1:
try:
dat = handle.controlRead((usb1.TYPE_VENDOR | usb1.RECIPIENT_DEVICE), 210, 0, 0, 16)
break
except (USBErrorIO, USBErrorOverflow):
cloudlog.exception('CAN: BAD HEALTH, RETRYING')
(v, i, started) = struct.unpack('IIB', dat[0:9])
... |
def __parse_can_buffer(dat):
ret = []
for j in range(0, len(dat), 16):
ddat = dat[j:(j + 16)]
(f1, f2) = struct.unpack('II', ddat[0:8])
ret.append(((f1 >> 21), (f2 >> 16), ddat[8:(8 + (f2 & 15))], ((f2 >> 4) & 15)))
return ret
|
def can_send_many(arr):
snds = []
for (addr, _, dat, alt) in arr:
if (addr < 2048):
snd = (struct.pack('II', ((addr << 21) | 1), (len(dat) | (alt << 4))) + dat)
snd = snd.ljust(16, '\x00')
snds.append(snd)
while 1:
try:
handle.bulkWrite(3, ''... |
def can_recv():
dat = ''
while 1:
try:
dat = handle.bulkRead(1, (16 * 256))
break
except (USBErrorIO, USBErrorOverflow):
cloudlog.exception('CAN: BAD RECV, RETRYING')
return __parse_can_buffer(dat)
|
def can_init():
global handle, context
handle = None
cloudlog.info('attempting can init')
context = usb1.USBContext()
for device in context.getDeviceList(skip_on_error=True):
if ((device.getVendorID() == 48042) and (device.getProductID() == 56780)):
handle = device.open()
... |
def boardd_mock_loop():
context = zmq.Context()
can_init()
handle.controlWrite(64, 220, SAFETY_ALLOUTPUT, 0, b'')
logcan = messaging.sub_sock(context, service_list['can'].port)
sendcan = messaging.pub_sock(context, service_list['sendcan'].port)
while 1:
tsc = messaging.drain_sock(logca... |
def boardd_test_loop():
can_init()
cnt = 0
while 1:
can_send_many([[187, 0, 'ªªªª', 0], [170, 0, ('ªªªª' + struct.pack('!I', cnt)), 1]])
can_msgs = can_recv()
print(('got %d' % len(can_msgs)))
time.sleep(0.01)
cnt += 1
|
def boardd_loop(rate=200):
rk = Ratekeeper(rate)
context = zmq.Context()
can_init()
logcan = messaging.pub_sock(context, service_list['can'].port)
health_sock = messaging.pub_sock(context, service_list['health'].port)
sendcan = messaging.sub_sock(context, service_list['sendcan'].port)
whil... |
def boardd_proxy_loop(rate=200, address='192.168.2.251'):
rk = Ratekeeper(rate)
context = zmq.Context()
can_init()
logcan = messaging.sub_sock(context, service_list['can'].port, addr=address)
sendcan = messaging.pub_sock(context, service_list['sendcan'].port)
while 1:
can_msgs = can_re... |
def main(gctx=None):
if (os.getenv('MOCK') is not None):
boardd_mock_loop()
elif (os.getenv('PROXY') is not None):
boardd_proxy_loop()
elif (os.getenv('BOARDTEST') is not None):
boardd_test_loop()
else:
boardd_loop()
|
def pygame_modules_have_loaded():
return (pygame.display.get_init() and pygame.font.get_init())
|
def ui_thread(addr, frame_address):
context = zmq.Context()
pygame.init()
pygame.font.init()
assert pygame_modules_have_loaded()
size = ((_FULL_FRAME_SIZE[0] * SCALE), (_FULL_FRAME_SIZE[1] * SCALE))
pygame.display.set_caption('comma one debug UI')
screen = pygame.display.set_mode(size, pyg... |
def get_arg_parser():
parser = argparse.ArgumentParser(description='Show replay data in a UI.', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('ip_address', nargs='?', default='127.0.0.1', help='The ip address on which to receive zmq messages.')
parser.add_argument('--frame-ad... |
def asymmetric_l2_loss(u, tau):
return torch.mean((torch.abs((tau - (u < 0).float())) * (u ** 2)))
|
class IQL(nn.Module):
def __init__(self, qf, vf, policy, max_steps, tau, alpha, value_lr=0.0001, policy_lr=0.0001, discount=0.99, beta=0.005):
super().__init__()
self.qf = qf.to(DEFAULT_DEVICE)
self.q_target = copy.deepcopy(qf).requires_grad_(False).to(DEFAULT_DEVICE)
self.vf = vf... |
def get_env_and_dataset(env_name, max_episode_steps, normalize):
env = gym.make(env_name)
dataset = d4rl.qlearning_dataset(env)
if any(((s in env_name) for s in ('halfcheetah', 'hopper', 'walker2d'))):
(min_ret, max_ret) = return_range(dataset, max_episode_steps)
print(f'Dataset returns ha... |
def main(args):
wandb.init(project='project_name', entity='your_wandb_id', name=f'{args.env_name}', config={'env_name': args.env_name, 'normalize': args.normalize, 'tau': args.tau, 'alpha': args.alpha, 'seed': args.seed, 'type': args.type, 'value_lr': args.value_lr, 'policy_lr': args.policy_lr})
torch.set_num... |
def get_env_and_dataset(env_name, max_episode_steps, normalize):
env = gym.make(env_name)
dataset = d4rl.qlearning_dataset(env)
if any(((s in env_name) for s in ('halfcheetah', 'hopper', 'walker2d'))):
(min_ret, max_ret) = return_range(dataset, max_episode_steps)
print(f'Dataset returns ha... |
def main(args):
wandb.init(project='project_name', entity='your_wandb_id', name=f'{args.env_name}', config={'env_name': args.env_name, 'normalize': args.normalize, 'tau': args.tau, 'alpha': args.alpha, 'seed': args.seed, 'type': args.type, 'value_lr': args.value_lr, 'policy_lr': args.policy_lr, 'pretrain': args.p... |
class GaussianPolicy(nn.Module):
def __init__(self, obs_dim, act_dim, hidden_dim=256, n_hidden=2):
super().__init__()
self.net = mlp([obs_dim, *([hidden_dim] * n_hidden), act_dim])
self.log_std = nn.Parameter(torch.zeros(act_dim, dtype=torch.float32))
def forward(self, obs):
... |
class DeterministicPolicy(nn.Module):
def __init__(self, obs_dim, act_dim, hidden_dim=256, n_hidden=2):
super().__init__()
self.net = mlp([obs_dim, *([hidden_dim] * n_hidden), act_dim], output_activation=nn.Tanh)
def forward(self, obs):
return self.net(obs)
def act(self, obs, de... |
def asymmetric_l2_loss(u, tau):
return torch.mean((torch.abs((tau - (u < 0).float())) * (u ** 2)))
|
class POR(nn.Module):
def __init__(self, vf, policy, goal_policy, max_steps, tau, alpha, value_lr=0.0001, policy_lr=0.0001, discount=0.99, beta=0.005):
super().__init__()
self.vf = vf.to(DEFAULT_DEVICE)
self.v_target = copy.deepcopy(vf).requires_grad_(False).to(DEFAULT_DEVICE)
sel... |
class TwinQ(nn.Module):
def __init__(self, state_dim, action_dim, hidden_dim=256, n_hidden=2):
super().__init__()
dims = [(state_dim + action_dim), *([hidden_dim] * n_hidden), 1]
self.q1 = mlp(dims, squeeze_output=True)
self.q2 = mlp(dims, squeeze_output=True)
def both(self, ... |
class ValueFunction(nn.Module):
def __init__(self, state_dim, hidden_dim=256, n_hidden=2):
super().__init__()
dims = [state_dim, *([hidden_dim] * n_hidden), 1]
self.v = mlp(dims, squeeze_output=True)
def forward(self, state):
return self.v(state)
|
class TwinV(nn.Module):
def __init__(self, state_dim, layer_norm=False, hidden_dim=256, n_hidden=2):
super().__init__()
dims = [state_dim, *([hidden_dim] * n_hidden), 1]
self.v1 = mlp(dims, layer_norm=layer_norm, squeeze_output=True)
self.v2 = mlp(dims, layer_norm=layer_norm, sque... |
def transformer(batch, chan, flow, U, out_size, name='SpatialTransformer', **kwargs):
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])), 1), [1, 0])
rep = tf.cast(rep, 'int32')
x = tf.ma... |
def warp_img(batch_size, imga, imgb, reuse, scope='easyflow'):
(n, h, w, c) = imga.get_shape().as_list()
with tf.variable_scope(scope, reuse=reuse):
with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biase... |
def load_stack(type_process, ite_stack):
'Load stack npy.\n\n type_process: "tra" or "val".\n ite_stack: start from 0.'
stack_name = (((('stack_' + type_process) + '_pre_') + str(ite_stack)) + '.hdf5')
pre_list = h5py.File(os.path.join(dir_stack, stack_name), 'r')['stack_pre'][:]
print('pre load... |
def cal_MSE(img1, img2):
'Calculate MSE of two images.\n\n img: [0,1].'
MSE = tf.reduce_mean(tf.pow(tf.subtract(img1, img2), 2.0))
return MSE
|
def cal_PSNR(img1, img2):
'Calculate PSNR of two images.\n\n img: [0,1].'
MSE = cal_MSE(img1, img2)
PSNR = ((10.0 * tf.log((1.0 / MSE))) / tf.log(10.0))
return PSNR
|
def main_train():
'Fine tune a model from step2 and continue training.\n\n Train and evaluate model.'
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
os.environ['CUDA_VISIBLE_DEVICES'] = GPU
config = tf.ConfigProto(allow_soft_placement=True)
sess = tf.Session(config=config)
x1 = tf.placeholder(tf.... |
def transformer(batch, chan, flow, U, out_size, name='SpatialTransformer', **kwargs):
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])), 1), [1, 0])
rep = tf.cast(rep, 'int32')
x = tf.ma... |
def warp_img(batch_size, imga, imgb, reuse, scope='easyflow'):
(n, h, w, c) = imga.get_shape().as_list()
with tf.variable_scope(scope, reuse=reuse):
with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biase... |
def load_stack(type_process, ite_stack):
'Load stack npy.\n\n type_process: "tra" or "val".\n ite_stack: start from 0.'
stack_name = (((('stack_' + type_process) + '_pre_') + str(ite_stack)) + '.hdf5')
stack_path = os.path.join(dir_stack, stack_name)
pre_list = h5py.File(stack_path, 'r')['stack_... |
def cal_MSE(img1, img2):
'Calculate MSE of two images.\n\n img: [0,1].'
MSE = tf.reduce_mean(tf.pow(tf.subtract(img1, img2), 2.0))
return MSE
|
def cal_PSNR(img1, img2):
'Calculate PSNR of two images.\n\n img: [0,1].'
MSE = cal_MSE(img1, img2)
PSNR = ((10.0 * tf.log((1.0 / MSE))) / tf.log(10.0))
return PSNR
|
def main_train():
'Train and evaluate model.\n\n Output: model_QPxx, record_train_QPxx.'
sess = tf.Session(config=config)
x1 = tf.placeholder(tf.float32, [BATCH_SIZE, WIDTH, HEIGHT, CHANNEL])
x2 = tf.placeholder(tf.float32, [BATCH_SIZE, WIDTH, HEIGHT, CHANNEL])
x3 = tf.placeholder(tf.float32, [... |
def transformer(batch, chan, flow, U, out_size, name='SpatialTransformer', **kwargs):
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])), 1), [1, 0])
rep = tf.cast(rep, 'int32')
x = tf.ma... |
def warp_img(batch_size, imga, imgb, reuse, scope='easyflow'):
(n, h, w, c) = imga.get_shape().as_list()
with tf.variable_scope(scope, reuse=reuse):
with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biase... |
def load_stack(type_process, ite_stack):
'Load stack npy.\n\n type_process: "tra" or "val".\n ite_stack: start from 0.'
stack_name = (((('stack_' + type_process) + '_pre_') + str(ite_stack)) + '.hdf5')
pre_list = h5py.File(os.path.join(dir_stack, stack_name), 'r')['stack_pre'][:]
print('pre load... |
def cal_MSE(img1, img2):
'Calculate MSE of two images.\n\n img: [0,1].'
MSE = tf.reduce_mean(tf.pow(tf.subtract(img1, img2), 2.0))
return MSE
|
def cal_PSNR(img1, img2):
'Calculate PSNR of two images.\n\n img: [0,1].'
MSE = cal_MSE(img1, img2)
PSNR = ((10.0 * tf.log((1.0 / MSE))) / tf.log(10.0))
return PSNR
|
def main_train():
'Train and evaluate model.\n\n Output: model_QPxx, record_train_QPxx.'
sess = tf.Session(config=config)
x1 = tf.placeholder(tf.float32, [BATCH_SIZE, HEIGHT, WIDTH, CHANNEL])
x2 = tf.placeholder(tf.float32, [BATCH_SIZE, HEIGHT, WIDTH, CHANNEL])
x3 = tf.placeholder(tf.float32, [... |
def network(frame1, frame2, frame3, is_training, reuse=False, scope='netflow'):
with tf.variable_scope(scope, reuse=reuse):
c3_1_w = tf.get_variable('c3_1_w', shape=[3, 3, 1, 32], initializer=tf.contrib.layers.xavier_initializer(uniform=True))
c3_1_b = tf.get_variable('c3_1_b', shape=[32], initial... |
def network2(frame1, frame2, frame3, reuse=False, scope='netflow'):
with tf.variable_scope(scope, reuse=reuse):
with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biases_initializer=tf.constant_initializer(0.0... |
def transformer(batch, chan, flow, U, out_size, name='SpatialTransformer', **kwargs):
def _repeat(x, n_repeats):
with tf.variable_scope('_repeat'):
rep = tf.transpose(tf.expand_dims(tf.ones(shape=tf.stack([n_repeats])), 1), [1, 0])
rep = tf.cast(rep, 'int32')
x = tf.ma... |
def warp_img(batch_size, imga, imgb, reuse, scope='easyflow'):
(n, h, w, c) = imga.get_shape().as_list()
with tf.variable_scope(scope, reuse=reuse):
with slim.arg_scope([slim.conv2d], activation_fn=tflearn.activations.prelu, weights_initializer=tf.contrib.layers.xavier_initializer(uniform=True), biase... |
def build_dataset(cfg, default_args=None):
'Build dataset.\n\n Difference to that in MMEditing: Use the DATASETS in PowerQE.\n '
if isinstance(cfg, (list, tuple)):
dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])
elif (cfg['type'] == 'RepeatDataset'):
dataset = ... |
@DATASETS.register_module()
class PairedVideoDataset(SRAnnotationDataset):
"Paired video dataset with an annotation file.\n\n Differences to SRAnnotationDataset:\n Support versatile video loading. See arguments.\n\n Suppose the video sequences are stored as:\n\n powerqe\n `-- {gt,lq}_folder\n ... |
@DATASETS.register_module()
class PairedVideoKeyFramesDataset(PairedVideoDataset):
'Paired video dataset with an annotation file. Return the paths of\n neighboring key frames.\n\n Differences to PairedVideoAnnotationDataset:\n Use high-quality key frames instead of neighboring frames.\n Se... |
@DATASETS.register_module()
class PairedVideoKeyFramesAnnotationDataset(PairedVideoDataset):
'Paired video dataset with an annotation file. Return the annotation of\n key frames in each sample.\n\n Differences to PairedVideoAnnotationDataset:\n Return key-frame annotation. See "load_annotations".\n\n... |
@BACKBONES.register_module()
class ARCNN(BaseNet):
'AR-CNN network structure.\n\n Args:\n io_channels (int): Number of I/O channels.\n mid_channels_1 (int): Channel number of the first intermediate\n features.\n mid_channels_2 (int): Channel number of the second intermediate\n ... |
class BaseNet(nn.Module):
'Base network with the function init_weights.'
def __init__(self) -> None:
super().__init__()
def init_weights(self, pretrained=None, strict=True):
'Init weights for models.\n\n Args:\n pretrained (str): Path for pretrained weights.\n ... |
@BACKBONES.register_module()
class CBDNet(BaseNet):
'CBDNet network structure.\n\n Args:\n io_channels (int): Number of I/O channels.\n estimate_channels (int): Channel number of the features in the\n estimation module.\n nlevel_denoise (int): Level number of UNet for denoising.... |
@BACKBONES.register_module()
class DCAD(BaseNet):
'DCAD network structure.\n\n Args:\n io_channels (int): Number of I/O channels.\n mid_channels (int): Channel number of intermediate features.\n num_blocks (int): Block number in the trunk network.\n '
def __init__(self, io_channels... |
@BACKBONES.register_module()
class DnCNN(BaseNet):
'DnCNN network structure.\n\n Momentum for nn.BatchNorm2d is 0.9 in\n "https://github.com/cszn/KAIR/blob\n /7e51c16c6f55ff94b59c218c2af8e6b49fe0668b/models/basicblock.py#L69",\n but is 0.1 default in PyTorch.\n\n Args:\n io_channels (int): N... |
class Interpolate(nn.Module):
def __init__(self, scale_factor, mode):
super().__init__()
self.interp = nn.functional.interpolate
self.scale_factor = scale_factor
self.mode = mode
def forward(self, x):
x = self.interp(x, scale_factor=self.scale_factor, mode=self.mode, ... |
@BACKBONES.register_module()
class RDNQE(BaseNet):
'RDN for quality enhancement.\n\n Differences to the RDN in MMEditing:\n Support rescaling before/after enhancement.\n\n Args:\n rescale (int): Rescaling factor.\n io_channels (int): Number of I/O channels.\n mid_channels (int): ... |
@BACKBONES.register_module()
class RRDBNetQE(RRDBNet):
'Networks consisting of Residual in Residual Dense Block, which is used\n in ESRGAN and Real-ESRGAN.\n\n ESRGAN: Enhanced Super-Resolution Generative Adversarial Networks.\n Currently, it supports [x1/x2/x4] upsampling scale factor.\n\n Args:\n ... |
def build(cfg, registry, default_args=None):
'Build module function.\n\n Args:\n cfg (dict): Configuration for building modules.\n registry (obj): Registry object.\n default_args (dict, optional): Default arguments.\n Default: None.\n '
if isinstance(cfg, list):
m... |
def build_backbone(cfg):
'Build backbone.\n\n Args:\n cfg (dict): Configuration for building backbone.\n '
return build(cfg, BACKBONES)
|
def build_component(cfg):
'Build component.\n\n Args:\n cfg (dict): Configuration for building component.\n '
return build(cfg, COMPONENTS)
|
def build_loss(cfg):
'Build loss.\n\n Args:\n cfg (dict): Configuration for building loss.\n '
return build(cfg, LOSSES)
|
def build_model(cfg, train_cfg=None, test_cfg=None):
'Build model.\n\n Args:\n cfg (dict): Configuration for building model.\n train_cfg (dict): Training configuration. Default: None.\n test_cfg (dict): Testing configuration. Default: None.\n '
return build(cfg, MODELS, dict(train_c... |
@LOSSES.register_module()
class PerceptualLossGray(PerceptualLoss):
'Perceptual loss for gray-scale images.\n\n Differences to PerceptualLoss: Input x is a gray-scale image.\n '
def forward(self, x, gt):
x = x.repeat(1, 3, 1, 1)
if self.norm_img:
x = ((x + 1.0) * 0.5)
... |
@MODELS.register_module()
class ESRGANRestorer(BasicQERestorer):
'ESRGAN restorer for quality enhancement.\n\n Args:\n generator (dict): Config for the generator.\n discriminator (dict): Config for the discriminator. Default: None.\n gan_loss (dict): Config for the GAN loss.\n N... |
def read_json(json_path, losses, metrics):
'\n Examples:\n {\n "exp_name": "exp2.6",\n "mmedit Version": "0.16.1",\n "seed": 0,\n "env_info": "test"\n }\n {\n "mode": "train",\n "epoch": 1,\n "iter": 100,\n ... |
def plot_curve(data, ylabel, smooth=False, save_path=''):
keys = list(data.keys())
values = list(data.values())
if smooth:
window_size = 9
assert ((window_size % 2) == 1)
keys = keys[(window_size // 2):(- (window_size // 2))]
values = np.convolve(values, (np.ones(window_siz... |
def main():
parser = argparse.ArgumentParser(description='Parse JSON file')
parser.add_argument('json_path', type=str, help='Path to the JSON file')
parser.add_argument('--save-dir', type=str, default=None, help='Path to save the PNG')
args = parser.parse_args()
if osp.isdir(args.json_path):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.