jaimin commited on
Commit
3b4a036
·
1 Parent(s): 8db6646

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -0
app.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ def predict(image,max_length=64, num_beams=4):
16
+ image = image.convert('RGB')
17
+ image = feature_extractor(image, return_tensors="pt").pixel_values.to(device)
18
+ clean_text = lambda x: x.replace('<|endoftext|>','').split('\n')[0]
19
+ caption_ids = model.generate(image, max_length = max_length)[0]
20
+ caption_text = clean_text(tokenizer.decode(caption_ids))
21
+ return caption_text
22
+
23
+
24
+
25
+ input = gr.inputs.Image(label="Upload your Image", type = 'pil', optional=True)
26
+ output = gr.outputs.Textbox(type="auto",label="Captions")
27
+ examples = [f"example{i}.jpg" for i in range(1,7)]
28
+
29
+ title = "Image Captioning "
30
+
31
+ interface = gr.Interface(
32
+ fn=predict,
33
+ inputs = input,
34
+ theme="grass",
35
+ outputs=output,
36
+ examples = examples,
37
+ title=title,
38
+ )
39
+ interface.launch(debug=True)