IMageCaptioning / app.py
Hassan501's picture
Create app.py
781f5dc verified
Raw History Blame Contribute Delete
2.42 kB
import streamlit as st
from transformers import BlipProcessor, BlipForConditionalGeneration
from PIL import Image
import torch
# Set Streamlit page configuration for an attractive, wide layout
st.set_page_config(layout="wide", page_title="Image Captioning AI")
# --- Function to load the model and processor ---
@st.cache_resource
def load_model():
"""
Loads the BLIP-2 model and processor and caches it.
This prevents the model from reloading every time the user interacts with the app.
"""
processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
model = BlipForConditionalGeneration.from_pretrained(
"Salesforce/blip-image-captioning-large"
).to("cpu") # Use "cpu" for free tier deployment
return processor, model
# Load the model and processor
processor, model = load_model()
# --- Front-end UI Design ---
st.title("📸 AI Image Captioning with BLIP-2")
st.markdown(
"""
Upload an image and let the AI generate a descriptive caption for it.
This app uses the powerful **BLIP-2** model by Salesforce.
"""
)
# Create a file uploader widget
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)
st.image(image, caption="Uploaded Image", use_column_width=True)
# Add a button to generate the caption
if st.button("Generate Caption"):
with st.spinner("Generating caption..."):
try:
# Preprocess the image and generate the caption
inputs = processor(images=image, return_tensors="pt")
outputs = model.generate(**inputs)
caption = processor.decode(outputs[0], skip_special_tokens=True)
# Display the generated caption
st.subheader("📝 Generated Caption")
st.info(caption)
except Exception as e:
st.error(f"An error occurred: {e}")
# --- Customizing the UI with Streamlit's theming ---
# To make the app more attractive, you can create a .streamlit/config.toml file
# and add a theme. For example:
# [theme]
# primaryColor = "#F63366"
# backgroundColor = "#FFFFFF"
# secondaryBackgroundColor = "#F0F2F6"
# textColor = "#262730"
# font = "sans serif"
# This theme gives the app a clean, professional look.