ChandraP12330 commited on
Commit
cb5683a
1 Parent(s): 86fa1f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -15
app.py CHANGED
@@ -1,19 +1,37 @@
1
  import streamlit as st
2
- from transformers import pipeline
3
- from PIL import Image
4
- import torch
5
 
6
- ##BLIP
7
- # Create the caption pipeline
8
- initial_caption = pipeline('image-to-text', model="Salesforce/blip-image-captioning-large")
9
 
10
- # Display the image using Streamlit
11
- uploaded_image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
12
- if uploaded_image is not None:
13
- image= Image.open(uploaded_image)
14
- st.image(image, caption="Uploaded Image", use_column_width=True)
 
 
 
 
 
 
15
 
16
- # Generate the caption
17
- if st.button("Generate Caption"):
18
- captions = initial_caption(image)
19
- st.write(captions[0]['generated_text'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from transformers import BlipForConditionalGeneration, BlipProcessor
 
 
3
 
4
+ # Load the BLIP model and processor
5
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large")
6
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
7
 
8
+ def generate_caption(image):
9
+ # Preprocess the image
10
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values
11
+
12
+ # Generate caption using the BLIP model
13
+ output_ids = model.generate(pixel_values, max_length=50, num_beams=4, early_stopping=True)
14
+
15
+ # Decode the caption
16
+ caption = processor.decode(output_ids[0], skip_special_tokens=True)
17
+
18
+ return caption
19
 
20
+ def main():
21
+ st.title("Image Caption Generator")
22
+
23
+ # Upload image
24
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
25
+
26
+ if uploaded_file is not None:
27
+ # Display the uploaded image
28
+ image = st.image(uploaded_file, caption="Uploaded Image", use_column_width=True)
29
+
30
+ # Generate caption
31
+ if st.button("Generate Caption"):
32
+ with st.spinner("Generating caption..."):
33
+ caption = generate_caption(uploaded_file.getvalue())
34
+ st.success(f"Caption: {caption}")
35
+
36
+ if __name__ == "__main__":
37
+ main()