python_code
stringlengths
0
992k
repo_name
stringlengths
8
46
file_path
stringlengths
5
162
from .base import BaseLocalizer from .bmn import BMN from .bsn import PEM, TEM from .ssn import SSN __all__ = ['PEM', 'TEM', 'BMN', 'SSN', 'BaseLocalizer']
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/models/localizers/__init__.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from ...localization import temporal_iop from ..builder import build_loss from ..registry import LOCALIZERS from .base import BaseLocalizer from .utils import post_processing @LOCALIZERS.register_module() class TEM(BaseLocalizer): ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/models/localizers/bsn.py
from abc import ABCMeta, abstractmethod from collections import OrderedDict import torch import torch.distributed as dist import torch.nn as nn from .. import builder class BaseLocalizer(nn.Module, metaclass=ABCMeta): """Base class for localizers. All localizers should subclass it. All subclass should over...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/models/localizers/base.py
from .post_processing import post_processing __all__ = ['post_processing']
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/models/localizers/utils/__init__.py
from mmaction.localization import soft_nms def post_processing(result, video_info, soft_nms_alpha, soft_nms_low_threshold, soft_nms_high_threshold, post_process_top_k, feature_extraction_interval): """Post process for temporal proposals generation. Args: result...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/models/localizers/utils/post_processing.py
from .bsn_utils import generate_bsp_feature, generate_candidate_proposals from .proposal_utils import soft_nms, temporal_iop, temporal_iou from .ssn_utils import (eval_ap, load_localize_proposal_file, perform_regression, temporal_nms) __all__ = [ 'generate_candidate_proposals', 'generate_bs...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/localization/__init__.py
import os.path as osp import numpy as np from .proposal_utils import temporal_iop, temporal_iou def generate_candidate_proposals(video_list, video_infos, tem_results_dir, temporal_scale, ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/localization/bsn_utils.py
import numpy as np def temporal_iou(proposal_min, proposal_max, gt_min, gt_max): """Compute IoU score between a groundtruth bbox and the proposals. Args: proposal_min (list[float]): List of temporal anchor min. proposal_max (list[float]): List of temporal anchor max. gt_min (float): G...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/localization/proposal_utils.py
from itertools import groupby import numpy as np from ..core import average_precision_at_temporal_iou from . import temporal_iou def load_localize_proposal_file(filename): """Load the proposal file and split it into many parts which contain one video's information separately. Args: filename(str...
InternVideo-main
Downstream/Open-Set-Action-Recognition/mmaction/localization/ssn_utils.py
import argparse import mmcv import numpy as np import torch from mmcv.runner import load_checkpoint from mmaction.models import build_model try: import onnx import onnxruntime as rt except ImportError as e: raise ImportError(f'Please install onnx and onnxruntime first. {e}') try: from mmcv.onnx.symb...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/pytorch2onnx.py
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/__init__.py
import argparse import os import os.path as osp import cv2 import numpy as np def flow_to_img(raw_flow, bound=20.): """Convert flow to gray image. Args: raw_flow (np.ndarray[float]): Estimated flow with the shape (w, h). bound (float): Bound for the flow-to-image normalization. Default: 20. ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/flow_extraction.py
import argparse import os import os.path as osp import warnings import mmcv import torch from mmcv import Config, DictAction from mmcv.cnn import fuse_conv_bn from mmcv.fileio.io import file_handlers from mmcv.parallel import MMDataParallel, MMDistributedDataParallel from mmcv.runner import get_dist_info, init_dist, l...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/test.py
import argparse import subprocess import torch def parse_args(): parser = argparse.ArgumentParser( description='Process a checkpoint to be published') parser.add_argument('in_file', help='input checkpoint filename') parser.add_argument('out_file', help='output checkpoint filename') args = par...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/publish_model.py
import argparse import os import os.path as osp import mmcv import numpy as np import torch.multiprocessing as mp from mmaction.localization import (generate_bsp_feature, generate_candidate_proposals) def load_video_infos(ann_file): """Load the video annotations. Args: ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/bsn_proposal_generation.py
import argparse import copy import os import os.path as osp import time import warnings import mmcv import torch from mmcv import Config, DictAction from mmcv.runner import init_dist, set_random_seed from mmcv.utils import get_git_hash from mmaction import __version__ from mmaction.apis import train_model from mmacti...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/train.py
import argparse import copy import os import os.path as osp import time import warnings import mmcv import torch from mmcv import Config, DictAction from mmcv.runner import init_dist, set_random_seed from mmcv.utils import get_git_hash import numpy as np from mmaction import __version__ from mmaction.apis import trai...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/hypertune.py
import argparse import mmcv from mmcv import Config, DictAction from mmaction.datasets import build_dataset def parse_args(): parser = argparse.ArgumentParser(description='Evaluate metric of the ' 'results saved in pkl/yaml/json format') parser.add_argument('config', hel...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/eval_metric.py
import argparse import time import torch from mmcv import Config from mmcv.cnn import fuse_conv_bn from mmcv.parallel import MMDataParallel from mmcv.runner.fp16_utils import wrap_fp16_model from mmaction.datasets import build_dataloader, build_dataset from mmaction.models import build_model def parse_args(): p...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/benchmark.py
import argparse from mmcv import Config, DictAction def parse_args(): parser = argparse.ArgumentParser(description='Print the whole config') parser.add_argument('config', help='config file path') parser.add_argument( '--options', nargs='+', action=DictAction, help='arguments in dict') args = ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/print_config.py
import argparse from mmcv import load from scipy.special import softmax from mmaction.core.evaluation import (get_weighted_score, mean_class_accuracy, top_k_accuracy) def parse_args(): parser = argparse.ArgumentParser(description='Fusing multiple scores') parser.add_arg...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/report_accuracy.py
"""This file is for benchmark dataloading process. The command line to run this file is: $ python -m cProfile -o program.prof tools/analysis/bench_processing.py configs/task/method/[config filename] It use cProfile to record cpu running time and output to program.prof To visualize cProfile output program.prof, use Sn...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/bench_processing.py
import argparse from mmcv import Config from mmaction.models import build_recognizer try: from mmcv.cnn import get_model_complexity_info except ImportError: raise ImportError('Please upgrade mmcv to >0.6.2') def parse_args(): parser = argparse.ArgumentParser(description='Train a recognizer') parser...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/get_flops.py
import argparse import os import os.path as osp import mmcv import numpy as np from mmaction.core import ActivityNetDetection args = None def cuhk17_top1(): """Assign label for each proposal with the cuhk17 result, which is the #2 entry in http://activity-net.org/challenges/2017/evaluation.html.""" if ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/report_map.py
import argparse import json from collections import defaultdict import matplotlib.pyplot as plt import numpy as np import seaborn as sns def cal_train_time(log_dicts, args): for i, log_dict in enumerate(log_dicts): print(f'{"-" * 5}Analyze train time of {args.json_logs[i]}{"-" * 5}') all_times = ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/analysis/analyze_logs.py
import argparse import glob import os import os.path as osp from multiprocessing import Pool import mmcv def extract_audio_wav(line): """Extract the audio wave from video streams using FFMPEG.""" video_id, _ = osp.splitext(osp.basename(line)) video_dir = osp.dirname(line) video_rel_dir = osp.relpath(...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/extract_audio.py
import argparse import mmcv def parse_args(): parser = argparse.ArgumentParser( description='Convert txt annotation list to json') parser.add_argument( 'annofile', type=str, help='the txt annotation file to convert') parser.add_argument( '--format', type=str, defau...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/anno_txt2json.py
import argparse import glob import json import os.path as osp import random from mmcv.runner import set_random_seed from tools.data.anno_txt2json import lines2dictlist from tools.data.parse_file_list import (parse_directory, parse_hmdb51_split, parse_jester_splits, ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/build_file_list.py
import argparse import glob import os import os.path as osp import sys import warnings from multiprocessing import Pool import mmcv import numpy as np def extract_frame(vid_item): """Generate optical flow using dense flow. Args: vid_item (list): Video item containing video full path, vid...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/build_rawframes.py
import os, argparse import cv2 from tqdm import tqdm if __name__ == '__main__': parser = argparse.ArgumentParser(description='Check the data') parser.add_argument('video_path', type=str, help='The video path') parser.add_argument('dataset_list', type=str, help='The list file of dataset.') parser.add_a...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/data_check.py
import argparse import glob import os import os.path as osp import sys from multiprocessing import Pool def encode_video(frame_dir_item): """Encode frames to video using ffmpeg. Args: frame_dir_item (list): Rawframe item containing raw frame directory full path, rawframe directory (short)...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/build_videos.py
import csv import fnmatch import glob import json import os import os.path as osp def parse_directory(path, rgb_prefix='img_', flow_x_prefix='flow_x_', flow_y_prefix='flow_y_', level=1): """Parse directories holding extracted frames f...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/parse_file_list.py
import argparse import os.path as osp from tools.data.parse_file_list import parse_directory from mmaction.localization import load_localize_proposal_file def process_norm_proposal_file(norm_proposal_file, frame_dict): """Process the normalized proposal file and denormalize it. Args: norm_proposal_...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/denormalize_proposal_file.py
import argparse import glob import os import os.path as osp import sys from multiprocessing import Pool import mmcv import numpy as np from scipy.io import wavfile try: import librosa import lws except ImportError: print('Please import librosa, lws first.') sys.path.append('..') SILENCE_THRESHOLD = 2 FM...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/build_audio_features.py
import argparse import glob import os import os.path as osp import sys from multiprocessing import Pool def resize_videos(vid_item): """Generate resized video cache. Args: vid_item (list): Video item containing video full path, video relative path. Returns: bool: Whether gene...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/resize_video.py
import os import os.path as osp import sys from subprocess import check_output import mmcv def get_duration(vid_name): command = f'ffprobe -i {vid_name} 2>&1 | grep "Duration"' output = str(check_output(command, shell=True)) output = output.split(',')[0].split('Duration:')[1].strip() h, m, s = output...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/omnisource/trim_raw_video.py
import argparse import multiprocessing import os import os.path as osp import numpy as np import scipy.interpolate from mmcv import dump, load args = None def parse_args(): parser = argparse.ArgumentParser(description='ANet Feature Prepare') parser.add_argument('--rgb', default='', help='rgb feature root') ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/activitynet/activitynet_feature_postprocessing.py
# This scripts is copied from # https://github.com/activitynet/ActivityNet/blob/master/Crawler/Kinetics/download.py # noqa: E501 # The code is licensed under the MIT licence. import os import ssl import subprocess import mmcv from joblib import Parallel, delayed ssl._create_default_https_context = ssl._create_unveri...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/activitynet/download.py
import os import os.path as osp import mmcv data_file = '../../../data/ActivityNet' video_list = f'{data_file}/video_info_new.csv' anno_file = f'{data_file}/anet_anno_action.json' rawframe_dir = f'{data_file}/rawframes' action_name_list = 'action_name.csv' def generate_rawframes_filelist(): anet_annotations = m...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/activitynet/generate_rawframes_filelist.py
"""This file converts the output proposal file of proposal generator (BSN, BMN) into the input proposal file of action classifier (Currently supports SSN and P-GCN, not including TSN, I3D etc.).""" import argparse import mmcv import numpy as np from mmaction.core import pairwise_temporal_iou def load_annotations(an...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/activitynet/convert_proposal_format.py
import argparse import os import os.path as osp import pickle import mmcv import numpy as np import torch from mmaction.datasets.pipelines import Compose from mmaction.models import build_model def parse_args(): parser = argparse.ArgumentParser(description='Extract TSN Feature') parser.add_argument('--data-...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/activitynet/tsn_feature_extraction.py
"""This file processes the annotation files and generates proper annotation files for localizers.""" import json import numpy as np def load_json(file): with open(file) as json_file: data = json.load(json_file) return data data_file = '../../../data/ActivityNet' info_file = f'{data_file}/video_...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/activitynet/process_annotations.py
# ------------------------------------------------------------------------------ # Adapted from https://github.com/activitynet/ActivityNet/ # Original licence: Copyright (c) Microsoft, under the MIT License. # ------------------------------------------------------------------------------ import argparse import glob imp...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/kinetics/download.py
# ------------------------------------------------------------------------------ # Adapted from https://github.com/activitynet/ActivityNet/ # Original licence: Copyright (c) Microsoft, under the MIT License. # ------------------------------------------------------------------------------ import argparse import glob imp...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/kinetics/download_subset.py
import argparse import os.path as osp import subprocess import mmcv from joblib import Parallel, delayed URL_PREFIX = 'https://s3.amazonaws.com/ava-dataset/trainval/' def download_video(video_url, output_dir, num_attempts=5): video_file = osp.basename(video_url) output_file = osp.join(output_dir, video_file...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/ava/download_videos_parallel.py
# ------------------------------------------------------------------------------ # Adapted from https://github.com/activitynet/ActivityNet/ # Original licence: Copyright (c) Microsoft, under the MIT License. # ------------------------------------------------------------------------------ import argparse import glob im...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/hvu/download.py
import mmcv tag_list = '../../../data/hvu/annotations/hvu_categories.csv' lines = open(tag_list).readlines() lines = [x.strip().split(',') for x in lines[1:]] tag_categories = {} for line in lines: tag, category = line tag_categories.setdefault(category, []).append(tag) for k in tag_categories: tag_categ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/hvu/parse_tag_list.py
import argparse import os.path as osp import mmcv def main(annotation_file, category): assert category in [ 'action', 'attribute', 'concept', 'event', 'object', 'scene' ] data = mmcv.load(annotation_file) basename = osp.basename(annotation_file) dirname = osp.dirname(annotation_file) ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/hvu/generate_sub_file_list.py
import argparse import fnmatch import glob import os import os.path as osp import mmcv annotation_root = '../../data/hvu/annotations' tag_file = 'hvu_tags.json' args = None def parse_directory(path, rgb_prefix='img_', flow_x_prefix='flow_x_', flow_y_prefix...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/hvu/generate_file_list.py
import os, argparse from sklearn.utils import shuffle def parse_args(): parser = argparse.ArgumentParser(description='Build file list') parser.add_argument('dataset', type=str, choices=['mimetics10', 'mimetics'], help='dataset to be built file list') parser.add_argument('src_folder', type=str, help='root...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/mimetics/build_file_list.py
# This scripts is copied from # https://github.com/activitynet/ActivityNet/blob/master/Crawler/Kinetics/download.py # noqa: E501 # The code is licensed under the MIT licence. import argparse import os import ssl import subprocess import mmcv from joblib import Parallel, delayed import youtube_dl import glob ssl._cre...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/gym/download_ytdl.py
# This scripts is copied from # https://github.com/activitynet/ActivityNet/blob/master/Crawler/Kinetics/download.py # noqa: E501 # The code is licensed under the MIT licence. import argparse import os import ssl import subprocess import mmcv from joblib import Parallel, delayed ssl._create_default_https_context = ss...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/gym/download.py
import os import os.path as osp import subprocess import mmcv data_root = '../../../data/gym' anno_root = f'{data_root}/annotations' event_anno_file = f'{anno_root}/event_annotation.json' event_root = f'{data_root}/events' subaction_root = f'{data_root}/subactions' events = os.listdir(event_root) events = set(event...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/gym/trim_subaction.py
import os import os.path as osp import subprocess import mmcv data_root = '../../../data/gym' video_root = f'{data_root}/videos' anno_root = f'{data_root}/annotations' anno_file = f'{anno_root}/annotation.json' event_anno_file = f'{anno_root}/event_annotation.json' event_root = f'{data_root}/events' videos = os.lis...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/gym/trim_event.py
import os import os.path as osp annotation_root = '../../../data/gym/annotations' data_root = '../../../data/gym/subactions' frame_data_root = '../../../data/gym/subaction_frames' videos = os.listdir(data_root) videos = set(videos) train_file_org = osp.join(annotation_root, 'gym99_train_org.txt') val_file_org = osp....
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/gym/generate_file_list.py
import os from tqdm import tqdm def fix_listfile(file_split, phase): assert os.path.exists(file_split), 'File does not exist! %s'%(file_split) filename = file_split.split('/')[-1] file_split_new = os.path.join(dataset_path, 'temp_' + filename) with open(file_split_new, 'w') as fw: with open(fi...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tools/data/mit/fix_video_filelist.py
import matplotlib.pyplot as plt import numpy as np from matplotlib.lines import Line2D def draw_curves(): fig = plt.figure(figsize=(8,5)) plt.rcParams["font.family"] = "Arial" fontsize = 15 markersize = 80 # I3D I3D_DNN_HMDB = [94.69, 75.07] # (closed-set ACC, open-set AUC) I3D_DNN_MiT =...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/draw_performance_gain.py
import numpy as np import argparse import os import matplotlib.pyplot as plt # from mmaction.core.evaluation import confusion_matrix from mpl_toolkits.axes_grid1 import make_axes_locatable import matplotlib.ticker as ticker from matplotlib.colors import LogNorm def confusion_maxtrix(ind_labels, ind_results, ind_uncer...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/draw_confusion_matrix.py
import argparse import os import os.path as osp import torch import mmcv from mmaction.apis import init_recognizer from mmcv.parallel import collate, scatter from operator import itemgetter from mmaction.datasets.pipelines import Compose from mmaction.datasets import build_dataloader, build_dataset from mmcv.parallel i...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/ood_detection.py
import argparse import os import torch import mmcv from mmaction.apis import init_recognizer from mmaction.datasets import build_dataloader, build_dataset from mmaction.core.evaluation import top_k_accuracy from mmcv.parallel import MMDataParallel import numpy as np import torch.multiprocessing torch.multiprocessing.se...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/eval_debias.py
import argparse, os, sys import torch import mmcv import numpy as np import torch.nn.functional as F from mmcv.parallel import collate, scatter from mmaction.datasets.pipelines import Compose from mmaction.apis import init_recognizer from mmaction.datasets import build_dataloader, build_dataset from mmcv.parallel impor...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/baseline_openmax.py
import argparse import os import os.path as osp import torch import mmcv from mmaction.apis import init_recognizer from mmcv.parallel import collate, scatter from operator import itemgetter from mmaction.datasets.pipelines import Compose from mmaction.datasets import build_dataloader, build_dataset from mmcv.parallel i...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/get_threshold_dist.py
import argparse import os import os.path as osp import torch import mmcv from mmaction.apis import init_recognizer from mmcv.parallel import collate, scatter from operator import itemgetter from mmaction.datasets.pipelines import Compose from mmaction.datasets import build_dataloader, build_dataset from mmcv.parallel i...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/get_threshold.py
import argparse, os, sys import torch import mmcv import numpy as np import torch.nn.functional as F from mmcv.parallel import collate, scatter from mmaction.datasets.pipelines import Compose from mmaction.apis import init_recognizer from mmaction.datasets import build_dataloader, build_dataset from mmcv.parallel impor...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/baseline_softmax.py
import argparse import os import os.path as osp import torch import mmcv from mmaction.apis import init_recognizer from mmcv.parallel import collate, scatter from mmaction.datasets.pipelines import Compose from mmaction.datasets import build_dataloader, build_dataset from mmcv.parallel import MMDataParallel import nump...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/baseline_rpl.py
import os import argparse from matplotlib.pyplot import axis import numpy as np from sklearn.metrics import roc_auc_score, accuracy_score, precision_recall_curve, auc, roc_curve from terminaltables import AsciiTable def parse_args(): '''Command instruction: source activate mmaction python experimen...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/compare_openness_new.py
import argparse import os import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker def parse_args(): parser = argparse.ArgumentParser(description='Draw histogram') parser.add_argument('--uncertainty', default='EDL', choices=['BALD', 'Entropy', 'EDL'], help='the uncertainty estimat...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/draw_ood_hist.py
import argparse import os import os.path as osp import torch import mmcv from mmcv import Config, DictAction from mmaction.apis import init_recognizer from mmcv.parallel import collate, scatter from operator import itemgetter from mmaction.datasets.pipelines import Compose from mmaction.datasets import build_dataloader...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/ood_detection_dist.py
import os import numpy as np import matplotlib.pyplot as plt def plot_by_uncertainty(result_file, uncertainty='EDL', auc=80, fontsize=16, result_prefix=''): assert os.path.exists(result_file), 'result file not exists! %s'%(result_file) results = np.load(result_file, allow_pickle=True) # ind_confidences = ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/draw_fig7cd.py
import os import argparse import numpy as np from sklearn.metrics import f1_score, roc_auc_score, accuracy_score import matplotlib.pyplot as plt def parse_args(): '''Command instruction: source activate mmaction python experiments/compare_openness.py --ind_ncls 101 --ood_ncls 51 ''' parser ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/compare_openness.py
import argparse import os import torch from mmaction.apis import init_recognizer from mmcv.parallel import collate, scatter from mmaction.datasets.pipelines import Compose import numpy as np from tqdm import tqdm def parse_args(): parser = argparse.ArgumentParser(description='MMAction2 test') # model config ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/demo.py
import argparse, os import numpy as np import matplotlib.pyplot as plt def eval_calibration(predictions, confidences, labels, M=15): """ M: number of bins for confidence scores """ num_Bm = np.zeros((M,), dtype=np.int32) accs = np.zeros((M,), dtype=np.float32) confs = np.zeros((M,), dtype=np.f...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/evaluate_calibration.py
import argparse import os import torch from mmcv.parallel import collate, scatter from mmaction.datasets.pipelines import Compose from mmaction.apis import init_recognizer from sklearn.manifold import TSNE import numpy as np import matplotlib.pyplot as plt from tqdm import tqdm def parse_args(): parser = argparse...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/analyze_features.py
import os, argparse import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import f1_score def softmax_curvepoints(result_file, thresh, ood_ncls, num_rand): assert os.path.exists(result_file), "File not found! Run baseline_i3d_softmax.py first!" # load the testing results results = np.loa...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/draw_openness_curves.py
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext from Cython.Build import cythonize import sys import numpy #ext_modules = [Extension("libmr", ["libmr.pyx", "MetaRecognition.cpp"])] setup( ext_modules = cythonize(Extension('libmr', ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/libMR/setup.py
import os, sys import scipy as sp import libmr def main(): posscores = sp.asarray([0.245 , 0.2632, 0.3233, 0.3573, 0.4014, 0.4055, 0.4212, 0.5677]) test_distances = sp.asarray([ 0.05, 0.1 , 0.25, 0.4 , 0.75, 1. , 1.5 , 2.]) mr = libmr.MR() # since higher is worse and we want to fit the ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/libMR/estimate_wscores.py
import scipy as sp import sys, os try: import libmr print("Imported libmr succesfully") except ImportError: print("Cannot import libmr") sys.exit() import pickle svm_data = {} svm_data["labels"] = [1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1 , -1, -1, -1, -1, -1, 1, 1, 1, 1,...
InternVideo-main
Downstream/Open-Set-Action-Recognition/experiments/libMR/test_libmr.py
import os.path as osp import random import numpy as np import pytest from numpy.testing import assert_array_almost_equal, assert_array_equal from mmaction.core import (ActivityNetDetection, average_recall_at_avg_proposals, confusion_matrix, get_weighted_score, mea...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_accuracy.py
import os.path as osp import numpy as np import pytest from numpy.testing import assert_array_almost_equal, assert_array_equal from mmaction.localization import (generate_bsp_feature, generate_candidate_proposals, soft_nms, temporal_iop, temporal_i...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_localization_utils.py
import numpy as np import pytest import torch import torch.nn as nn import torch.nn.functional as F from mmcv import ConfigDict from numpy.testing import assert_array_almost_equal from torch.autograd import Variable from mmaction.models import (BCELossWithLogits, BinaryLogisticRegressionLoss, ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_loss.py
import os.path as osp import mmcv import numpy as np import pytest import torch from mmaction.models import build_recognizer from mmaction.utils.gradcam_utils import GradCAM def _get_cfg(fname): """Grab configs necessary to create a recognizer. These are deep copied to allow for safe modification of parame...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_gradcam.py
import copy import numpy as np import pytest import torch import torch.nn as nn from mmcv.utils import _BatchNorm from mmaction.models import (C3D, X3D, ResNet, ResNet2Plus1d, ResNet3d, ResNet3dCSN, ResNet3dSlowFast, ResNet3dSlowOnly, ResNetAudio, ResNetTIN, R...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_backbone.py
import mmcv import pytest import torch import torch.nn as nn from mmaction.apis import inference_recognizer, init_recognizer video_config_file = 'configs/recognition/tsn/tsn_r50_video_inference_1x1x3_100e_kinetics400_rgb.py' # noqa: E501 frame_config_file = 'configs/recognition/tsn/tsn_r50_inference_1x1x3_100e_kinet...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_inference.py
import os.path as osp import mmcv import numpy as np import pytest import torch import torch.nn.functional as F from mmaction.models import BaseRecognizer, build_recognizer class ExampleRecognizer(BaseRecognizer): def __init__(self, train_cfg, test_cfg): super(BaseRecognizer, self).__init__() #...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_recognizers.py
import pytest import torch from mmaction.models import Conv2plus1d, ConvAudio def test_conv2plus1d(): with pytest.raises(AssertionError): # Length of kernel size, stride and padding must be the same Conv2plus1d(3, 8, (2, 2)) conv_2plus1d = Conv2plus1d(3, 8, 2) conv_2plus1d.init_weights()...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_common_modules.py
import torch import torch.nn as nn from mmaction.models import (AudioTSNHead, BaseHead, I3DHead, SlowFastHead, TPNHead, TSMHead, TSNHead, X3DHead) class ExampleHead(BaseHead): # use a ExampleHead to success BaseHead def init_weights(self): pass def forward(self, x): ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_head.py
import copy import mmcv import numpy as np import pytest import torch from mmaction.models import build_localizer from mmaction.models.localizers.utils import post_processing def test_tem(): model_cfg = dict( type='TEM', temporal_dim=100, boundary_ratio=0.1, tem_feat_dim=400, ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_localizers.py
import copy import numpy as np import pytest import torch from mmaction.models import TPN def test_tpn(): """Test TPN backbone.""" tpn_cfg = dict( in_channels=(1024, 2048), out_channels=1024, spatial_modulation_cfg=dict( in_channels=(1024, 2048), out_channels=2048), ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_models/test_neck.py
import numpy as np import pytest from mmaction.datasets.pipelines import Compose, ImageToTensor def check_keys_equal(result_keys, target_keys): """Check if all elements in target_keys is in result_keys.""" return set(target_keys) == set(result_keys) def test_compose(): with pytest.raises(TypeError): ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_data/test_compose.py
import copy import os.path as osp import mmcv import numpy as np import pytest import torch from numpy.testing import assert_array_almost_equal, assert_array_equal # yapf: disable from mmaction.datasets.pipelines import (AudioDecode, AudioDecodeInit, AudioFeatureSelector, Deco...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_data/test_loading.py
import numpy as np import pytest import torch from mmcv.parallel import DataContainer as DC from mmaction.datasets.pipelines import (Collect, FormatAudioShape, FormatShape, ImageToTensor, ToDataContainer, ToTensor, Transpose) def check...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_data/test_formating.py
import os import os.path as osp import tempfile import mmcv import numpy as np import pytest from mmcv import ConfigDict from numpy.testing import assert_array_almost_equal, assert_array_equal from mmaction.datasets import (ActivityNetDataset, AudioDataset, AudioFeatureDataset, AudioVis...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_data/test_dataset.py
import os.path as osp import mmcv import numpy as np from numpy.testing import assert_array_equal from mmaction.datasets import AVADataset def check_keys_contain(result_keys, target_keys): """Check if all elements in target_keys is in result_keys.""" return set(target_keys).issubset(set(result_keys)) clas...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_data/test_ava_dataset.py
import copy import mmcv import numpy as np import pytest from numpy.testing import assert_array_almost_equal, assert_array_equal # yapf: disable from mmaction.datasets.pipelines import (AudioAmplify, CenterCrop, ColorJitter, EntityBoxClip, EntityBoxCrop, ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_data/test_augmentations.py
import os.path as osp import tempfile import unittest.mock as mock from unittest.mock import MagicMock, patch import mmcv import pytest import torch import torch.nn as nn from mmcv.runner import EpochBasedRunner, build_optimizer from mmcv.utils import get_logger from torch.utils.data import DataLoader, Dataset from m...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_runtime/test_eval_hook.py
import torch import torch.nn as nn from mmcv.runner import build_optimizer_constructor class SubModel(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(2, 2, kernel_size=1, groups=2) self.gn = nn.GroupNorm(2, 2) self.fc = nn.Linear(2, 2) self.param1...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_runtime/test_optimizer.py
import tempfile import pytest import torch import torch.nn as nn from mmcv import Config from torch.utils.data import Dataset from mmaction.apis import train_model from mmaction.datasets.registry import DATASETS @DATASETS.register_module() class ExampleDataset(Dataset): def __init__(self, test_mode=False): ...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_runtime/test_train.py
import sys from unittest.mock import MagicMock, Mock, patch import pytest import torch import torch.nn as nn from torch.utils.data import DataLoader, Dataset from mmaction.apis.test import (collect_results_cpu, multi_gpu_test, single_gpu_test) class OldStyleModel(nn.Module): def...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_runtime/test_apis_test.py
import logging import shutil import sys import tempfile from unittest.mock import MagicMock, call import torch import torch.nn as nn from mmcv.runner import IterTimerHook, PaviLoggerHook, build_runner from torch.utils.data import DataLoader def test_tin_lr_updater_hook(): sys.modules['pavi'] = MagicMock() lo...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_runtime/test_lr.py
import os.path as osp import tempfile import torch.nn as nn from tools.pytorch2onnx import _convert_batchnorm, pytorch2onnx class TestModel(nn.Module): def __init__(self): super().__init__() self.conv = nn.Conv3d(1, 2, 1) self.bn = nn.SyncBatchNorm(2) def forward(self, x): r...
InternVideo-main
Downstream/Open-Set-Action-Recognition/tests/test_runtime/test_onnx.py