mohAhmad commited on
Commit
6799494
1 Parent(s): bddd311

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -0
app.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from transformers import AutoProcessor, VisionEncoderDecoderModel
3
+ import requests
4
+ from PIL import Image
5
+ import torch
6
+
7
+ # Load processor and model
8
+ st.title("Image to Text Captioning App")
9
+ st.write("This app converts an image into a text description using the ViT-GPT2 model.")
10
+
11
+ @st.cache_resource
12
+ def load_model():
13
+ processor = AutoProcessor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
14
+ model = VisionEncoderDecoderModel.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
15
+ return processor, model
16
+
17
+ processor, model = load_model()
18
+
19
+ # Upload image
20
+ uploaded_file = st.file_uploader("Upload an image", type=["jpg", "png", "jpeg"])
21
+
22
+ if uploaded_file is not None:
23
+ image = Image.open(uploaded_file).convert("RGB")
24
+ st.image(image, caption="Uploaded Image", use_column_width=True)
25
+
26
+ # Preprocessing image
27
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values
28
+
29
+ # Generate caption
30
+ generated_ids = model.generate(pixel_values)
31
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
32
+
33
+ st.write("Generated Caption: ")
34
+ st.success(generated_text)