repo stringlengths 1 99 | file stringlengths 13 215 | code stringlengths 12 59.2M | file_length int64 12 59.2M | avg_line_length float64 3.82 1.48M | max_line_length int64 12 2.51M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
synboost | synboost-master/image_synthesis_spade/data/image_folder.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
###############################################################################
# Code from
# https://github.com/pytorch/vision/blob/master/torc... | 3,137 | 30.69697 | 105 | py |
synboost | synboost-master/image_synthesis_spade/data/__init__.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import importlib
import torch.utils.data
from data.base_dataset import BaseDataset
def find_dataset_using_name(dataset_name):
# Given the ... | 1,877 | 33.145455 | 105 | py |
Spitfire | Spitfire-master/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Spitfire documentation build configuration file, created by
# sphinx-quickstart on Mon Dec 11 17:45:56 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... | 5,577 | 28.828877 | 100 | py |
SLRT | SLRT-main/NLA-SLR/gen_pose.py | # Copyright (c) OpenMMLab. All rights reserved.
# https://github.com/kennymckormick/pyskl/blob/main/tools/data/custom_2d_skeleton.py
import argparse
from gc import garbage
import os
from unittest.mock import NonCallableMagicMock
import os.path as osp
from torch.utils.data import DataLoader, sampler
import torch
import ... | 12,225 | 42.978417 | 179 | py |
SLRT | SLRT-main/NLA-SLR/prediction.py | from turtle import forward
import warnings, wandb
import pickle
from collections import defaultdict
from modelling.model import build_model
from utils.optimizer import build_optimizer, build_scheduler
warnings.filterwarnings("ignore")
import argparse
import numpy as np
import os, sys
import shutil
import time
import qu... | 14,168 | 49.603571 | 189 | py |
SLRT | SLRT-main/NLA-SLR/training.py | from typing import Text
import warnings
from modelling.model import build_model
from utils.optimizer import build_optimizer, build_scheduler, update_moving_average
warnings.filterwarnings("ignore")
import argparse
import numpy as np
import os, sys
import shutil
import time
import queue
sys.path.append(os.getcwd())#slt ... | 18,038 | 47.754054 | 172 | py |
SLRT | SLRT-main/NLA-SLR/dataset/Dataset.py | import torch, pickle
import json, os, gzip
from glob import glob
import numpy as np
from utils.misc import get_logger
Hrnet_Part2index = {
'pose': list(range(11)),
'hand': list(range(91, 133)),
'mouth': list(range(71,91)),
'face_others': list(range(23, 71))
}
for k_ in ['mouth','face_others', 'hand']:... | 5,272 | 38.94697 | 128 | py |
SLRT | SLRT-main/NLA-SLR/dataset/VideoLoader.py | import os, numpy as np
from utils.zipreader import ZipReader
import io, torch, torchvision
from PIL import Image
import lintel, random
def _load_frame_nums_to_4darray(video, frame_nums):
"""Decodes a specific set of frames from `video` to a 4D numpy array.
Args:
video: Encoded video.
data... | 8,677 | 38.09009 | 150 | py |
SLRT | SLRT-main/NLA-SLR/dataset/Dataloader.py | from dataset.VideoLoader import load_batch_video
from dataset.Dataset import build_dataset
import torch
from functools import partial
import random
def collate_fn_(batch, data_cfg, is_train, vocab, name2keypoint, word_emb_tab):
outputs = {'names': [sample['name'] for sample in batch],
'word_embs':... | 2,971 | 44.030303 | 153 | py |
SLRT | SLRT-main/NLA-SLR/utils/loss.py | from multiprocessing.sharedctypes import Value
import torch as t
import torch.nn as nn
import torch.nn.functional as F
import math
class LabelSmoothCE(nn.Module):
'''
This is the autograd version, you can also try the LabelSmoothSoftmaxCEV2 that uses derived gradients
'''
def __init__(self, lb_smooth... | 4,131 | 39.910891 | 139 | py |
SLRT | SLRT-main/NLA-SLR/utils/misc.py | import copy
from copyreg import pickle
import glob
import os
import os.path
import errno
import shutil
import random
import logging
from sys import platform
from logging import Logger
from typing import Callable, Optional
import numpy as np
import torch
from torch import nn, Tensor
import torch.nn.functional as F
impo... | 11,141 | 33.81875 | 132 | py |
SLRT | SLRT-main/NLA-SLR/utils/gen_gaussian.py | import torch
def gen_a_limb_heatmap(arr, starts, ends, sigma=1.0):
# https://github.com/kennymckormick/pyskl/blob/main/pyskl/datasets/pipelines/heatmap_related.py
"""Generate pseudo heatmap for one limb in one frame.
Args:
arr: The array to store the generated heatmaps. Shape: img_h * img_w.
... | 6,095 | 39.105263 | 140 | py |
SLRT | SLRT-main/NLA-SLR/utils/metrics.py | import torch
import numpy as np
def compute_accuracy(results, logits_name_lst, cls_num, device, name_lst=[], effective_label_idx=[], all_prob=None, eval_setting='origin'):
per_ins_stat_dict, per_cls_stat_dict = {}, {}
if eval_setting == 'origin':
for k in logits_name_lst:
correct = correct... | 7,616 | 48.461039 | 193 | py |
SLRT | SLRT-main/NLA-SLR/utils/optimizer.py | # coding: utf-8
"""
Collection of builder functions
"""
from typing import Callable, Optional, Generator
import torch
from torch import nn
# Learning Rate Scheduler
from torch.optim import lr_scheduler
from torch.optim.lr_scheduler import _LRScheduler
# Optimization Algorithms
from torch.optim import Optimizer
impor... | 14,247 | 34.267327 | 136 | py |
SLRT | SLRT-main/NLA-SLR/modelling/S3D_base.py | import torch
from torch import nn
import torch.nn.functional as F
class S3D_base(nn.Module):
def __init__(self, in_channels, use_block, coord_conv=None):
super(S3D_base, self).__init__()
base_seq = []
coord_setting1 = coord_setting2 = None
if coord_conv is not None:
if '... | 12,981 | 34.181572 | 168 | py |
SLRT | SLRT-main/NLA-SLR/modelling/four_stream.py | import torch
from torch import nn
import torch.nn.functional as F
from modelling.two_stream import S3D_two_stream_v2
from modelling.fusion import Lateral_Conn
class S3D_four_stream(nn.Module):
def __init__(self, use_block=5, freeze_block=(0,0), pose_inchannels=17, flag_lateral=[True, True], **kwargs):
sup... | 5,830 | 56.166667 | 176 | py |
SLRT | SLRT-main/NLA-SLR/modelling/fusion.py | import torch
from torch import nn
import torch.nn.functional as F
class Lateral_Conn(nn.Module):
def __init__(self, inchannels, outchannels, kernel_size=(7,3,3), ratio=(1,2,2), direction='rgb2pose', variant=None, interpolate=False, adapt_first=False):
super(Lateral_Conn, self).__init__()
# ratio: ... | 2,689 | 41.698413 | 158 | py |
SLRT | SLRT-main/NLA-SLR/modelling/model.py | from modelling.recognition import RecognitionNetwork
from utils.misc import get_logger
import torch
class SignLanguageModel(torch.nn.Module):
def __init__(self, cfg, cls_num, word_emb_tab=None) -> None:
super().__init__()
self.logger = get_logger()
self.device = cfg['device']
model... | 2,436 | 41.017241 | 110 | py |
SLRT | SLRT-main/NLA-SLR/modelling/S3D.py | import torch, glob, os
import torch.nn as nn
from utils.misc import get_logger, neq_load_customized
from modelling.S3D_base import S3D_base, BasicConv3d
BLOCK2SIZE = {1:64, 2:192, 3:480, 4:832, 5:1024}
class S3Ds(S3D_base):
def __init__(self, in_channel=3, use_block=5, freeze_block=0, coord_conv=None):
sel... | 5,216 | 38.824427 | 129 | py |
SLRT | SLRT-main/NLA-SLR/modelling/Visualhead.py | from re import X
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.misc import get_logger
import math
import numpy as np
class SepConvVisualHead(torch.nn.Module):
def __init__(self, cls_num, input_size=1024, hidden_size=512, ff_size=2048, pe=True,
ff_kernelsize=3, pretr... | 3,772 | 43.388235 | 126 | py |
SLRT | SLRT-main/NLA-SLR/modelling/two_stream.py | import torch
from torch import nn
import torch.nn.functional as F
from modelling.fusion import Lateral_Conn
from modelling.S3D import S3D_backbone
class S3D_two_stream_v2(nn.Module):
# use pyramid v2
def __init__(self, use_block=5, freeze_block=(0,0), pose_inchannels=17, flag_lateral=[False, False], **kwargs)... | 5,914 | 52.288288 | 182 | py |
SLRT | SLRT-main/NLA-SLR/modelling/recognition.py | import torch
from modelling.S3D import S3D_backbone
from modelling.two_stream import S3D_two_stream_v2
from modelling.four_stream import S3D_four_stream
from utils.misc import get_logger, neq_load_customized
import random, torchvision
from modelling.Visualhead import SepConvVisualHead
import numpy as np
from copy impor... | 39,745 | 58.233979 | 173 | py |
SLRT | SLRT-main/TwoStreamNetwork/prediction.py | from lib2to3.pytree import WildcardPattern
from logging import Logger
from typing import DefaultDict, Text
import warnings, wandb
import pickle
from google.protobuf.reflection import ParseMessage
from collections import defaultdict
from modelling.model import build_model
from modelling.recognition import ctc_decode_fun... | 10,958 | 46.855895 | 122 | py |
SLRT | SLRT-main/TwoStreamNetwork/training.py | import warnings, argparse, os, sys, shutil, time, queue
sys.path.append(os.getcwd())#slt dir
import numpy as np
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.tensorboard import SummaryWriter
from modelling.model import build_model
from utils.optimizer import build_optimizer... | 10,152 | 42.952381 | 131 | py |
SLRT | SLRT-main/TwoStreamNetwork/extract_feature.py | import warnings, pickle, gzip, argparse, os, sys
import numpy as np
import torch
from torch.nn.parallel import DistributedDataParallel as DDP
warnings.filterwarnings("ignore")
from modelling.model import build_model
sys.path.append(os.getcwd())#slt dir
from utils.misc import (
get_logger, load_config, make_logge... | 5,593 | 38.957143 | 117 | py |
SLRT | SLRT-main/TwoStreamNetwork/dataset/Dataset.py | from tkinter.filedialog import Open
import torch, pickle
import gzip, os
from glob import glob
import numpy as np
from utils.misc import get_logger
Openpose_Part2index = {
'pose': [('pose', [0,1,2,3,4,5,6,7,14,15,16,17])],
'mouth': [('face', list(range(48, 68)))],
'face_others': [('face', list(range(0,48))... | 4,695 | 43.72381 | 126 | py |
SLRT | SLRT-main/TwoStreamNetwork/dataset/VideoLoader.py | import os, numpy as np, random, io
from PIL import Image
from utils.zipreader import ZipReader
import torch, torchvision
def get_selected_indexs(vlen, tmin=1, tmax=1, num_tokens=1, max_num_frames=400):
if tmin==1 and tmax==1:
if vlen <= max_num_frames:
frame_index = np.arange(vlen)
... | 6,071 | 39.751678 | 115 | py |
SLRT | SLRT-main/TwoStreamNetwork/dataset/Dataloader.py | from dataset.VideoLoader import load_batch_video
from dataset.FeatureLoader import load_batch_feature
from dataset.Dataset import build_dataset
import torch
def collate_fn_(inputs, data_cfg, task, is_train,
text_tokenizer=None, gloss_tokenizer=None,name2keypoint=None):
outputs = {
'name':[i['name'] f... | 4,674 | 52.735632 | 115 | py |
SLRT | SLRT-main/TwoStreamNetwork/dataset/FeatureLoader.py | import torch
def load_batch_feature(features):
#features list of tensor
batch_features, lengths = [], []
lengths = [f.shape[0] for f in features]
max_length = max(lengths)
mask = torch.zeros([len(features), max_length],dtype=torch.long)
for ii,f in enumerate(features):
if f.shape[0]<max_... | 805 | 39.3 | 88 | py |
SLRT | SLRT-main/TwoStreamNetwork/preprocess/preprocess_plm.py | import torch, os, gzip, pickle, json, numpy as np
from copy import deepcopy
from tqdm import tqdm
from collections import defaultdict
import transformers
from transformers import MBartForConditionalGeneration, MBartTokenizer
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser("Prune word-em... | 1,603 | 37.190476 | 95 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/augmentation.py | import random
import numbers
import math
import collections
import torchvision
from torchvision import transforms
import torchvision.transforms.functional as F
from PIL import ImageOps, Image, ImageFilter
import numpy as np
class Padding:
def __init__(self, pad):
self.pad = pad
def __call__(self, img... | 18,287 | 37.02079 | 126 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/loss.py | import torch
from torch import nn, Tensor
from torch.autograd import Variable
class XentLoss(nn.Module):
"""
Cross-Entropy Loss with optional label smoothing
"""
def __init__(self, pad_index: int, smoothing: float = 0.0):
super(XentLoss, self).__init__()
self.smoothing = smoothing
... | 3,041 | 41.84507 | 85 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/misc.py | import copy
import glob
import os
import os.path
import errno
import shutil
import random
import logging
from sys import platform
from logging import Logger
from typing import Callable, Optional
import numpy as np
import torch
from torch import nn, Tensor
import yaml
from torch.utils.tensorboard import SummaryWriter
i... | 7,803 | 31.789916 | 107 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/gen_gaussian.py |
import torch
def gen_gaussian_hmap_op(coords, raw_size=(260,210), map_size=None, sigma=1, confidence=False, threshold=0, **kwargs):
# openpose version
# pose [T,18,3]; face [T,70,3]; hand_0(left) [T,21,3]; hand_1(right) [T,21,3]
# gamma: hyper-param, control the width of gaussian, larger gamma, SMALLE... | 1,571 | 36.428571 | 118 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/video_transformation.py | # define project dependency
from numpy.random import SeedSequence
from functools import partial
import os, glob, pickle, random
import numpy as np
from tqdm import tqdm
import torch
import torch.nn as nn
from torch.utils import data
import torchvision
from torchvision import transforms
import torch.distributed as di... | 5,345 | 36.125 | 89 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/optimizer.py | # coding: utf-8
"""
Collection of builder functions
"""
from typing import Callable, Optional, Generator
import torch
from torch import nn
# Learning Rate Scheduler
from torch.optim import lr_scheduler
from torch.optim.lr_scheduler import _LRScheduler
# Optimization Algorithms
from torch.optim import Optimizer
impor... | 13,340 | 33.651948 | 104 | py |
SLRT | SLRT-main/TwoStreamNetwork/utils/transforms.py | # from references/video_classification
# and torchvision/transforms/functional_tensor.py
# Support data argumentation for 4D tensor, [N, H, W, C]
import torch
import random
import numbers
import torchvision
import numpy as np
import math
def crop(vid, i, j, h, w):
return vid[..., i:(i + h), j:(j + w)]
def cen... | 13,797 | 34.19898 | 123 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/translation_ensemble.py | import torch
from transformers import MBartForConditionalGeneration,MBartConfig
from transformers.modeling_utils import PreTrainedModel
from transformers.file_utils import ModelOutput
from utils.misc import freeze_params, get_logger
from utils.loss import XentLoss
from .Tokenizer import GlossTokenizer_G2T, TextTokenize... | 9,596 | 44.056338 | 139 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/translation.py | import torch
from transformers import MBartForConditionalGeneration, MBartTokenizer, MBartConfig
from utils.misc import freeze_params, get_logger
from utils.loss import XentLoss
from .Tokenizer import GlossTokenizer_G2T, TextTokenizer
import pickle, math
class TranslationNetwork(torch.nn.Module):
def __init__(self... | 11,020 | 49.555046 | 158 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/fusion.py | import torch
from torch import nn
import torch.nn.functional as F
class Lateral_Conn(nn.Module):
def __init__(self, inchannels, outchannels, kernel_size=(7,3,3), ratio=(1,2,2), direction='rgb2pose'):
super(Lateral_Conn, self).__init__()
# ratio: temporal, height, width
# kernel_size: tempo... | 1,572 | 37.365854 | 124 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/vl_mapper.py | import torch, os
from utils.misc import freeze_params, get_logger
class VLMapper(torch.nn.Module):
def __init__(self, cfg, in_features, out_features,
gloss_id2str=None,
gls2embed=None,
freeze=False) -> None:
super().__init__()
logger = get_logger()
self.type = cfg.ge... | 1,797 | 37.255319 | 88 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/utils.py | import torch, math
import torch.nn as nn
from torch import Tensor
class MLPHead(nn.Module):
def __init__(self, embedding_size, projection_hidden_size):
super().__init__()
self.embedding_size = embedding_size
self.net = nn.Sequential(nn.Linear(self.embedding_size, projection_hidden_size),
... | 6,046 | 38.266234 | 109 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/model.py | import torch
from modelling.recognition import RecognitionNetwork
from utils.misc import get_logger
from modelling.translation import TranslationNetwork
from modelling.translation_ensemble import TranslationNetwork_Ensemble
from modelling.vl_mapper import VLMapper
class SignLanguageModel(torch.nn.Module):
def __in... | 6,463 | 49.108527 | 113 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/S3D.py | import torch, glob, os
from utils.misc import get_logger, neq_load_customized
from modelling.models_3d.S3D.model import S3Dsup
from modelling.pyramid import PyramidNetwork, PyramidNetwork_v2
BLOCK2SIZE = {1:64, 2:192, 3:480, 4:832, 5:1024}
class S3Ds(S3Dsup):
def __init__(self, in_channel=3, use_block=5, freeze_bl... | 6,268 | 41.646259 | 162 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/pyramid.py | import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
class ConvModule(nn.Module):
def __init__(
self,
inplanes,
planes,
kernel_size,
stride,
padding,
bias=False,
groups=1,
):
... | 8,694 | 38.343891 | 164 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/Visualhead.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.misc import get_logger
from modelling.utils import PositionalEncoding, MaskedNorm, PositionwiseFeedForward, MLPHead
class VisualHead(torch.nn.Module):
def __init__(self,
cls_num, input_size=832, hidden_size=512, ff_size=2048, pe=... | 5,261 | 40.433071 | 129 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/two_stream.py | import torch
from torch import nn
import torch.nn.functional as F
from modelling.fusion import Lateral_Conn
from modelling.S3D import S3D_backbone
class S3D_two_stream_v2(nn.Module):
def __init__(self, use_block=4, freeze_block=(1,0), downsample=2, pose_inchannels=17, flag_lateral=[False, False], **kwargs):
... | 6,704 | 52.64 | 145 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/recognition.py | import math
from copy import deepcopy
import random, torchvision
import numpy as np
import tensorflow as tf
import torch
from itertools import groupby
from modelling.S3D import S3D_backbone
from modelling.two_stream import S3D_two_stream_v2
from utils.misc import get_logger, neq_load_customized
from modelling.Tokenize... | 45,247 | 62.107392 | 171 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/Tokenizer.py | from json import decoder
import torch, pickle, json
from collections import defaultdict
from transformers import MBartTokenizer
def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, ignore_index: int=-100):
"""
Shift input ids one token to the right, and wrap the last non pad token (the <LID> toke... | 11,513 | 45.804878 | 118 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/models_3d/S3D/main.py | import os
import numpy as np
import cv2
import torch
from modelling.models_3d.S3D.model import S3D
def main():
''' Output the top 5 Kinetics classes predicted by the model '''
path_sample = './sample'
file_weight = './S3D_kinetics400.pt'
class_names = [c.strip() for c in open('./label_map.txt')]
nu... | 2,200 | 28.346667 | 102 | py |
SLRT | SLRT-main/TwoStreamNetwork/modelling/models_3d/S3D/model.py | import torch
from torch import nn
import torch.nn.functional as F
class S3Dsup(nn.Module):
def __init__(self, in_channels, num_class, use_block, stride):
super(S3Dsup, self).__init__()
base_seq = []
if use_block>=1:
base_seq += [
SepConv3d(in_channels, 64, kernel... | 11,716 | 32.286932 | 162 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/main.py | """Main code driver
"""
import logging
import os
import sys
import time
from pathlib import Path
import humanize
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import evaluate
import models
import opts
from datasets.multidataloader import MultiDataLoader
f... | 6,844 | 31.908654 | 86 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/epoch.py | import os
import time
import numpy as np
import torch
from utils import Bar
from utils.evaluation.averagemeter import AverageMeter
from utils.evaluation.classification import performance
from utils.misc import (
is_show,
save_pred,
)
from utils.vizutils import viz_gt_pred
import pickle
def save_file(name2feat... | 3,866 | 28.295455 | 127 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/extract_sign_features.py | """Main code driver
"""
import logging
import os
import sys
import time
from pathlib import Path
import humanize
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import evaluate
import models
import opts
from datasets.multidataloader import MultiDataLoader
f... | 6,669 | 31.067308 | 86 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/evaluate.py | # Example usage:
# source activate pytorch1.3_env
""" python evaluate.py \
--datasetname bsl1k \
--checkpoint checkpoint/bsl1k/c1064_16f_unfreezei3d_m9/test_050/ \
--num-classes 1064 --num_in_frames 16 --stride 0.5 \
--nperf 3 --topk 1 5 10 \
--word_data_pkl misc/bsldict/subtitles/data/words_mouthin... | 10,943 | 36.098305 | 132 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/epoch_pseudo.py | import os
import time
import numpy as np
import torch
from utils import Bar
from utils.evaluation.averagemeter import AverageMeter
from utils.evaluation.classification import performance
from utils.misc import (
is_show,
save_pred,
)
from utils.vizutils import viz_gt_pred
import pickle
import torch.nn.functio... | 7,892 | 34.554054 | 159 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/evaluate_H2S.py | # Example usage:
"""
source activate pytorch1.3
python evaluate_seq.py --datasetname phoenix2014 \
--checkpoint checkpoint/phoenix2014/T_c1233_ctc_blank_unfreeze/test_002_stride0.50/ \
--num-classes 1233 --num_in_frames 16 --stride 0.5 \
--phoenix_path data/PHOENIX-2014-T-release-v3/PHOENIX-2014-T \
"""
imp... | 7,051 | 34.084577 | 113 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/evaluate_seq.py | # Example usage:
"""
source activate pytorch1.3
python evaluate_seq.py --datasetname phoenix2014 \
--checkpoint checkpoint/phoenix2014/T_c1233_ctc_blank_unfreeze/test_002_stride0.50/ \
--num-classes 1233 --num_in_frames 16 --stride 0.5 \
--phoenix_path data/PHOENIX-2014-T-release-v3/PHOENIX-2014-T \
"""
imp... | 7,050 | 34.079602 | 113 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/main_psuedo.py | """Main code driver
"""
import logging
import os
import sys
import time
from pathlib import Path
import humanize
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import evaluate
import models
import opts
from datasets.multidataloader import MultiDataLoader
f... | 6,508 | 32.040609 | 86 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/generate_pseudo_labels.py | """Main code driver
"""
import logging
import os
import sys
import time
from pathlib import Path
import humanize
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import evaluate
import models
import opts
from datasets.multidataloader import MultiDataLoader
f... | 6,513 | 32.06599 | 86 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/models/i3d.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ["InceptionI3d"]
class MaxPool3dSamePadding(nn.MaxPool3d):
def compute_pad(self, dim, s):
if s % self.stride[dim] == 0:
return max(self.kernel_size[dim] - self.stride[dim], 0)
else:
r... | 14,914 | 32.144444 | 126 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/models/pose2sign.py | import torch
import torch.nn as nn
__all__ = ["Pose2Sign"]
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=dilation,
groups=gro... | 8,381 | 31.614786 | 106 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/datasets/multidataloader.py | import copy
import mock
import torch
import datasets
from beartype import beartype
from datasets.videodataset import VideoDataset
class MultiDataLoader:
def __init__(self, train_datasets, val_datasets):
self.datasets = {"train": train_datasets, "val": val_datasets}
print("Data loading info:")
... | 3,133 | 33.065217 | 86 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/datasets/videodataset.py | import math
import os
import pickle as pkl
import random
from abc import abstractmethod
from collections import OrderedDict, defaultdict
import cv2
import numpy as np
import torch
import torch.utils.data as data
from beartype import beartype
from utils.imutils import (im_to_numpy, im_to_torch, im_to_video,
... | 22,165 | 40.431776 | 89 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/utils/misc.py | import errno
import functools
import getpass
import os
import pickle as pkl
import shutil
import sys
import time
from datetime import datetime
from pathlib import Path
import numpy as np
import scipy.io
import torch
def mkdir_p(dir_path):
try:
os.makedirs(dir_path)
except OSError as e:
if e.e... | 6,008 | 30.460733 | 92 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/utils/logger.py | # A simple tensorboard logger
import getpass
import json
import logging.config
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from utils.misc import Timer
__all__ = ["Logger", "savefig"]
def savefig(fname, dpi=None):
dpi ... | 7,803 | 33.839286 | 88 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/utils/imutils.py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc
import scipy.ndimage
from PIL import Image, ImageDraw, ImageFont
from .misc import to_numpy, to_torch
def im_to_numpy(img):
img = to_numpy(img)
img = np.transpose(img, (1, 2, 0)) # H*W*C
return img
def im_to_torch(img):
... | 4,617 | 32.223022 | 124 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/utils/vizutils.py | import getpass
from os.path import dirname
import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc
import torch
from PIL import Image
from utils.imutils import rectangle_on_image, text_on_image
from .misc import mkdir_p, to_numpy
def _imshow_pytorch(rgb, ax=None):
from utils.transforms ... | 5,488 | 29.159341 | 90 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/utils/transforms.py | import random
import numpy as np
import torch
from .imutils import im_to_video, video_to_im
def bbox_format(bbox, src, dest):
if src == "yxyx" and dest == "cenhw":
hw = bbox[:, 2:] - bbox[:, :2]
cen = bbox[:, :2] + (hw / 2)
bbox = np.hstack((cen, hw))
elif src == "cenhw" and dest == ... | 4,316 | 37.544643 | 87 | py |
SLRT | SLRT-main/CiCo/I3D_feature_extractor/utils/evaluation/classification.py | def performance(output, target, topk=[1, 5]):
"""
Returns the accuracy at top-k over a batch
output: [batchsize x num_classes] torch matrix, output of the model
target: [batchsize] torch vector, indices of the GT classes
topk: list of k values
"""
maxk = max(topk)
batch_size ... | 588 | 30 | 75 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/main.py | """Main code driver
"""
import logging
import os
import sys
import time
from pathlib import Path
import humanize
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn.parallel
import torch.optim
import evaluate
import models
import opts
from datasets.multidataloader import MultiDataLoader
f... | 10,743 | 32.263158 | 137 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/epoch.py | import os
import time
import numpy as np
import torch
from utils import Bar
from utils.evaluation.averagemeter import AverageMeter
from utils.evaluation.classification import performance
from utils.misc import (
is_show,
save_pred,
)
from utils.vizutils import viz_gt_pred
# ---------------------------------... | 4,660 | 27.950311 | 148 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/evaluate.py | # Example usage:
# source activate pytorch1.3_env
""" python evaluate.py \
--datasetname bsl1k \
--checkpoint checkpoint/bsl1k/c1064_16f_unfreezei3d_m9/test_050/ \
--num-classes 1064 --num_in_frames 16 --stride 0.5 \
--nperf 3 --topk 1 5 10 \
--word_data_pkl misc/bsldict/subtitles/data/words_mouthin... | 10,943 | 36.098305 | 132 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/models/i3d.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ["InceptionI3d"]
class MaxPool3dSamePadding(nn.MaxPool3d):
def compute_pad(self, dim, s):
if s % self.stride[dim] == 0:
return max(self.kernel_size[dim] - self.stride[dim], 0)
else:
r... | 14,914 | 32.144444 | 126 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/models/pose2sign.py | import torch
import torch.nn as nn
__all__ = ["Pose2Sign"]
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(
in_planes,
out_planes,
kernel_size=3,
stride=stride,
padding=dilation,
groups=gro... | 8,381 | 31.614786 | 106 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/datasets/multidataloader.py | import copy
import mock
import torch
import datasets
from beartype import beartype
from datasets.videodataset import VideoDataset
class MultiDataLoader:
def __init__(self, train_datasets, val_datasets):
self.datasets = {"train": train_datasets, "val": val_datasets}
print("Data loading info:")
... | 3,263 | 31.64 | 86 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/datasets/videodataset.py | import math
import os
import pickle as pkl
import random
from abc import abstractmethod
from collections import OrderedDict, defaultdict
from PIL import Image
import cv2
import numpy as np
import torch
import torch.utils.data as data
from beartype import beartype
from utils.imutils import (im_to_numpy, im_to_torch, im... | 22,805 | 40.922794 | 104 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/utils/misc.py | import errno
import functools
import getpass
import os
import pickle as pkl
import shutil
import sys
import time
from datetime import datetime
from pathlib import Path
import numpy as np
import scipy.io
import torch
def mkdir_p(dir_path):
try:
os.makedirs(dir_path)
except OSError as e:
if e.e... | 6,066 | 30.598958 | 92 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/utils/logger.py | # A simple tensorboard logger
import getpass
import json
import logging.config
import os
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from utils.misc import Timer
__all__ = ["Logger", "savefig"]
def savefig(fname, dpi=None):
dpi ... | 7,803 | 33.839286 | 88 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/utils/imutils.py | import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc
import scipy.ndimage
from PIL import Image, ImageDraw, ImageFont
from .misc import to_numpy, to_torch
def im_to_numpy(img):
img = to_numpy(img)
img = np.transpose(img, (1, 2, 0)) # H*W*C
return img
def im_to_torch(img):
... | 4,617 | 32.223022 | 124 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/utils/vizutils.py | import getpass
from os.path import dirname
import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.misc
import torch
from PIL import Image
from utils.imutils import rectangle_on_image, text_on_image
from .misc import mkdir_p, to_numpy
def _imshow_pytorch(rgb, ax=None):
from utils.transforms ... | 5,488 | 29.159341 | 90 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/utils/transforms.py | import random
import numpy as np
import torch
from .imutils import im_to_video, video_to_im
def bbox_format(bbox, src, dest):
if src == "yxyx" and dest == "cenhw":
hw = bbox[:, 2:] - bbox[:, :2]
cen = bbox[:, :2] + (hw / 2)
bbox = np.hstack((cen, hw))
elif src == "cenhw" and dest == ... | 4,316 | 37.544643 | 87 | py |
SLRT | SLRT-main/CiCo/I3D_trainer/utils/evaluation/classification.py | def performance(output, target, topk=[1, 5]):
"""
Returns the accuracy at top-k over a batch
output: [batchsize x num_classes] torch matrix, output of the model
target: [batchsize] torch vector, indices of the GT classes
topk: list of k values
"""
maxk = max(topk)
batch_size ... | 588 | 30 | 75 | py |
SLRT | SLRT-main/CiCo/CLCL/main_task_retrieval.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
from datetime import datetime
import torch
import numpy as np
import random
import os
from metrics import compute_metrics, tensor_text_to_video_metrics, tensor_video_to_te... | 39,368 | 46.777913 | 190 | py |
SLRT | SLRT-main/CiCo/CLCL/util.py | import torch
import torch.nn as nn
import threading
from torch._utils import ExceptionWrapper
import logging
def get_a_var(obj):
if isinstance(obj, torch.Tensor):
return obj
if isinstance(obj, list) or isinstance(obj, tuple):
for result in map(get_a_var, obj):
if isinstance(result,... | 2,495 | 33.191781 | 99 | py |
SLRT | SLRT-main/CiCo/CLCL/metrics.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import numpy as np
import torch
def compute_metrics(x):
sx = np.sort(-x, axis=1)
d = np.diag(-x)
d = d[:, np.newaxis]
ind = sx - d
ind = np.where(ind... | 3,029 | 41.676056 | 103 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | 7,259 | 42.214286 | 141 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/module_clip.py | """
Adapted from: https://github.com/openai/CLIP/blob/main/clip/clip.py
"""
from collections import OrderedDict
from typing import Tuple, Union
import hashlib
import os
import urllib
import warnings
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch import nn
import math
_MODELS = {
"R... | 29,588 | 40.095833 | 178 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/modeling.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import copy
import torch
from torch import nn
from modules.until_module import PreTrainedModel, AllGather, CrossEn
from modules.module_cross import CrossModel, CrossConfig, Transformer as Transf... | 30,463 | 51.253859 | 210 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/until_module.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy... | 11,390 | 39.393617 | 114 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/module_cross.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import copy
import json
import math
import logging
import tarfile
import tempfile
import shutil
import torch
from torch import nn
import torch.nn.functional as F
from .file_utils import cached_path
f... | 9,833 | 42.706667 | 116 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
import os
import logging
import shutil
import tempfile
import json
from urllib.parse import urlparse
from pathlib import Path
from typing ... | 8,021 | 32.425 | 98 | py |
SLRT | SLRT-main/CiCo/CLCL/modules/until_config.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy... | 5,036 | 38.97619 | 105 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/dataloader_csl_retrieval.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import torch
import os
from torch.utils.data import Dataset
import numpy as np
import pickle
from dataloaders.rawvideo_util import RawVideoExtractor
import random
class ... | 9,646 | 42.651584 | 145 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/data_dataloaders.py | import torch
from torch.utils.data import DataLoader
from dataloaders.dataloader_H2_retrieval import H2_DataLoader
from dataloaders.dataloader_ph_retrieval import ph_DataLoader
from dataloaders.dataloader_ph_retrieval_train import ph_DataLoader_train
from dataloaders.dataloader_H2_retrieval_train import H2_DataLoader... | 5,941 | 29.947917 | 110 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/rawvideo_util.py | import torch as th
import numpy as np
from PIL import Image
# pytorch=1.7.1
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
# pip install opencv-python
import cv2
class RawVideoExtractorCV2():
def __init__(self, centercrop=False, size=224, framerate=-1, ):
self.centercro... | 3,715 | 36.535354 | 138 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/dataloader_H2_retrieval_train.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('omw-1.4')
import torch
... | 12,840 | 42.976027 | 127 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/dataloader_csl_retrieval_train.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import nltk
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('omw-1.4')
import torch
... | 12,840 | 43.127148 | 127 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/dataloader_ph_retrieval_train.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import torch
import os
from torch.utils.data import Dataset
import numpy as np
import pickle
from dataloaders.rawvideo_util import RawVideoExtractor
import random
import n... | 12,118 | 42.593525 | 118 | py |
SLRT | SLRT-main/CiCo/CLCL/dataloaders/dataloader_H2_retrieval.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import torch
import os
from torch.utils.data import Dataset
import numpy as np
import pickle
from dataloaders.rawvideo_util import RawVideoExtractor
import random
class H... | 9,635 | 42.8 | 145 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.