Spaces:
Sleeping
Sleeping
Upload app.py with huggingface_hub
Browse files
app.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
description= "Image captioning application made using transformers"
|
30 |
+
title = "Image Captioning 🖼️"
|
31 |
+
|
32 |
+
article = "Created By : Shreyas Dixit "
|
33 |
+
|
34 |
+
interface = gr.Interface(
|
35 |
+
fn=predict,
|
36 |
+
inputs = input,
|
37 |
+
theme="grass",
|
38 |
+
outputs=output,
|
39 |
+
examples = examples,
|
40 |
+
title=title,
|
41 |
+
description=description,
|
42 |
+
article = article,
|
43 |
+
)
|
44 |
+
interface.launch(debug=True)
|