insta_captions / app.py
yash-srivastava19's picture
Create app.py
e9757be
raw
history blame
1.85 kB
import cohere
import gradio as gr
from transformers import AutoTokenizer, ViTFeatureExtractor, VisionEncoderDecoderModel
co_client = cohere.Client('29JdDGuDUqPx2jqTkQUtsJqZRIwUoqwPKd2j9CRA')
device = 'cpu'
encoder_checkpoint = "nlpconnect/vit-gpt2-image-captioning"
decoder_checkpoint = "nlpconnect/vit-gpt2-image-captioning"
model_checkpoint = "nlpconnect/vit-gpt2-image-captioning"
feature_extractor = ViTFeatureExtractor.from_pretrained(encoder_checkpoint)
tokenizer = AutoTokenizer.from_pretrained(decoder_checkpoint)
model = VisionEncoderDecoderModel.from_pretrained(model_checkpoint).to(device)
def predict(image, max_length=64, num_beams=4):
image = image.convert('RGB')
image = feature_extractor(image, return_tensors="pt").pixel_values.to(device)
clean_text = lambda x: x.replace('<|endoftext|>', '').split('\n')[0]
caption_ids = model.generate(image, max_length=max_length)[0]
img_caption_text = clean_text(tokenizer.decode(caption_ids))
caption_text = creative_caption(img_caption_text)
hashtags = caption_hashtags(img_caption_text)
return caption_text, hashtags
def creative_caption(text):
return co_client.generate(prompt=f"Write some trendy instagram captions for the following prompt - {text}")
def caption_hashtags(text):
return co_client.generate(prompt=f"Write some trendy instagram hashtags for the following prompt - {text}")
input_upload = gr.inputs.Image(label="Upload any Image", type='pil', optional=True)
output = [
gr.outputs.Textbox(type="auto", label="Captions"),
gr.outputs.Textbox(type="auto", label="Hashtags"),
]
title = "Image Captioning "
description = "Made for Linesh"
interface = gr.Interface(
fn=predict,
description=description,
inputs=input_upload,
theme="grass",
outputs=output,
title=title,
)
interface.launch(debug=True)