import streamlit as st from PIL import Image from transformers import Blip2Processor, Blip2ForConditionalGeneration import torch # Set the device to use device = "cuda" if torch.cuda.is_available() else "cpu" # Title and description st.set_page_config(page_title="BLIP-2 Image Captioning") st.title("Image Captioning with BLIP-2") st.write("Upload an image and let the model generate a caption for it.") # Use st.cache_resource to cache the model and processor # This prevents them from being reloaded on every user interaction @st.cache_resource def load_model(): """ Loads the BLIP-2 model and processor from Hugging Face. """ processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b") model = Blip2ForConditionalGeneration.from_pretrained( "Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16 if device == "cuda" else torch.float32 ) return processor, model # Load the model and processor processor, model = load_model() model.to(device) # File uploader uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"]) if uploaded_file is not None: # Display the uploaded image image = Image.open(uploaded_file).convert("RGB") st.image(image, caption='Uploaded Image', use_column_width=True) st.write("") st.write("Generating caption...") # Preprocess the image and generate a caption inputs = processor(images=image, return_tensors="pt").to(device, torch.float16 if device == "cuda" else torch.float32) generated_ids = model.generate(**inputs, max_length=50) # Decode and display the caption caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() st.subheader("Generated Caption:") st.success(caption)