Spaces:
Runtime error
Runtime error
Download app.py from berkaydun/Image-Captioning: direct link, hf CLI and curl.
- Browser
- Download file 1.29 kB
-
https://huggingface.co/spaces/berkaydun/Image-Captioning/resolve/main/app.py
- Command line
-
hf download hf://spaces/berkaydun/Image-Captioning/app.py
-
curl -L -o app.py https://huggingface.co/spaces/berkaydun/Image-Captioning/resolve/main/app.py
1.29 kB
| 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}") | |