Ankan Ghosh commited on
Commit
45296db
·
1 Parent(s): 0d5d5f5

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +62 -0
  2. requirement.txt +5 -0
app.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #imported all required libraries
2
+ import streamlit as st
3
+ import torch
4
+ import requests
5
+ from PIL import Image
6
+ from io import BytesIO
7
+ from transformers import ViTFeatureExtractor, AutoTokenizer, VisionEncoderDecoderModel
8
+
9
+
10
+ #used a pretrained model hosted on huggingface
11
+ loc = "ydshieh/vit-gpt2-coco-en"
12
+
13
+ feature_extractor = ViTFeatureExtractor.from_pretrained(loc)
14
+ tokenizer = AutoTokenizer.from_pretrained(loc)
15
+ model = VisionEncoderDecoderModel.from_pretrained(loc)
16
+ model.eval()
17
+
18
+ #defined a function for prediction
19
+
20
+ def predict(image):
21
+ pixel_values = feature_extractor(images=image, return_tensors="pt").pixel_values
22
+
23
+ with torch.no_grad():
24
+ output_ids = model.generate(pixel_values, max_length=16, num_beams=4, return_dict_in_generate=True).sequences
25
+
26
+ preds = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
27
+ preds = [pred.strip() for pred in preds]
28
+
29
+ return preds
30
+
31
+ #defined a function for Streamlit App
32
+ def app():
33
+ st.title("Image Captioner")
34
+ st.write("ViT and GPT2 are used to generate Image Caption for the uploaded image. COCO Dataset was used for training. This image captioning model might have some biases that I couldn’t figure during testing")
35
+ st.write("Upload an image or paste a URL to get predicted captions.")
36
+
37
+ upload_option = st.selectbox("Choose an option:", ("Upload Image", "Paste URL"))
38
+
39
+ if upload_option == "Upload Image":
40
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "jpeg"])
41
+
42
+ if uploaded_file is not None:
43
+ image = Image.open(uploaded_file)
44
+ preds = predict(image)
45
+ st.image(image, caption="Uploaded Image", use_column_width=True)
46
+ st.write("Predicted Caption:", preds)
47
+
48
+
49
+ elif upload_option == "Paste URL":
50
+ image_url = st.text_input("Enter Image URL")
51
+ if st.button("Submit") and image_url:
52
+ try:
53
+ response = requests.get(image_url, stream=True)
54
+ image = Image.open(BytesIO(response.content))
55
+ preds = predict(image)
56
+ st.image(image, caption="Image from URL", use_column_width=True)
57
+ st.write("Predicted Caption:", preds)
58
+ except:
59
+ st.write("Error: Invalid URL or unable to fetch image.")
60
+
61
+ if __name__ == "__main__":
62
+ app()
requirement.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch==2.0.1
2
+ streamlit==1.22.0
3
+ transformers==4.29.2
4
+ requests
5
+ pillow