Spaces:
Runtime error
Runtime error
File size: 1,288 Bytes
91b95fb 1706d00 5888e2a 91b95fb 5888e2a 91b95fb 5888e2a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import streamlit as st
from PIL import Image
import torch
from transformers import BlipProcessor, BlipForConditionalGeneration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_name = "Salesforce/blip-image-captioning-base"
processor = BlipProcessor.from_pretrained(model_name)
model = BlipForConditionalGeneration.from_pretrained(model_name)
# β
PyTorch 2.6 fix
state_dict = torch.load("model_chunk_21.pt", map_location=device, weights_only=False)
model.load_state_dict(state_dict)
model.to(device)
model.eval()
def predict_caption(image):
inputs = processor(image, return_tensors="pt").to(device)
with torch.no_grad():
output_ids = model.generate(**inputs, max_length=16, num_beams=4)
caption = processor.decode(output_ids[0], skip_special_tokens=True)
return caption
st.title("Image Captioning with BLIP")
st.write("Upload an image and get a generated caption!")
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
image = Image.open(uploaded_file).convert("RGB")
st.image(image, caption="Uploaded Image", use_column_width=True)
if st.button("Generate Caption"):
caption = predict_caption(image)
st.markdown(f"**Caption:** {caption}")
|