Image_Cap / app.py
Lokesh1024's picture
Update app.py
215e3fc verified
raw
history blame
1.77 kB
import io
import os
import streamlit as st
import requests
from PIL import Image
from model import get_caption_model, generate_caption
# Initialize session state for the model
if 'caption_model' not in st.session_state:
st.session_state.caption_model = get_caption_model()
def predict():
captions = []
try:
pred_caption = generate_caption('tmp.jpg', st.session_state.caption_model)
st.markdown('#### Predicted Captions:')
captions.append(pred_caption)
for _ in range(4):
pred_caption = generate_caption('tmp.jpg', st.session_state.caption_model, add_noise=True)
if pred_caption not in captions:
captions.append(pred_caption)
for c in captions:
st.write(c)
except Exception as e:
st.error(f"An error occurred during prediction: {e}")
st.title('Image Captioner')
# Handle image URL input
img_url = st.text_input(label='Enter Image URL')
if img_url:
try:
img = Image.open(requests.get(img_url, stream=True).raw)
img = img.convert('RGB')
st.image(img)
img.save('tmp.jpg')
predict()
os.remove('tmp.jpg')
except Exception as e:
st.error(f"An error occurred with the image URL: {e}")
st.markdown('<center style="opacity: 70%">OR</center>', unsafe_allow_html=True)
# Handle image file upload
img_upload = st.file_uploader(label='Upload Image', type=['jpg', 'png', 'jpeg'])
if img_upload:
try:
img = Image.open(io.BytesIO(img_upload.read()))
img = img.convert('RGB')
img.save('tmp.jpg')
st.image(img)
predict()
os.remove('tmp.jpg')
except Exception as e:
st.error(f"An error occurred with the image upload: {e}")