Spaces:
Sleeping
Sleeping
Upload 29 files
Browse files- .gitattributes +1 -0
- data_processing/.DS_Store +0 -0
- data_processing/__init__.py +2 -0
- data_processing/split_train_test.py +126 -0
- extractor/.DS_Store +0 -0
- extractor/__init__.py +2 -0
- extractor/extract_clip_embeds.py +166 -0
- extractor/extract_frag.py +327 -0
- extractor/extract_slowfast_clip.py +64 -0
- extractor/extract_swint_clip.py +40 -0
- model/.DS_Store +0 -0
- model/finetune/.DS_Store +0 -0
- model/finetune/cvd_2014_camp-vqa_fine_tuned_model.pth +3 -0
- model/finetune/finevd_camp-vqa_fine_tuned_model.pth +3 -0
- model/finetune/konvid_1k_camp-vqa_fine_tuned_model.pth +3 -0
- model/finetune/kvq_camp-vqa_fine_tuned_model.pth +3 -0
- model/finetune/live_vqc_camp-vqa_fine_tuned_model.pth +3 -0
- model/finetune/live_yt_gaming_camp-vqa_fine_tuned_model.pth +3 -0
- model/finetune/youtube_ugc_h264_camp-vqa_fine_tuned_model.pth +3 -0
- model/wo_finetune/.DS_Store +0 -0
- model/wo_finetune/cvd_2014_camp-vqa_Mlp_byrmse_trained_model.pth +3 -0
- model/wo_finetune/finevd_camp-vqa_Mlp_byrmse_trained_model.pth +3 -0
- model/wo_finetune/konvid_1k_camp-vqa_Mlp_byrmse_trained_model.pth +3 -0
- model/wo_finetune/kvq_camp-vqa_Mlp_byrmse_trained_model.pth +3 -0
- model/wo_finetune/live_vqc_camp-vqa_Mlp_byrmse_trained_mode.pth +3 -0
- model/wo_finetune/live_yt_gaming_camp-vqa_Mlp_byrmse_trained_model.pth +3 -0
- model/wo_finetune/lsvq_train_camp-vqa_Mlp_byrmse_trained_model_1080p.pth +3 -0
- model/wo_finetune/lsvq_train_camp-vqa_Mlp_byrmse_trained_model_kfold.pth +3 -0
- model/wo_finetune/youtube_ugc_h264_camp-vqa_Mlp_byrmse_trained_model.pth +3 -0
- ugc_original_videos/0_16_07_500001604801190-yase.mp4 +3 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
ugc_original_videos/0_16_07_500001604801190-yase.mp4 filter=lfs diff=lfs merge=lfs -text
|
data_processing/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
data_processing/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# __init__.py
|
| 2 |
+
# print("Data processing")
|
data_processing/split_train_test.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
import torch
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
#NR: original
|
| 9 |
+
def process_lsvq(train_data_name, test_data_name, metadata_path, feature_path, network_name):
|
| 10 |
+
train_df = pd.read_csv(f'{metadata_path}/{train_data_name.upper()}_metadata.csv')
|
| 11 |
+
test_df = pd.read_csv(f'{metadata_path}/{test_data_name.upper()}_metadata.csv')
|
| 12 |
+
|
| 13 |
+
# grayscale videos, do not consider them for fair comparison
|
| 14 |
+
# grey_df_train = pd.read_csv(f'{metadata_path}/greyscale_report/{train_data_name.upper()}_greyscale_metadata.csv')
|
| 15 |
+
# grey_df_test = pd.read_csv(f'{metadata_path}/greyscale_report/{test_data_name.upper()}_greyscale_metadata.csv')
|
| 16 |
+
# grey_indices_train = grey_df_train.iloc[:, 0].tolist()
|
| 17 |
+
# grey_indices_test = grey_df_test.iloc[:, 0].tolist()
|
| 18 |
+
# train_df = train_df.drop(index=grey_indices_train).reset_index(drop=True)
|
| 19 |
+
# test_df = test_df.drop(index=grey_indices_test).reset_index(drop=True)
|
| 20 |
+
test_vids = test_df['vid']
|
| 21 |
+
|
| 22 |
+
# mos scores
|
| 23 |
+
train_scores = train_df['mos'].tolist()
|
| 24 |
+
test_scores = test_df['mos'].tolist()
|
| 25 |
+
train_mos_list = train_scores
|
| 26 |
+
test_mos_list = test_scores
|
| 27 |
+
|
| 28 |
+
# reorder columns
|
| 29 |
+
sorted_train_df = pd.DataFrame({'vid': train_df['vid'], 'framerate': train_df['framerate'], 'MOS': train_mos_list, 'MOS_raw': train_df['mos']})
|
| 30 |
+
sorted_test_df = pd.DataFrame({'vid': test_df['vid'], 'framerate': test_df['framerate'], 'MOS': test_mos_list, 'MOS_raw': test_df['mos']})
|
| 31 |
+
|
| 32 |
+
# use indices from the train and test DataFrames to split features
|
| 33 |
+
train_features = torch.load(f'{feature_path}/{network_name}_{train_data_name}_features.pt')
|
| 34 |
+
print(f"loaded {train_data_name}: dimensions are {train_features.shape}")
|
| 35 |
+
test_features = torch.load(f'{feature_path}/{network_name}_{test_data_name}_features.pt')
|
| 36 |
+
|
| 37 |
+
# grayscale videos
|
| 38 |
+
# train_mask = torch.ones(train_features.size(0), dtype=torch.bool, device=train_features.device)
|
| 39 |
+
# test_mask = torch.ones(test_features.size(0), dtype=torch.bool, device=test_features.device)
|
| 40 |
+
# train_mask[grey_indices_train] = False
|
| 41 |
+
# test_mask[grey_indices_test] = False
|
| 42 |
+
# train_features = train_features[train_mask]
|
| 43 |
+
# test_features = test_features[test_mask]
|
| 44 |
+
print(len(train_features))
|
| 45 |
+
print(len(test_features))
|
| 46 |
+
|
| 47 |
+
# save the files
|
| 48 |
+
sorted_train_df.to_csv(f'{metadata_path}mos_files/{train_data_name}_MOS_train.csv', index=False)
|
| 49 |
+
sorted_test_df.to_csv(f'{metadata_path}mos_files/{train_data_name}_MOS_test.csv', index=False)
|
| 50 |
+
os.makedirs(os.path.join(feature_path, "split_train_test"), exist_ok=True)
|
| 51 |
+
torch.save(train_features, f'{feature_path}/split_train_test/{network_name}_{train_data_name}_train_features.pt')
|
| 52 |
+
torch.save(test_features, f'{feature_path}/split_train_test/{network_name}_{test_data_name}_test_features.pt')
|
| 53 |
+
|
| 54 |
+
return train_features, test_features, test_vids
|
| 55 |
+
|
| 56 |
+
def process_other(data_name, test_size, random_state, metadata_path, feature_path, network_name):
|
| 57 |
+
metadata_name = f'{data_name.upper()}_metadata.csv'
|
| 58 |
+
# for test finevd mos dimensions
|
| 59 |
+
# if data_name == 'finevd':
|
| 60 |
+
# metadata_name = f'{data_name.upper()}_MOS_temporal_metadata.csv'
|
| 61 |
+
# print(metadata_name)
|
| 62 |
+
|
| 63 |
+
# load CSV data
|
| 64 |
+
df = pd.read_csv(f'{metadata_path}/{metadata_name}')
|
| 65 |
+
# if data_name == 'youtube_ugc':
|
| 66 |
+
# # grayscale videos, do not consider them for fair comparison
|
| 67 |
+
# grey_df = pd.read_csv(f'{metadata_path}/greyscale_report/{data_name.upper()}_greyscale_metadata.csv')
|
| 68 |
+
# grey_indices = grey_df.iloc[:, 0].tolist()
|
| 69 |
+
# df = df.drop(index=grey_indices).reset_index(drop=True)
|
| 70 |
+
|
| 71 |
+
# get unique vids
|
| 72 |
+
unique_vids = df['vid'].unique()
|
| 73 |
+
|
| 74 |
+
# split videonames into train and test sets
|
| 75 |
+
train_vids, test_vids = train_test_split(unique_vids, test_size=test_size, random_state=random_state)
|
| 76 |
+
|
| 77 |
+
# split all_dfs into train and test based on vids
|
| 78 |
+
train_df = df[df['vid'].isin(train_vids)]
|
| 79 |
+
test_df = df[df['vid'].isin(test_vids)]
|
| 80 |
+
|
| 81 |
+
# mos scores
|
| 82 |
+
train_scores = train_df['mos'].tolist()
|
| 83 |
+
test_scores = test_df['mos'].tolist()
|
| 84 |
+
train_mos_list = train_scores
|
| 85 |
+
test_mos_list = test_scores
|
| 86 |
+
|
| 87 |
+
# reorder columns
|
| 88 |
+
sorted_train_df = pd.DataFrame({'vid': train_df['vid'], 'framerate': train_df['framerate'], 'MOS': train_mos_list, 'MOS_raw': train_df['mos']})
|
| 89 |
+
sorted_test_df = pd.DataFrame({'vid': test_df['vid'], 'framerate': test_df['framerate'], 'MOS': test_mos_list, 'MOS_raw': test_df['mos']})
|
| 90 |
+
|
| 91 |
+
# use indices from the train and test DataFrames to split features
|
| 92 |
+
features = torch.load(f'{feature_path}/{network_name}_{data_name}_features.pt')
|
| 93 |
+
# if data_name == 'youtube_ugc':
|
| 94 |
+
# # features = np.delete(features, grey_indices, axis=0)
|
| 95 |
+
# mask = torch.ones(features.size(0), dtype=torch.bool, device=features.device)
|
| 96 |
+
# mask[grey_indices] = False
|
| 97 |
+
# features = features[mask]
|
| 98 |
+
train_features = features[train_df.index]
|
| 99 |
+
test_features = features[test_df.index]
|
| 100 |
+
|
| 101 |
+
# save the files
|
| 102 |
+
sorted_train_df.to_csv(f'{metadata_path}mos_files/{data_name}_MOS_train.csv', index=False)
|
| 103 |
+
sorted_test_df.to_csv(f'{metadata_path}mos_files/{data_name}_MOS_test.csv', index=False)
|
| 104 |
+
os.makedirs(os.path.join(feature_path, "split_train_test"), exist_ok=True)
|
| 105 |
+
torch.save(train_features, f'{feature_path}/split_train_test/{network_name}_{data_name}_train_features.pt')
|
| 106 |
+
torch.save(test_features, f'{feature_path}/split_train_test/{network_name}_{data_name}_test_features.pt')
|
| 107 |
+
|
| 108 |
+
return train_features, test_features, test_vids
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == '__main__':
|
| 112 |
+
network_name = "slowfast"
|
| 113 |
+
data_name = "test"
|
| 114 |
+
metadata_path = '../../metadata/'
|
| 115 |
+
feature_path = '../../features/konvid_1k_test/slowfast/'
|
| 116 |
+
|
| 117 |
+
# train test split
|
| 118 |
+
test_size = 0.2
|
| 119 |
+
random_state = None
|
| 120 |
+
|
| 121 |
+
if data_name == 'lsvq_train':
|
| 122 |
+
test_data_name = 'lsvq_test'
|
| 123 |
+
process_lsvq(data_name, test_data_name, metadata_path, feature_path, network_name)
|
| 124 |
+
|
| 125 |
+
else:
|
| 126 |
+
process_other(data_name, test_size, random_state, metadata_path, feature_path, network_name)
|
extractor/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
extractor/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# __init__.py
|
| 2 |
+
# print("Initializing extractor")
|
extractor/extract_clip_embeds.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import re
|
| 2 |
+
import torch
|
| 3 |
+
import clip
|
| 4 |
+
import numpy as np
|
| 5 |
+
from numpy.linalg import norm
|
| 6 |
+
from PIL import Image
|
| 7 |
+
|
| 8 |
+
def get_quality_hint_from_metadata(mos, width, height, bitrate, bitdepth, framerate, quality_hints):
|
| 9 |
+
hint = []
|
| 10 |
+
if mos > 5:
|
| 11 |
+
mos = (mos / 100) * 5
|
| 12 |
+
if mos >= 4.5:
|
| 13 |
+
hint.append(quality_hints["mos"]["excellent"])
|
| 14 |
+
elif 3.5 <= mos < 4.5:
|
| 15 |
+
hint.append(quality_hints["mos"]["good"])
|
| 16 |
+
elif 2.5 <= mos < 3.5:
|
| 17 |
+
hint.append(quality_hints["mos"]["fair"])
|
| 18 |
+
elif 1.5 <= mos < 2.5:
|
| 19 |
+
hint.append(quality_hints["mos"]["bad"])
|
| 20 |
+
else:
|
| 21 |
+
hint.append(quality_hints["mos"]["poor"])
|
| 22 |
+
|
| 23 |
+
res = width * height
|
| 24 |
+
if res < 640 * 480:
|
| 25 |
+
hint.append(quality_hints["resolution"]["low"])
|
| 26 |
+
elif res < 1280 * 720:
|
| 27 |
+
hint.append(quality_hints["resolution"]["sd"])
|
| 28 |
+
else:
|
| 29 |
+
hint.append(quality_hints["resolution"]["hd"])
|
| 30 |
+
if bitrate < 500_000:
|
| 31 |
+
hint.append(quality_hints["bitrate"]["low"])
|
| 32 |
+
elif bitrate < 1_000_000:
|
| 33 |
+
hint.append(quality_hints["bitrate"]["medium"])
|
| 34 |
+
else:
|
| 35 |
+
hint.append(quality_hints["bitrate"]["high"])
|
| 36 |
+
|
| 37 |
+
if 0 < bitdepth <= 8:
|
| 38 |
+
hint.append(quality_hints["bitdepth"]["low"])
|
| 39 |
+
elif bitdepth == 0:
|
| 40 |
+
hint.append(quality_hints["bitdepth"]["standard"])
|
| 41 |
+
else:
|
| 42 |
+
hint.append(quality_hints["bitdepth"]["high"])
|
| 43 |
+
if framerate < 24:
|
| 44 |
+
hint.append(quality_hints["framerate"]["low"])
|
| 45 |
+
elif framerate > 60:
|
| 46 |
+
hint.append(quality_hints["framerate"]["high"])
|
| 47 |
+
else:
|
| 48 |
+
hint.append(quality_hints["framerate"]["standard"])
|
| 49 |
+
return " ".join(hint)
|
| 50 |
+
|
| 51 |
+
def generate_caption(blip_processor, blip_model, device, image, prompt):
|
| 52 |
+
inputs = blip_processor(image, prompt, return_tensors="pt").to(device)
|
| 53 |
+
generated_ids = blip_model.generate(**inputs, max_new_tokens=50)
|
| 54 |
+
caption = blip_processor.decode(generated_ids[0], skip_special_tokens=True)
|
| 55 |
+
return caption
|
| 56 |
+
|
| 57 |
+
def tensor_to_pil(image_tensor):
|
| 58 |
+
if isinstance(image_tensor, torch.Tensor):
|
| 59 |
+
arr = image_tensor.cpu().numpy()
|
| 60 |
+
if arr.ndim == 4 and arr.shape[0] == 1:
|
| 61 |
+
arr = arr[0] # remove batch dimension
|
| 62 |
+
arr = arr.astype('uint8')
|
| 63 |
+
return Image.fromarray(arr)
|
| 64 |
+
|
| 65 |
+
def extract_semantic_captions(blip_processor, blip_model, curr_frame, frag_residual, frag_frame, prompts, device, metadata=None, use_metadata_prompt=False):
|
| 66 |
+
quality_prompt_base = prompts["quality_prompt_base"]
|
| 67 |
+
residual_prompt = prompts["residual_prompt"]
|
| 68 |
+
frag_prompt = prompts["frag_prompt"]
|
| 69 |
+
|
| 70 |
+
quality_hint = ""
|
| 71 |
+
if use_metadata_prompt and metadata:
|
| 72 |
+
mos, width, height, bitrate, bitdepth, framerate = metadata
|
| 73 |
+
quality_hint = get_quality_hint_from_metadata(mos, width, height, bitrate, bitdepth, framerate, quality_hints=prompts["quality_hints"])
|
| 74 |
+
|
| 75 |
+
prompt_hints = []
|
| 76 |
+
if quality_hint:
|
| 77 |
+
prompt_hints.append(quality_hint)
|
| 78 |
+
|
| 79 |
+
quality_prompt = "\n\n".join(prompt_hints + [quality_prompt_base])
|
| 80 |
+
fragment_prompt = "\n\n".join(prompt_hints)
|
| 81 |
+
# print('content_prompt:', content_prompt)
|
| 82 |
+
# print('quality_prompt:', quality_prompt)
|
| 83 |
+
# print('residual_prompt:', fragment_prompt + "\n\n" + residual_prompt)
|
| 84 |
+
# print('frame_fragment_prompt:', fragment_prompt + "\n\n" + frag_prompt)
|
| 85 |
+
|
| 86 |
+
captions = {
|
| 87 |
+
"curr_frame_quality": generate_caption(blip_processor, blip_model, device, curr_frame, prompt=quality_prompt),
|
| 88 |
+
"frag_residual": generate_caption(blip_processor, blip_model, device, frag_residual, prompt=(fragment_prompt + "\n\n" + residual_prompt)),
|
| 89 |
+
"frag_frame": generate_caption(blip_processor, blip_model, device, frag_frame, prompt=(fragment_prompt + "\n\n" + frag_prompt))
|
| 90 |
+
}
|
| 91 |
+
return captions
|
| 92 |
+
|
| 93 |
+
def clean_caption_text(text):
|
| 94 |
+
text = re.sub(r"- .*?stock videos & royalty-free footage", "", text)
|
| 95 |
+
text = re.sub(r"\s+", " ", text)
|
| 96 |
+
return text.strip()
|
| 97 |
+
|
| 98 |
+
def dedup_keywords(text, split_tokens=[",", ".", ";"]):
|
| 99 |
+
for token in split_tokens:
|
| 100 |
+
text = text.replace(token, ",")
|
| 101 |
+
parts = [p.strip().lower() for p in text.split(",") if p.strip()]
|
| 102 |
+
seen = set()
|
| 103 |
+
unique_parts = []
|
| 104 |
+
for part in parts:
|
| 105 |
+
if part not in seen:
|
| 106 |
+
unique_parts.append(part)
|
| 107 |
+
seen.add(part)
|
| 108 |
+
return " ".join(unique_parts) # good for embedding
|
| 109 |
+
|
| 110 |
+
def get_clip_text_embedding(clip_model, device, text):
|
| 111 |
+
text_tokens = clip.tokenize([text]).to(device)
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
with torch.amp.autocast(device_type='cuda'):
|
| 114 |
+
text_features = clip_model.encode_text(text_tokens)
|
| 115 |
+
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
|
| 116 |
+
return text_features.squeeze()
|
| 117 |
+
|
| 118 |
+
def get_clip_image_embedding(clip_model, clip_preprocess, device, image):
|
| 119 |
+
image_input = clip_preprocess(image).unsqueeze(0).to(device)
|
| 120 |
+
with torch.no_grad():
|
| 121 |
+
with torch.amp.autocast(device_type='cuda'):
|
| 122 |
+
image_features = clip_model.encode_image(image_input)
|
| 123 |
+
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
|
| 124 |
+
return image_features.squeeze()
|
| 125 |
+
|
| 126 |
+
def extract_semantic_embeddings(clip_model, clip_preprocess, device, curr_frame, captions):
|
| 127 |
+
if not isinstance(curr_frame, Image.Image):
|
| 128 |
+
curr_frame = Image.fromarray(curr_frame)
|
| 129 |
+
|
| 130 |
+
quality_caption = dedup_keywords(clean_caption_text(captions["curr_frame_quality"]))
|
| 131 |
+
artifact_caption_1 = dedup_keywords(clean_caption_text(captions["frag_residual"]))
|
| 132 |
+
artifact_caption_2 = dedup_keywords(clean_caption_text(captions["frag_frame"]))
|
| 133 |
+
artifact_caption = dedup_keywords(f"{artifact_caption_1}, {artifact_caption_2}")
|
| 134 |
+
|
| 135 |
+
image_embed = get_clip_image_embedding(clip_model, clip_preprocess, device, curr_frame)
|
| 136 |
+
quality_embed = get_clip_text_embedding(clip_model, device, quality_caption)
|
| 137 |
+
artifact_embed = get_clip_text_embedding(clip_model, device, artifact_caption)
|
| 138 |
+
return image_embed, quality_embed, artifact_embed
|
| 139 |
+
|
| 140 |
+
def extract_features_clip_embed(frames_info, metadata, clip_model, clip_preprocess, blip_processor, blip_model, prompts, device):
|
| 141 |
+
feature_image_embed = []
|
| 142 |
+
feature_quality_embed = []
|
| 143 |
+
feature_artifact_embed = []
|
| 144 |
+
for i, (curr_frame, frag_residual, frag_frame) in enumerate(frames_info):
|
| 145 |
+
curr_frame = tensor_to_pil(curr_frame)
|
| 146 |
+
frag_residual = tensor_to_pil(frag_residual)
|
| 147 |
+
frag_frame = tensor_to_pil(frag_frame)
|
| 148 |
+
|
| 149 |
+
captions = extract_semantic_captions(
|
| 150 |
+
blip_processor, blip_model,
|
| 151 |
+
curr_frame, frag_residual, frag_frame, prompts,
|
| 152 |
+
device,
|
| 153 |
+
metadata=metadata,
|
| 154 |
+
use_metadata_prompt=True,
|
| 155 |
+
)
|
| 156 |
+
image_embed, quality_embed, artifact_embed = extract_semantic_embeddings(clip_model, clip_preprocess, device, curr_frame, captions)
|
| 157 |
+
feature_image_embed.append(image_embed)
|
| 158 |
+
feature_quality_embed.append(quality_embed)
|
| 159 |
+
feature_artifact_embed.append(artifact_embed)
|
| 160 |
+
|
| 161 |
+
# concatenate features
|
| 162 |
+
image_embedding = torch.stack(feature_image_embed, dim=0)
|
| 163 |
+
quality_embedding = torch.stack(feature_quality_embed, dim=0)
|
| 164 |
+
artifact_embedding = torch.stack(feature_artifact_embed, dim=0)
|
| 165 |
+
# print("image_embedding.shape:", image_embedding.shape, "quality_embedding.shape:", quality_embedding.shape, "artifact_embedding.shape:", artifact_embedding.shape)
|
| 166 |
+
return image_embedding, quality_embedding, artifact_embedding
|
extractor/extract_frag.py
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import cv2
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import time
|
| 5 |
+
import torch
|
| 6 |
+
import matplotlib.pyplot as plt
|
| 7 |
+
import numpy as np
|
| 8 |
+
from torchvision import transforms
|
| 9 |
+
from torch.utils.data import DataLoader
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from torch.utils import data
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class VideoDataset_feature(data.Dataset):
|
| 15 |
+
def __init__(self, filename_path, data_dir, database, transform, resize, patch_size=16, target_size=224, top_n=196):
|
| 16 |
+
super(VideoDataset_feature, self).__init__()
|
| 17 |
+
if isinstance(filename_path, str):
|
| 18 |
+
self.dataInfo = pd.read_csv(filename_path)
|
| 19 |
+
elif isinstance(filename_path, pd.DataFrame):
|
| 20 |
+
self.dataInfo = filename_path
|
| 21 |
+
else:
|
| 22 |
+
raise ValueError("filename_path: CSV file or DataFrame")
|
| 23 |
+
self.video_names = self.dataInfo['vid'].tolist()
|
| 24 |
+
self.videos_dir = data_dir
|
| 25 |
+
self.database = database
|
| 26 |
+
self.transform = transform
|
| 27 |
+
self.resize = resize
|
| 28 |
+
self.patch_size = patch_size
|
| 29 |
+
self.target_size = target_size
|
| 30 |
+
self.top_n = top_n
|
| 31 |
+
self.length = len(self.video_names)
|
| 32 |
+
|
| 33 |
+
def __len__(self):
|
| 34 |
+
return self.length
|
| 35 |
+
|
| 36 |
+
def __getitem__(self, idx):
|
| 37 |
+
if self.database in ['konvid_1k', 'test']:
|
| 38 |
+
video_clip_min = 8
|
| 39 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 40 |
+
elif self.database == 'live_vqc':
|
| 41 |
+
video_clip_min = 10
|
| 42 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 43 |
+
elif self.database == 'cvd_2014':
|
| 44 |
+
video_clip_min = 12
|
| 45 |
+
video_name = str(self.video_names[idx]) + '.avi'
|
| 46 |
+
elif self.database == 'youtube_ugc':
|
| 47 |
+
video_clip_min = 20
|
| 48 |
+
video_name = str(self.video_names[idx]) + '.mkv'
|
| 49 |
+
elif self.database == 'youtube_ugc_h264':
|
| 50 |
+
video_clip_min = 20
|
| 51 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 52 |
+
elif self.database == 'live_yt_gaming':
|
| 53 |
+
video_clip_min = 7
|
| 54 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 55 |
+
elif self.database == 'kvq':
|
| 56 |
+
video_clip_min = 8
|
| 57 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 58 |
+
elif self.database in ['finevd', 'finevd_test']:
|
| 59 |
+
video_clip_min = 8
|
| 60 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 61 |
+
elif self.database in ['lsvq_test_1080p', 'lsvq_test', 'lsvq_train']:
|
| 62 |
+
video_clip_min = 8
|
| 63 |
+
video_name = str(self.video_names[idx]) + '.mp4'
|
| 64 |
+
|
| 65 |
+
# get metadata
|
| 66 |
+
row = self.dataInfo.iloc[idx]
|
| 67 |
+
if 'prediction_mode' in row and pd.notnull(row['prediction_mode']):
|
| 68 |
+
mos = float(row['prediction_mode'])
|
| 69 |
+
else:
|
| 70 |
+
mos = float(row['mos'])
|
| 71 |
+
metadata = (
|
| 72 |
+
mos,
|
| 73 |
+
int(row["width"]),
|
| 74 |
+
int(row["height"]),
|
| 75 |
+
int(row["bitrate"]),
|
| 76 |
+
int(row["bitdepth"]),
|
| 77 |
+
float(row["framerate"])
|
| 78 |
+
)
|
| 79 |
+
filename = os.path.join(self.videos_dir, video_name)
|
| 80 |
+
|
| 81 |
+
video_capture = cv2.VideoCapture(filename)
|
| 82 |
+
video_capture.set(cv2.CAP_PROP_BUFFERSIZE, 3)
|
| 83 |
+
if not video_capture.isOpened():
|
| 84 |
+
raise RuntimeError(f"Failed to open video: {filename}")
|
| 85 |
+
|
| 86 |
+
video_length = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT))
|
| 87 |
+
video_frame_rate = int(round(video_capture.get(cv2.CAP_PROP_FPS)))
|
| 88 |
+
fps = video_capture.get(cv2.CAP_PROP_FPS)
|
| 89 |
+
if fps is None or fps <= 1:
|
| 90 |
+
print(f"Invalid FPS={fps} for video {filename}. Using default")
|
| 91 |
+
fps = 2.0
|
| 92 |
+
frame_step = int(fps // 2)
|
| 93 |
+
video_clip = int(video_length / video_frame_rate) if video_frame_rate != 0 else 10
|
| 94 |
+
video_channel = 3
|
| 95 |
+
video_length_clip = 32
|
| 96 |
+
|
| 97 |
+
all_frame_tensor = torch.zeros((video_length, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 98 |
+
all_residual_frag_tensor = torch.zeros((video_length - 1, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 99 |
+
all_frame_frag_tensor = torch.zeros((video_length - 1, video_channel, self.resize, self.resize), dtype=torch.float32)
|
| 100 |
+
|
| 101 |
+
video_read_index = 0
|
| 102 |
+
frames_info = []
|
| 103 |
+
prev_frame = None
|
| 104 |
+
for i in range(video_length):
|
| 105 |
+
has_frames, frame = video_capture.read()
|
| 106 |
+
if has_frames:
|
| 107 |
+
curr_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 108 |
+
# frame features
|
| 109 |
+
curr_frame_tensor = self.transform(Image.fromarray(curr_frame))
|
| 110 |
+
all_frame_tensor[video_read_index] = curr_frame_tensor
|
| 111 |
+
|
| 112 |
+
# frame frag features
|
| 113 |
+
if prev_frame is not None:
|
| 114 |
+
residual = cv2.absdiff(curr_frame, prev_frame)
|
| 115 |
+
diff = self.get_patch_diff(residual)
|
| 116 |
+
# frame residual fragment
|
| 117 |
+
imp_patches, positions = self.extract_important_patches(residual, diff)
|
| 118 |
+
imp_patches_pil = Image.fromarray(imp_patches.astype('uint8'))
|
| 119 |
+
residual_frag_tensor = self.transform(imp_patches_pil)
|
| 120 |
+
all_residual_frag_tensor[video_read_index] = residual_frag_tensor
|
| 121 |
+
|
| 122 |
+
# current frame fragment
|
| 123 |
+
ori_patches = self.get_original_frame_patches(curr_frame, positions)
|
| 124 |
+
ori_patches_pil = Image.fromarray(ori_patches.astype('uint8'))
|
| 125 |
+
frame_frag_tensor = self.transform(ori_patches_pil)
|
| 126 |
+
all_frame_frag_tensor[video_read_index] = frame_frag_tensor
|
| 127 |
+
|
| 128 |
+
# as a tuple
|
| 129 |
+
if i % frame_step == 0:
|
| 130 |
+
frames_info.append((curr_frame, imp_patches, ori_patches))
|
| 131 |
+
video_read_index += 1
|
| 132 |
+
prev_frame = curr_frame
|
| 133 |
+
video_capture.release()
|
| 134 |
+
|
| 135 |
+
# Unfilled frames
|
| 136 |
+
self.fill_tensor(all_frame_tensor, video_read_index, video_length)
|
| 137 |
+
self.fill_tensor(all_residual_frag_tensor, video_read_index, video_length - 1)
|
| 138 |
+
self.fill_tensor(all_frame_frag_tensor, video_read_index, video_length - 1)
|
| 139 |
+
|
| 140 |
+
video_all = []
|
| 141 |
+
video_res_frag_all = []
|
| 142 |
+
video_frag_all = []
|
| 143 |
+
for i in range(video_clip):
|
| 144 |
+
clip_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 145 |
+
clip_res_frag_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 146 |
+
clip_frag_tensor = torch.zeros([video_length_clip, video_channel, self.resize, self.resize])
|
| 147 |
+
|
| 148 |
+
start_idx = i * video_frame_rate
|
| 149 |
+
end_idx = start_idx + video_length_clip
|
| 150 |
+
# frame features
|
| 151 |
+
if end_idx <= video_length:
|
| 152 |
+
clip_tensor = all_frame_tensor[start_idx:end_idx]
|
| 153 |
+
else:
|
| 154 |
+
clip_tensor[:(video_length - start_idx)] = all_frame_tensor[start_idx:]
|
| 155 |
+
clip_tensor[(video_length - start_idx):video_length_clip] = clip_tensor[video_length - start_idx - 1]
|
| 156 |
+
|
| 157 |
+
# frame frag features
|
| 158 |
+
if end_idx <= (video_length - 1):
|
| 159 |
+
clip_res_frag_tensor = all_residual_frag_tensor[start_idx:end_idx]
|
| 160 |
+
clip_frag_tensor = all_frame_frag_tensor[start_idx:end_idx]
|
| 161 |
+
else:
|
| 162 |
+
clip_res_frag_tensor[:(video_length - 1 - start_idx)] = all_residual_frag_tensor[start_idx:]
|
| 163 |
+
clip_frag_tensor[:(video_length - 1 - start_idx)] = all_frame_frag_tensor[start_idx:]
|
| 164 |
+
clip_res_frag_tensor[(video_length - 1 - start_idx):video_length_clip] = clip_res_frag_tensor[video_length - 1 - start_idx - 1]
|
| 165 |
+
clip_frag_tensor[(video_length - 1 - start_idx):video_length_clip] = clip_frag_tensor[video_length - 1 - start_idx - 1]
|
| 166 |
+
|
| 167 |
+
video_all.append(clip_tensor)
|
| 168 |
+
video_res_frag_all.append(clip_res_frag_tensor)
|
| 169 |
+
video_frag_all.append(clip_frag_tensor)
|
| 170 |
+
|
| 171 |
+
# Underfilling of clips
|
| 172 |
+
if video_clip < video_clip_min:
|
| 173 |
+
for i in range(video_clip, video_clip_min):
|
| 174 |
+
video_all.append(video_all[video_clip - 1])
|
| 175 |
+
video_res_frag_all.append(video_res_frag_all[video_clip - 1])
|
| 176 |
+
video_frag_all.append(video_frag_all[video_clip - 1])
|
| 177 |
+
return video_all, video_res_frag_all, video_frag_all, video_name, frames_info, metadata
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
# duplicat the final frames
|
| 181 |
+
def fill_tensor(tensor, read_index, length):
|
| 182 |
+
if read_index < length:
|
| 183 |
+
tensor[read_index:length] = tensor[read_index - 1]
|
| 184 |
+
|
| 185 |
+
def get_patch_diff(self, residual_frame):
|
| 186 |
+
h, w = residual_frame.shape[:2]
|
| 187 |
+
patch_size = self.patch_size
|
| 188 |
+
h_adj = (h // patch_size) * patch_size
|
| 189 |
+
w_adj = (w // patch_size) * patch_size
|
| 190 |
+
residual_frame_adj = residual_frame[:h_adj, :w_adj]
|
| 191 |
+
# calculate absolute patch difference
|
| 192 |
+
diff = np.zeros((h_adj // patch_size, w_adj // patch_size))
|
| 193 |
+
for i in range(0, h_adj, patch_size):
|
| 194 |
+
for j in range(0, w_adj, patch_size):
|
| 195 |
+
patch = residual_frame_adj[i:i+patch_size, j:j+patch_size]
|
| 196 |
+
# absolute sum
|
| 197 |
+
diff[i // patch_size, j // patch_size] = np.sum(np.abs(patch))
|
| 198 |
+
return diff
|
| 199 |
+
|
| 200 |
+
def extract_important_patches(self, residual_frame, diff):
|
| 201 |
+
patch_size = self.patch_size
|
| 202 |
+
target_size = self.target_size
|
| 203 |
+
top_n = self.top_n
|
| 204 |
+
|
| 205 |
+
# find top n patches indices
|
| 206 |
+
patch_idx = np.unravel_index(np.argsort(-diff.ravel()), diff.shape)
|
| 207 |
+
top_patches = list(zip(patch_idx[0][:top_n], patch_idx[1][:top_n]))
|
| 208 |
+
sorted_idx = sorted(top_patches, key=lambda x: (x[0], x[1]))
|
| 209 |
+
|
| 210 |
+
imp_patches_img = np.zeros((target_size, target_size, residual_frame.shape[2]), dtype=residual_frame.dtype)
|
| 211 |
+
patches_per_row = target_size // patch_size # 14
|
| 212 |
+
# order the patch in the original location relation
|
| 213 |
+
positions = []
|
| 214 |
+
for idx, (y, x) in enumerate(sorted_idx):
|
| 215 |
+
patch = residual_frame[y * patch_size:(y + 1) * patch_size, x * patch_size:(x + 1) * patch_size]
|
| 216 |
+
# new patch location
|
| 217 |
+
row_idx = idx // patches_per_row
|
| 218 |
+
col_idx = idx % patches_per_row
|
| 219 |
+
start_y = row_idx * patch_size
|
| 220 |
+
start_x = col_idx * patch_size
|
| 221 |
+
imp_patches_img[start_y:start_y + patch_size, start_x:start_x + patch_size] = patch
|
| 222 |
+
positions.append((y, x))
|
| 223 |
+
return imp_patches_img, positions
|
| 224 |
+
|
| 225 |
+
def get_original_frame_patches(self, original_frame, positions):
|
| 226 |
+
patch_size = self.patch_size
|
| 227 |
+
target_size = self.target_size
|
| 228 |
+
imp_original_patches_img = np.zeros((target_size, target_size, original_frame.shape[2]), dtype=original_frame.dtype)
|
| 229 |
+
patches_per_row = target_size // patch_size
|
| 230 |
+
|
| 231 |
+
for idx, (y, x) in enumerate(positions):
|
| 232 |
+
start_y = y * patch_size
|
| 233 |
+
start_x = x * patch_size
|
| 234 |
+
end_y = start_y + patch_size
|
| 235 |
+
end_x = start_x + patch_size
|
| 236 |
+
|
| 237 |
+
patch = original_frame[start_y:end_y, start_x:end_x]
|
| 238 |
+
row_idx = idx // patches_per_row
|
| 239 |
+
col_idx = idx % patches_per_row
|
| 240 |
+
target_start_y = row_idx * patch_size
|
| 241 |
+
target_start_x = col_idx * patch_size
|
| 242 |
+
|
| 243 |
+
imp_original_patches_img[target_start_y:target_start_y + patch_size,
|
| 244 |
+
target_start_x:target_start_x + patch_size] = patch
|
| 245 |
+
return imp_original_patches_img
|
| 246 |
+
|
| 247 |
+
def visualise_tensor(tensors, num_frames_to_visualise=5, img_title='Frag'):
|
| 248 |
+
np_feat = tensors.numpy()
|
| 249 |
+
fig, axes = plt.subplots(1, num_frames_to_visualise, figsize=(15, 5))
|
| 250 |
+
for i in range(num_frames_to_visualise):
|
| 251 |
+
# move channels to last dimension for visualisation: (height, width, channels)
|
| 252 |
+
frame = np_feat[i].transpose(1, 2, 0)
|
| 253 |
+
# normalize to [0, 1] for visualisation
|
| 254 |
+
frame = (frame - frame.min()) / (frame.max() - frame.min())
|
| 255 |
+
axes[i].imshow(frame)
|
| 256 |
+
axes[i].axis('off')
|
| 257 |
+
axes[i].set_title(f'{img_title} {i + 1}')
|
| 258 |
+
|
| 259 |
+
plt.tight_layout()
|
| 260 |
+
plt.show()
|
| 261 |
+
|
| 262 |
+
def visualise_image(frame, img_title='Residual Fragment', debug=True):
|
| 263 |
+
if debug:
|
| 264 |
+
plt.figure(figsize=(5, 5))
|
| 265 |
+
plt.imshow(frame)
|
| 266 |
+
plt.axis('off')
|
| 267 |
+
plt.title(img_title)
|
| 268 |
+
plt.show()
|
| 269 |
+
|
| 270 |
+
if __name__ == "__main__":
|
| 271 |
+
database = 'test'
|
| 272 |
+
videos_dir = '../../test_videos/'
|
| 273 |
+
metadata_csv = '../../metadata/TEST_metadata.csv'
|
| 274 |
+
resize = 224
|
| 275 |
+
patch_size = 16
|
| 276 |
+
target_size = 224
|
| 277 |
+
top_n = 14 * 14
|
| 278 |
+
start_time = time.time()
|
| 279 |
+
resize_transform = transforms.Compose([
|
| 280 |
+
transforms.Resize([resize, resize]),
|
| 281 |
+
transforms.ToTensor(),
|
| 282 |
+
transforms.Normalize(mean=[0.45, 0.45, 0.45], std=[0.225, 0.225, 0.225])
|
| 283 |
+
])
|
| 284 |
+
|
| 285 |
+
dataset = VideoDataset_feature(
|
| 286 |
+
filename_path=metadata_csv,
|
| 287 |
+
data_dir=videos_dir,
|
| 288 |
+
database=database,
|
| 289 |
+
transform=resize_transform,
|
| 290 |
+
resize=resize,
|
| 291 |
+
patch_size=patch_size,
|
| 292 |
+
target_size=target_size,
|
| 293 |
+
top_n=top_n
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
# test
|
| 297 |
+
dataloader = DataLoader(dataset, batch_size=1, shuffle=False)
|
| 298 |
+
|
| 299 |
+
start_time = time.time()
|
| 300 |
+
index = 0
|
| 301 |
+
video_segments, video_res_frag_all, video_frag_all, video_name, frames_info, metadata = dataset[index]
|
| 302 |
+
|
| 303 |
+
print(f"\n=== Video Processed ===")
|
| 304 |
+
print(f"Video Name: {video_name}")
|
| 305 |
+
print(f"Metadata: [MOS, width, height, bitrate, bitdepth, framerate] = {metadata}")
|
| 306 |
+
print(f"Number of Segments: {len(video_segments)}")
|
| 307 |
+
print(f"Number of Video Residual Fragment Segments: {len(video_res_frag_all)}")
|
| 308 |
+
print(f"Number of Video Fragment Segments: {len(video_frag_all)}")
|
| 309 |
+
print(f"Shape of Each Segment: {video_segments[0].shape}") # (video_length_clip, channels, height, width)
|
| 310 |
+
print(f"Shape of Each Residual Fragment Segments: {video_res_frag_all[0].shape}")
|
| 311 |
+
print(f"Shape of Each Fragment Segments: {video_frag_all[0].shape}")
|
| 312 |
+
print(f"Total Key Frame Tuples (frames_info): {len(frames_info)}")
|
| 313 |
+
curr_frame, imp_patch, ori_patch = frames_info[0]
|
| 314 |
+
print("curr_frame shape:", np.array(curr_frame).shape)
|
| 315 |
+
print("imp_patch shape:", np.array(imp_patch).shape)
|
| 316 |
+
print("ori_patch shape:", np.array(ori_patch).shape)
|
| 317 |
+
|
| 318 |
+
# visualisation
|
| 319 |
+
curr_frame, frag_residual, frag_frame = frames_info[0]
|
| 320 |
+
visualise_image(curr_frame, 'Current Frame')
|
| 321 |
+
visualise_image(frag_residual, 'Residual Fragment')
|
| 322 |
+
visualise_image(frag_frame, 'Frame Fragment')
|
| 323 |
+
|
| 324 |
+
visualise_tensor(video_segments[0], num_frames_to_visualise=5, img_title='Frame')
|
| 325 |
+
visualise_tensor(video_res_frag_all[0], num_frames_to_visualise=5, img_title='Residual Frag')
|
| 326 |
+
visualise_tensor(video_frag_all[0], num_frames_to_visualise=5, img_title='Frame Frag')
|
| 327 |
+
print(f"\nTotal Time: {time.time() - start_time:.2f} seconds")
|
extractor/extract_slowfast_clip.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from pytorchvideo.models.hub import slowfast_r50
|
| 4 |
+
|
| 5 |
+
def pack_pathway_output(frames, device):
|
| 6 |
+
fast_pathway = frames
|
| 7 |
+
# temporal sampling from the fast pathway.
|
| 8 |
+
slow_pathway = torch.index_select(
|
| 9 |
+
frames,
|
| 10 |
+
2,
|
| 11 |
+
torch.linspace(0, frames.shape[2] - 1, frames.shape[2] // 4).long(),
|
| 12 |
+
)
|
| 13 |
+
return [slow_pathway.to(device), fast_pathway.to(device)]
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SlowFast(torch.nn.Module):
|
| 17 |
+
def __init__(self):
|
| 18 |
+
super(SlowFast, self).__init__()
|
| 19 |
+
slowfast_pretrained_features = nn.Sequential(*list(slowfast_r50(pretrained=True).children())[0])
|
| 20 |
+
|
| 21 |
+
self.feature_extraction = torch.nn.Sequential()
|
| 22 |
+
self.slow_avg_pool = torch.nn.Sequential()
|
| 23 |
+
self.fast_avg_pool = torch.nn.Sequential()
|
| 24 |
+
self.adp_avg_pool = torch.nn.Sequential()
|
| 25 |
+
|
| 26 |
+
for x in range(0, 5):
|
| 27 |
+
self.feature_extraction.add_module(str(x), slowfast_pretrained_features[x])
|
| 28 |
+
|
| 29 |
+
self.slow_avg_pool.add_module('slow_avg_pool', slowfast_pretrained_features[5].pool[0])
|
| 30 |
+
self.fast_avg_pool.add_module('fast_avg_pool', slowfast_pretrained_features[5].pool[1])
|
| 31 |
+
self.adp_avg_pool.add_module('adp_avg_pool', slowfast_pretrained_features[6].output_pool)
|
| 32 |
+
|
| 33 |
+
def forward(self, x):
|
| 34 |
+
with torch.no_grad():
|
| 35 |
+
x = self.feature_extraction(x)
|
| 36 |
+
slow_feature = self.slow_avg_pool(x[0])
|
| 37 |
+
fast_feature = self.fast_avg_pool(x[1])
|
| 38 |
+
slow_feature = self.adp_avg_pool(slow_feature)
|
| 39 |
+
fast_feature = self.adp_avg_pool(fast_feature)
|
| 40 |
+
return slow_feature, fast_feature
|
| 41 |
+
|
| 42 |
+
def extract_features_slowfast_pool(video, model, device):
|
| 43 |
+
slow_features_list = []
|
| 44 |
+
fast_features_list = []
|
| 45 |
+
|
| 46 |
+
with torch.amp.autocast(device_type='cuda'):
|
| 47 |
+
for idx, segment in enumerate(video):
|
| 48 |
+
segment = segment.permute(0, 2, 1, 3, 4)
|
| 49 |
+
inputs = pack_pathway_output(segment, device)
|
| 50 |
+
# print(f"Inputs shapes: slow={inputs[0].shape}, fast={inputs[1].shape}")
|
| 51 |
+
|
| 52 |
+
# extract features
|
| 53 |
+
slow_feature, fast_feature = model(inputs)
|
| 54 |
+
# global average pooling to reduce dimensions
|
| 55 |
+
slow_feature = slow_feature.mean(dim=[2, 3, 4]) # Pool over spatial and temporal dims
|
| 56 |
+
fast_feature = fast_feature.mean(dim=[2, 3, 4])
|
| 57 |
+
slow_features_list.append(slow_feature)
|
| 58 |
+
fast_features_list.append(fast_feature)
|
| 59 |
+
|
| 60 |
+
# concatenate pooled features
|
| 61 |
+
slow_features = torch.cat(slow_features_list, dim=0)
|
| 62 |
+
fast_features = torch.cat(fast_features_list, dim=0)
|
| 63 |
+
slowfast_features = torch.cat((slow_features, fast_features), dim=1) # along feature dimension
|
| 64 |
+
return slow_features, fast_features, slowfast_features
|
extractor/extract_swint_clip.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
from timm import create_model
|
| 4 |
+
|
| 5 |
+
class Identity(nn.Module):
|
| 6 |
+
def __init__(self):
|
| 7 |
+
super(Identity, self).__init__()
|
| 8 |
+
|
| 9 |
+
def forward(self, x):
|
| 10 |
+
return x
|
| 11 |
+
|
| 12 |
+
class SwinT(nn.Module):
|
| 13 |
+
def __init__(self, model_name='swin_base_patch4_window7_224', global_pool='avg', pretrained=True):
|
| 14 |
+
super(SwinT, self).__init__()
|
| 15 |
+
self.swin_model = create_model(
|
| 16 |
+
model_name, pretrained=pretrained, global_pool=global_pool
|
| 17 |
+
)
|
| 18 |
+
self.swin_model.head = Identity() # Remove classification head
|
| 19 |
+
self.global_pool = global_pool
|
| 20 |
+
|
| 21 |
+
def forward(self, x):
|
| 22 |
+
features = self.swin_model(x) # Shape: (batch_size, 7, 7, 1024)
|
| 23 |
+
if self.global_pool == 'avg':
|
| 24 |
+
features = features.mean(dim=[1, 2]) # Global pool
|
| 25 |
+
return features
|
| 26 |
+
|
| 27 |
+
def extract_features_swint_pool(video, model, device):
|
| 28 |
+
swint_feature_list = []
|
| 29 |
+
|
| 30 |
+
with torch.amp.autocast(device_type='cuda'):
|
| 31 |
+
for segment in video:
|
| 32 |
+
# Flatten the segment into a batch of frames
|
| 33 |
+
frames = segment.squeeze(0).to(device) # Shape: (32, 3, 224, 224)
|
| 34 |
+
|
| 35 |
+
swint_features = model(frames) # Shape: (32, feature_dim)
|
| 36 |
+
swint_feature_list.append(swint_features)
|
| 37 |
+
|
| 38 |
+
# Concatenate features across segments
|
| 39 |
+
features = torch.cat(swint_feature_list, dim=0) # Shape: (num_frames, feature_dim)
|
| 40 |
+
return features
|
model/.DS_Store
ADDED
|
Binary file (10.2 kB). View file
|
|
|
model/finetune/.DS_Store
ADDED
|
Binary file (8.2 kB). View file
|
|
|
model/finetune/cvd_2014_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:577a57259bcb14d536cb9be01e735a9659a418523a5f6882e1d6f0aa34a1a879
|
| 3 |
+
size 13511298
|
model/finetune/finevd_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:96f2baf34f0aeb853cdaf498a38b0bfaa4d05085ee7ad0bbe083050ed7613b9c
|
| 3 |
+
size 13511148
|
model/finetune/konvid_1k_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c96602e5c2aeb644487af17215f3dd79c48f56f06c7a41a130a48cb70f7de4ee
|
| 3 |
+
size 13511794
|
model/finetune/kvq_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:76b2e72b802565a29892f2570555575ee00982253591f914e78528118a32a7a7
|
| 3 |
+
size 13511103
|
model/finetune/live_vqc_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0962ea94657840d3afe4b7099ae532635c7cf1e21dab3c9df476d090fc892cb1
|
| 3 |
+
size 13511298
|
model/finetune/live_yt_gaming_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9030af7485bbda2661c8c208c288f0b50cead0bc1bf600934eb02dd2e1893796
|
| 3 |
+
size 13511874
|
model/finetune/youtube_ugc_h264_camp-vqa_fine_tuned_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3a19c4fb90d6b44929f0dcfb276d5daf44b12f73b08a8b861cd8fa93fcdd6924
|
| 3 |
+
size 13511418
|
model/wo_finetune/.DS_Store
ADDED
|
Binary file (8.2 kB). View file
|
|
|
model/wo_finetune/cvd_2014_camp-vqa_Mlp_byrmse_trained_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e30fbbbc821527e4204d84b1145f9ace84061779208a313180abd2cb8b377368
|
| 3 |
+
size 13506412
|
model/wo_finetune/finevd_camp-vqa_Mlp_byrmse_trained_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c47579161d9bf8037d12baebcfc2d4ca49d0037d3dc77612d199606d1f43fe48
|
| 3 |
+
size 13506031
|
model/wo_finetune/konvid_1k_camp-vqa_Mlp_byrmse_trained_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9d73eb32a787b243a7b5aacbc8bf16ea91179f6aa89dc6980081ff422a2c05a9
|
| 3 |
+
size 13506487
|
model/wo_finetune/kvq_camp-vqa_Mlp_byrmse_trained_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1ca9718e13e7446df65bfdfb519c63004eb5df85c19260fa37e7f05f068bdd52
|
| 3 |
+
size 13505998
|
model/wo_finetune/live_vqc_camp-vqa_Mlp_byrmse_trained_mode.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:464a2fa7f837658c01f113b503f37699cf2e9e809e258f09a0dc08808e5baf88
|
| 3 |
+
size 13506412
|
model/wo_finetune/live_yt_gaming_camp-vqa_Mlp_byrmse_trained_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:af0893a05ebc27512eede807f8c663f962b1fe6578aeb9d597abeefab58e304b
|
| 3 |
+
size 13506271
|
model/wo_finetune/lsvq_train_camp-vqa_Mlp_byrmse_trained_model_1080p.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d3beef20985f987dc89b33524f55d136ab23e2aab6eb936d29c3d2cc7a3d14ae
|
| 3 |
+
size 13512098
|
model/wo_finetune/lsvq_train_camp-vqa_Mlp_byrmse_trained_model_kfold.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bec5863ae799a9f496d597d576b7e37dcdbea5df9e1c05a80d5da66591972fc7
|
| 3 |
+
size 13512754
|
model/wo_finetune/youtube_ugc_h264_camp-vqa_Mlp_byrmse_trained_model.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8efe4d8b5817453da1dd6664914e5d0b5a307b7f5746b17939d7059622efcbdd
|
| 3 |
+
size 13506692
|
ugc_original_videos/0_16_07_500001604801190-yase.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:41b1f2a7cf48cda0a3adc956a98c864115dc83b692fcfb26d46814cb9fd9e9bc
|
| 3 |
+
size 3883352
|