|
|
|
# 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.
|
|
|
|
|
|
|
|
|
|
|
|
from typing import Dict
|
|
|
|
|
|
|
|
from pathlib import Path
|
|
|
|
from towhee.operator.base import NNOperator
|
|
|
|
from towhee import register
|
|
|
|
from towhee.models import collaborative_experts
|
|
|
|
|
|
|
|
import warnings
|
|
|
|
|
|
|
|
warnings.filterwarnings('ignore')
|
|
|
|
|
|
|
|
|
|
|
|
@register(output_schema=['vec'])
|
|
|
|
class CollaborativeExperts(NNOperator):
|
|
|
|
"""
|
|
|
|
CollaborativeExperts embedding operator
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, config: Dict = None, weights_path: str = None, device: str = None):
|
|
|
|
super().__init__()
|
|
|
|
if weights_path is None:
|
|
|
|
weights_path = str(Path(__file__).parent / 'model_state_dict.pth')
|
|
|
|
self.ce_net_model = collaborative_experts.create_model(config, weights_path, device)
|
|
|
|
|
|
|
|
def __call__(self, experts, ind, text):
|
|
|
|
out = self.ce_net_model(experts, ind, text)
|
|
|
|
text_embds = {k: v.squeeze(1).detach().cpu().numpy() for k, v in out['text_embds'].items()}
|
|
|
|
vid_embds = {k: v.detach().cpu().numpy() for k, v in out['vid_embds'].items()}
|
|
|
|
return text_embds, vid_embds
|
|
|
|
|
|
|
|
def get_text_embds(self, experts, ind, text):
|
|
|
|
out = self.ce_net_model(experts, ind, text)
|
|
|
|
text_embds = {k: v.squeeze(1).detach().cpu().numpy() for k, v in out['text_embds'].items()}
|
|
|
|
return text_embds
|
|
|
|
|
|
|
|
def get_vid_embds(self, experts, ind, text):
|
|
|
|
out = self.ce_net_model(experts, ind, text)
|
|
|
|
vid_embds = {k: v.detach().cpu().numpy() for k, v in out['vid_embds'].items()}
|
|
|
|
return vid_embds
|
|
|
|
|
|
|
|
def get_cross_view_conf_matrix(self, experts, ind, text):
|
|
|
|
out = self.ce_net_model(experts, ind, text)
|
|
|
|
return out['cross_view_conf_matrix'].detach().cpu().numpy()
|
|
|
|
|