Create app.py
Browse filesGitHub Repository: https://github.com/CapstoneProjectimagecaptioning/image_captioning_transformer
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import gradio as gr
|
3 |
+
from transformers import AutoTokenizer, ViTImageProcessor, VisionEncoderDecoderModel
|
4 |
+
|
5 |
+
device = 'cpu'
|
6 |
+
|
7 |
+
# Load the pretrained model, feature extractor, and tokenizer
|
8 |
+
model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning").to(device)
|
9 |
+
feature_extractor = ViTImageProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
10 |
+
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
|
11 |
+
|
12 |
+
def predict(image, max_length=64, num_beams=4):
|
13 |
+
# Process the input image
|
14 |
+
image = image.convert('RGB')
|
15 |
+
pixel_values = feature_extractor(images=image, return_tensors="pt").pixel_values.to(device)
|
16 |
+
|
17 |
+
# Generate the caption
|
18 |
+
caption_ids = model.generate(pixel_values, max_length=max_length, num_beams=num_beams)[0]
|
19 |
+
|
20 |
+
# Decode and clean the generated caption
|
21 |
+
caption = tokenizer.decode(caption_ids, skip_special_tokens=True)
|
22 |
+
return caption
|
23 |
+
|
24 |
+
css = '''
|
25 |
+
h1#title {
|
26 |
+
text-align: center;
|
27 |
+
}
|
28 |
+
h3#header {
|
29 |
+
text-align: center;
|
30 |
+
}
|
31 |
+
img#overview {
|
32 |
+
max-width: 800px;
|
33 |
+
max-height: 600px;
|
34 |
+
}
|
35 |
+
img#style-image {
|
36 |
+
max-width: 1000px;
|
37 |
+
max-height: 600px;
|
38 |
+
}
|
39 |
+
'''
|
40 |
+
|
41 |
+
demo = gr.Blocks(css=css)
|
42 |
+
|
43 |
+
with demo:
|
44 |
+
gr.Markdown('''<h1 id="title">Automated Image Captioning Using Generative AI: A Transformer based approach 🖼️</h1>''')
|
45 |
+
gr.Markdown('Contributed by : Premanth Alahari, Charan Gudivada')
|
46 |
+
|
47 |
+
with gr.Column():
|
48 |
+
input_image = gr.Image(label="Upload your Image", type='pil')
|
49 |
+
output_caption = gr.Textbox(label="Generated Caption")
|
50 |
+
|
51 |
+
btn = gr.Button("Generate Caption")
|
52 |
+
btn.click(fn=predict, inputs=input_image, outputs=output_caption)
|
53 |
+
|
54 |
+
demo.launch()
|