Spaces:
Sleeping
Sleeping
Download app.py from Hassan501/IMageCaptioning: direct link, hf CLI and curl.
- Browser
- Download file 2.42 kB
-
https://huggingface.co/spaces/Hassan501/IMageCaptioning/resolve/main/app.py
- Command line
-
hf download hf://spaces/Hassan501/IMageCaptioning/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Hassan501/IMageCaptioning/resolve/main/app.py
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 --- | |
| 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. |