logo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Readme
Files and versions

110 lines
4.5 KiB

2 years ago
# Copyright 2021 Zilliz. 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
2 years ago
from typing import List, Union
2 years ago
from torchvision import transforms
from towhee.models.clip4clip import convert_tokens_to_id
2 years ago
from towhee.operator.base import NNOperator
2 years ago
from towhee import register
from towhee.models import clip4clip
from PIL import Image as PILImage
from towhee.types import VideoFrame
from pathlib import Path
2 years ago
2 years ago
@register(output_schema=['vec'])
2 years ago
class CLIP4Clip(NNOperator):
"""
2 years ago
CLIP4Clip multi-modal embedding operator
2 years ago
"""
2 years ago
def __init__(self, model_name: str, modality: str, weight_path: str = None, device: str = None):
2 years ago
super().__init__()
self.modality = modality
if weight_path is None:
weight_path = str(Path(__file__).parent / 'pytorch_model.bin.1')
2 years ago
# print('weight_path is None, use default path: {}'.format(weight_path))
if device is None:
self.device = "cuda" if torch.cuda.is_available() else "cpu"
else:
self.device = device
2 years ago
self.model = clip4clip.create_model(model_name=model_name,
context_length=77,
pretrained=True,
weights_path=weight_path,
device=self.device)
self.tokenize = clip4clip.SimpleTokenizer()
self.tfms = transforms.Compose([
transforms.Resize(224, interpolation=transforms.InterpolationMode.BICUBIC),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
2 years ago
(0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))
])
2 years ago
self.model.eval()
def __call__(self, data: Union[str, List[VideoFrame]]):
2 years ago
if self.modality == 'video':
vec = self._inference_from_video(data)
elif self.modality == 'text':
vec = self._inference_from_text(data)
else:
raise ValueError("modality[{}] not implemented.".format(self._modality))
return vec
2 years ago
def _inference_from_text(self, text: str):
2 years ago
self.model.eval()
text_ids = convert_tokens_to_id(self.tokenize, text)
text_ids = torch.tensor(text_ids).unsqueeze(0).to(self.device)
text_features = self.model.get_sequence_output(text_ids)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
2 years ago
return text_features.detach().flatten().cpu().numpy()
2 years ago
def _inference_from_video(self, img_list: List[VideoFrame]):
2 years ago
self.model.eval()
max_frames = 12
2 years ago
video = np.zeros((1, max_frames, 1, 3, 224, 224), dtype=np.float64)
2 years ago
slice_len = len(img_list)
max_video_length = 0 if 0 > slice_len else slice_len
for i, img in enumerate(img_list):
pil_img = PILImage.fromarray(img, img.mode)
tfmed_img = self.tfms(pil_img).unsqueeze(0)
2 years ago
if slice_len >= 1:
video[0, i, ...] = tfmed_img.cpu().numpy()
2 years ago
video_mask = np.zeros((1, max_frames), dtype=np.int32)
2 years ago
video_mask[0, :max_video_length] = [1] * max_video_length
video = torch.as_tensor(video).float().to(self.device)
2 years ago
pair, bs, ts, channel, h, w = video.shape
video = video.view(pair * bs * ts, channel, h, w)
video_mask = torch.as_tensor(video_mask).float().to(self.device)
2 years ago
visual_output = self.model.get_visual_output(video, video_mask, shaped=True)
visual_output = visual_output / visual_output.norm(dim=-1, keepdim=True)
video_mask_un = video_mask.to(dtype=torch.float).unsqueeze(-1)
visual_output = visual_output * video_mask_un
video_mask_un_sum = torch.sum(video_mask_un, dim=1, dtype=torch.float)
video_mask_un_sum[video_mask_un_sum == 0.] = 1.
visual_output = torch.sum(visual_output, dim=1) / video_mask_un_sum
visual_output = visual_output / visual_output.norm(dim=-1, keepdim=True)
2 years ago
return visual_output.detach().flatten().cpu().numpy()