Up
Browse files
app.py
CHANGED
@@ -1,36 +1,38 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
gr.
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import re
|
3 |
+
import gradio as gr
|
4 |
+
from transformers import AutoTokenizer, ViTFeatureExtractor, VisionEncoderDecoderModel
|
5 |
+
|
6 |
+
device='cpu'
|
7 |
+
encoder_checkpoint = "nlpconnect/vit-gpt2-image-captioning"
|
8 |
+
decoder_checkpoint = "nlpconnect/vit-gpt2-image-captioning"
|
9 |
+
model_checkpoint = "nlpconnect/vit-gpt2-image-captioning"
|
10 |
+
feature_extractor = ViTFeatureExtractor.from_pretrained(encoder_checkpoint)
|
11 |
+
tokenizer = AutoTokenizer.from_pretrained(decoder_checkpoint)
|
12 |
+
model = VisionEncoderDecoderModel.from_pretrained(model_checkpoint).to(device)
|
13 |
+
|
14 |
+
def predict(image,max_length=64, num_beams=4):
|
15 |
+
image = image.convert('RGB')
|
16 |
+
image = feature_extractor(image, return_tensors="pt").pixel_values.to(device)
|
17 |
+
clean_text = lambda x: x.replace('<|endoftext|>','').split('\n')[0]
|
18 |
+
caption_ids = model.generate(image, max_length = max_length)[0]
|
19 |
+
caption_text = clean_text(tokenizer.decode(caption_ids))
|
20 |
+
return caption_text
|
21 |
+
|
22 |
+
input = gr.inputs.Image(label="Upload any Image", type = 'pil', optional=True)
|
23 |
+
output = gr.outputs.Textbox(type="auto",label="Captions")
|
24 |
+
examples = [f"example{i}.jpg" for i in range(1,7)]
|
25 |
+
|
26 |
+
title = "Image Captioning "
|
27 |
+
description = "Made by : shreyasdixit.tech"
|
28 |
+
interface = gr.Interface(
|
29 |
+
|
30 |
+
fn=predict,
|
31 |
+
description=description,
|
32 |
+
inputs = input,
|
33 |
+
theme="grass",
|
34 |
+
outputs=output,
|
35 |
+
examples = examples,
|
36 |
+
title=title,
|
37 |
+
)
|
38 |
+
interface.launch(debug=True)
|