Hassan501 commited on
Commit
ce32235
·
verified ·
1 Parent(s): 68860b4

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -0
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from PIL import Image
3
+ from transformers import Blip2Processor, Blip2ForConditionalGeneration
4
+ import torch
5
+
6
+ # Set the device to use
7
+ device = "cuda" if torch.cuda.is_available() else "cpu"
8
+
9
+ # Title and description
10
+ st.set_page_config(page_title="BLIP-2 Image Captioning")
11
+ st.title("Image Captioning with BLIP-2")
12
+ st.write("Upload an image and let the model generate a caption for it.")
13
+
14
+ # Use st.cache_resource to cache the model and processor
15
+ # This prevents them from being reloaded on every user interaction
16
+ @st.cache_resource
17
+ def load_model():
18
+ """
19
+ Loads the BLIP-2 model and processor from Hugging Face.
20
+ """
21
+ processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
22
+ model = Blip2ForConditionalGeneration.from_pretrained(
23
+ "Salesforce/blip2-opt-2.7b",
24
+ torch_dtype=torch.float16 if device == "cuda" else torch.float32
25
+ )
26
+ return processor, model
27
+
28
+ # Load the model and processor
29
+ processor, model = load_model()
30
+ model.to(device)
31
+
32
+ # File uploader
33
+ uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
34
+
35
+ if uploaded_file is not None:
36
+ # Display the uploaded image
37
+ image = Image.open(uploaded_file).convert("RGB")
38
+ st.image(image, caption='Uploaded Image', use_column_width=True)
39
+ st.write("")
40
+ st.write("Generating caption...")
41
+
42
+ # Preprocess the image and generate a caption
43
+ inputs = processor(images=image, return_tensors="pt").to(device, torch.float16 if device == "cuda" else torch.float32)
44
+ generated_ids = model.generate(**inputs, max_length=50)
45
+
46
+ # Decode and display the caption
47
+ caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip()
48
+
49
+ st.subheader("Generated Caption:")
50
+ st.success(caption)