Commit
·
ed8f8cb
1
Parent(s):
638a214
Add application file
Browse files
app.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import pickle as pkl
|
| 3 |
+
|
| 4 |
+
from tensorflow.keras.applications.vgg16 import VGG16, preprocess_input
|
| 5 |
+
from tensorflow.keras.models import Model
|
| 6 |
+
import tensorflow as tf
|
| 7 |
+
from tensorflow.keras.preprocessing.text import Tokenizer
|
| 8 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# Feature Extracting model
|
| 12 |
+
vgg_model = VGG16()
|
| 13 |
+
vgg_model.trainable = False
|
| 14 |
+
|
| 15 |
+
img_model = Model(inputs=vgg_model.input,
|
| 16 |
+
outputs=vgg_model.layers[-2].output)
|
| 17 |
+
|
| 18 |
+
# Caption genartion model
|
| 19 |
+
model = tf.keras.models.load_model('caption_genaration_model.h5')
|
| 20 |
+
|
| 21 |
+
# load Tokenizer
|
| 22 |
+
with open('tokenizer.pkl','rb') as f:
|
| 23 |
+
tokenizer = pkl.load(f)
|
| 24 |
+
|
| 25 |
+
# convert index to word from prediction
|
| 26 |
+
def index_to_word(word_idx):
|
| 27 |
+
return tokenizer.index_word[word_idx]
|
| 28 |
+
|
| 29 |
+
# Resize layer
|
| 30 |
+
resize_img = tf.keras.layers.Resizing(height=224, width=224)
|
| 31 |
+
|
| 32 |
+
# Preprocces input Image
|
| 33 |
+
def img_preprocces(img):
|
| 34 |
+
img = tf.expand_dims(img,axis=0)
|
| 35 |
+
resized_image = resize_img(img)
|
| 36 |
+
img = preprocess_input(resized_image)
|
| 37 |
+
feature = vgg_model.predict(img,verbose=False)
|
| 38 |
+
return feature
|
| 39 |
+
|
| 40 |
+
def genarate_caption(img):
|
| 41 |
+
seq_in = 'startseq'
|
| 42 |
+
feature_img = img_preprocces(img)
|
| 43 |
+
|
| 44 |
+
for _ in range(30):
|
| 45 |
+
# Tokenization & Padding
|
| 46 |
+
seq_in_sequence = tokenizer.texts_to_sequences([seq_in])[0]
|
| 47 |
+
seq_in_padded = pad_sequences([seq_in_sequence], padding='post',maxlen=30)
|
| 48 |
+
|
| 49 |
+
# Predict next word
|
| 50 |
+
y_hat = model.predict([feature_img,seq_in_padded],verbose=False)
|
| 51 |
+
word_index = y_hat.argmax(axis=1)
|
| 52 |
+
predicted_word = index_to_word(word_index[0])
|
| 53 |
+
if predicted_word == 'endseq':
|
| 54 |
+
break
|
| 55 |
+
seq_in = seq_in + ' ' + predicted_word
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
return seq_in[9:]
|
| 59 |
+
|
| 60 |
+
app = gr.Interface(
|
| 61 |
+
fn=genarate_caption,
|
| 62 |
+
inputs=['image'],
|
| 63 |
+
outputs=['text']
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
app.launch()
|