File size: 2,416 Bytes
781f5dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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.