Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import tensorflow as tf
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pickle
|
| 6 |
+
|
| 7 |
+
# Load the pre-trained model
|
| 8 |
+
@st.cache(allow_output_mutation=True)
|
| 9 |
+
def load_model():
|
| 10 |
+
model = tf.keras.models.load_model('model.h5')
|
| 11 |
+
return model
|
| 12 |
+
|
| 13 |
+
# Load the tokenizer
|
| 14 |
+
@st.cache(allow_output_mutation=True)
|
| 15 |
+
def load_tokenizer():
|
| 16 |
+
with open('tokenizer.pkl', 'rb') as handle:
|
| 17 |
+
tokenizer = pickle.load(handle)
|
| 18 |
+
return tokenizer
|
| 19 |
+
|
| 20 |
+
model = load_model()
|
| 21 |
+
tokenizer = load_tokenizer()
|
| 22 |
+
|
| 23 |
+
# Function to preprocess the image
|
| 24 |
+
def preprocess_image(image):
|
| 25 |
+
image = image.resize((299, 299)) # Resize to the input size of the model
|
| 26 |
+
image = np.array(image) / 255.0 # Normalize
|
| 27 |
+
image = np.expand_dims(image, axis=0) # Add batch dimension
|
| 28 |
+
return image
|
| 29 |
+
|
| 30 |
+
# Function to generate caption
|
| 31 |
+
def generate_caption(image):
|
| 32 |
+
image = preprocess_image(image)
|
| 33 |
+
predictions = model.predict(image)
|
| 34 |
+
predicted_caption = tokenizer.sequences_to_texts(predictions.argmax(axis=-1))
|
| 35 |
+
return predicted_caption[0]
|
| 36 |
+
|
| 37 |
+
# Streamlit app
|
| 38 |
+
st.title("Image Captioning App")
|
| 39 |
+
st.write("Upload an image to generate a caption")
|
| 40 |
+
|
| 41 |
+
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "png", "jpeg"])
|
| 42 |
+
|
| 43 |
+
if uploaded_file is not None:
|
| 44 |
+
image = Image.open(uploaded_file)
|
| 45 |
+
st.image(image, caption='Uploaded Image.', use_column_width=True)
|
| 46 |
+
st.write("")
|
| 47 |
+
st.write("Generating caption...")
|
| 48 |
+
caption = generate_caption(image)
|
| 49 |
+
st.write(caption)
|