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

111 lines
4.1 KiB

# 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 sys
import os
from pathlib import Path
import torch
from torchvision import transforms
from transformers import GPT2Tokenizer
from towhee.types.arg import arg, to_image_color
from towhee.types.image_utils import to_pil
from towhee.operator.base import NNOperator, OperatorFlag
from towhee import register
from towhee.models import clip
from towhee.command.s3 import S3Bucket
from transformers import GPT2Tokenizer, GPT2LMHeadModel, AdamW, get_linear_schedule_with_warmup
class Capdec(NNOperator):
"""
CapDec image captioning operator
"""
def __init__(self, model_name: str):
super().__init__()
sys.path.append(str(Path(__file__).parent))
from modules import ClipCaptionModel, generate_beam, generate2
path = str(Path(__file__).parent)
config = self._configs()[model_name]
s3_bucket = S3Bucket()
s3_bucket.download_file(config['weights'], path + '/weights/')
model_path = path + '/weights/' + os.path.basename(config['weights'])
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.clip_caption_model = ClipCaptionModel()
self.clip_caption_model.load_state_dict(torch.load(model_path, map_location=torch.device('cpu')))
self.clip_caption_model.to(self.device)
self.clip_caption_model.eval()
self.clip_model = clip.create_model(model_name='clip_resnet_r50x4', pretrained=True, jit=True)
self.clip_model.to(self.device)
self.clip_tfms = clip.get_transforms(model_name='clip_resnet_r50x4')
self.tokenizer = GPT2Tokenizer.from_pretrained("gpt2").to(self.device)
self.generate_beam = generate_beam
self.generate2 = generate2
@arg(1, to_image_color('RGB'))
def inference_single_data(self, data):
text = self._inference_from_image(data)
return text
def _preprocess(self, img):
img = to_pil(img)
processed_img = self.clip_tfms(img).unsqueeze(0).to(self.device)
return processed_img
def __call__(self, data):
if not isinstance(data, list):
data = [data]
else:
data = data
results = []
for single_data in data:
result = self.inference_single_data(single_data)
results.append(result)
if len(data) == 1:
return results[0]
else:
return results
@arg(1, to_image_color('RGB'))
def _inference_from_image(self, img):
img = self._preprocess(img)
use_beam_search = True
with torch.no_grad():
prefix = self.clip_model.encode_image(img)[0].to(self.device, dtype=torch.float32).unsqueeze(0)
prefix_embed = self.clip_caption_model.clip_project(prefix).reshape(1, 40, -1)
if use_beam_search:
generated_text_prefix = self.generate_beam(self.clip_caption_model, self.tokenizer, embed=prefix_embed)[0]
else:
generated_text_prefix = self.generate2(self.clip_caption_model, self.tokenizer, embed=prefix_embed)
return generated_text_prefix
def _configs(self):
config = {}
config['capdec_noise_0'] = {}
config['capdec_noise_0']['weights'] = 'image-captioning/capdec/0.pt'
config['capdec_noise_01'] = {}
config['capdec_noise_01']['weights'] = 'image-captioning/capdec/01.pt'
config['capdec_noise_001'] = {}
config['capdec_noise_001']['weights'] = 'image-captioning/capdec/001.pt'
config['capdec_noise_0001'] = {}
config['capdec_noise_0001']['weights'] = 'image-captioning/capdec/0001.pt'
return config