SRDdev commited on
Commit
c8081ec
1 Parent(s): 30fc802

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -0
app.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 'google/vit-base-patch16-224'
8
+ decoder_checkpoint = 'gpt2'
9
+ model_checkpoint = 'nlpconnect/vit-gpt2-image-captioning'
10
+ feature_extractor = ViTFeatureExtractor.from_pretrained(encoder_checkpoint)
11
+ model = VisionEncoderDecoderModel.from_pretrained(model_checkpoint).to(device)
12
+
13
+
14
+ def predict(image,max_length=64,num_beams=4):
15
+ image = image.convert('RGB')
16
+ image = feature_extractor(image,return_tensor='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
+
23
+ input = gr.inputs.Image(label='Image to generate caption',type = 'pil', optional=False)
24
+ output = gr.outputs.Textbox(type="auto",label="Caption")
25
+
26
+ article = "This is a Image captioning model created by Shreyas Dixit"
27
+ title = "Image Captioning"
28
+
29
+ interface = gr.Interface(
30
+ fn=predict,
31
+ inputs = input,
32
+ theme="grass",
33
+ outputs=output,
34
+ examples = examples,
35
+ title=title,
36
+ description=article,
37
+ )
38
+ interface.launch(debug=True)