ayush-goud commited on
Commit
46df4fa
·
1 Parent(s): 06282d7

Upload 9 files

Browse files
Flickr8k.token.txt ADDED
The diff for this file is too large to render. See raw diff
 
Flickr_8k.trainImages.txt ADDED
The diff for this file is too large to render. See raw diff
 
README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Image Captioning Project
2
+
3
+ This project implements an end-to-end Image Captioning system using VGG16, CNN, and LSTM. It generates descriptive captions for input images by combining the power of convolutional neural networks (CNN) for image feature extraction and long short-term memory (LSTM) networks for language modeling.
4
+
5
+ ## Overview
6
+
7
+ The Image Captioning system follows the following steps:
8
+
9
+ 1. Preprocessing: The input images are preprocessed to extract features using the VGG16 model. These features serve as the visual representation of the images.
10
+
11
+ 2. Text Preprocessing: The captions associated with the images are preprocessed by tokenizing them into words and creating a vocabulary of unique words.
12
+
13
+ 3. Model Architecture: The architecture consists of a CNN for image feature extraction and an LSTM network for generating captions. The CNN encodes the image features, while the LSTM decodes the features to generate descriptive captions.
14
+
15
+ 4. Training: The model is trained using a dataset of images and corresponding captions. The image features are extracted using the pre-trained VGG16 model, and the captions are processed and fed into the LSTM network.
16
+
17
+ 5. Caption Generation: Given a new input image, the trained model generates captions by first extracting the image features using the CNN and then using the LSTM to generate a sequence of words based on the image features.
18
+
19
+ ## Dependencies
20
+
21
+ - Python 3.x
22
+ - TensorFlow
23
+ - Keras
24
+ - NumPy
25
+ - NLTK
26
+
27
+ ## Installation
28
+
29
+ 1. Clone the repository:
30
+
31
+ ### app link(not fitted perfectly due to limited resources so that there would be chances of wrong predictions
32
+ https://sunilgiri7-end-to-end-image-screening-project-streamlit-z7uirv.streamlit.app/
33
+
img_captioning_project.ipynb ADDED
@@ -0,0 +1,1224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "execution_count": 81,
6
+ "metadata": {
7
+ "id": "4xDkP0IKzLgW"
8
+ },
9
+ "outputs": [],
10
+ "source": [
11
+ "from os import listdir\n",
12
+ "from numpy import array\n",
13
+ "from keras.models import Model\n",
14
+ "from pickle import dump\n",
15
+ "from keras.applications.vgg16 import VGG16\n",
16
+ "from tensorflow.keras.preprocessing.image import load_img\n",
17
+ "from tensorflow.keras.preprocessing.image import img_to_array\n",
18
+ "from tensorflow.keras.preprocessing.sequence import pad_sequences\n",
19
+ "from keras.preprocessing.text import Tokenizer\n",
20
+ "from keras.utils import to_categorical\n",
21
+ "from keras.utils import plot_model\n",
22
+ "from keras.models import Model\n",
23
+ "from keras.layers import Input\n",
24
+ "from keras.layers import Dense\n",
25
+ "from keras.layers import LSTM\n",
26
+ "from keras.layers import Embedding\n",
27
+ "from keras.layers import Dropout\n",
28
+ "from tensorflow.keras.layers import Add\n",
29
+ "from keras.callbacks import ModelCheckpoint"
30
+ ]
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "source": [
35
+ "from keras.applications.vgg16 import VGG16, preprocess_input\n",
36
+ "model = VGG16()\n",
37
+ "# re-structure the model\n",
38
+ "model.layers.pop()\n",
39
+ "model = Model(inputs=model.inputs, outputs=model.layers[-2].output)\n",
40
+ "# summarize\n",
41
+ "print(model.summary())"
42
+ ],
43
+ "metadata": {
44
+ "colab": {
45
+ "base_uri": "https://localhost:8080/"
46
+ },
47
+ "id": "UuRJY0-d9yux",
48
+ "outputId": "22a58ba4-0f1f-473f-ca65-b7422a453f22"
49
+ },
50
+ "execution_count": 82,
51
+ "outputs": [
52
+ {
53
+ "output_type": "stream",
54
+ "name": "stdout",
55
+ "text": [
56
+ "Model: \"model_7\"\n",
57
+ "_________________________________________________________________\n",
58
+ " Layer (type) Output Shape Param # \n",
59
+ "=================================================================\n",
60
+ " input_8 (InputLayer) [(None, 224, 224, 3)] 0 \n",
61
+ " \n",
62
+ " block1_conv1 (Conv2D) (None, 224, 224, 64) 1792 \n",
63
+ " \n",
64
+ " block1_conv2 (Conv2D) (None, 224, 224, 64) 36928 \n",
65
+ " \n",
66
+ " block1_pool (MaxPooling2D) (None, 112, 112, 64) 0 \n",
67
+ " \n",
68
+ " block2_conv1 (Conv2D) (None, 112, 112, 128) 73856 \n",
69
+ " \n",
70
+ " block2_conv2 (Conv2D) (None, 112, 112, 128) 147584 \n",
71
+ " \n",
72
+ " block2_pool (MaxPooling2D) (None, 56, 56, 128) 0 \n",
73
+ " \n",
74
+ " block3_conv1 (Conv2D) (None, 56, 56, 256) 295168 \n",
75
+ " \n",
76
+ " block3_conv2 (Conv2D) (None, 56, 56, 256) 590080 \n",
77
+ " \n",
78
+ " block3_conv3 (Conv2D) (None, 56, 56, 256) 590080 \n",
79
+ " \n",
80
+ " block3_pool (MaxPooling2D) (None, 28, 28, 256) 0 \n",
81
+ " \n",
82
+ " block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160 \n",
83
+ " \n",
84
+ " block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808 \n",
85
+ " \n",
86
+ " block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808 \n",
87
+ " \n",
88
+ " block4_pool (MaxPooling2D) (None, 14, 14, 512) 0 \n",
89
+ " \n",
90
+ " block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808 \n",
91
+ " \n",
92
+ " block5_conv2 (Conv2D) (None, 14, 14, 512) 2359808 \n",
93
+ " \n",
94
+ " block5_conv3 (Conv2D) (None, 14, 14, 512) 2359808 \n",
95
+ " \n",
96
+ " block5_pool (MaxPooling2D) (None, 7, 7, 512) 0 \n",
97
+ " \n",
98
+ " flatten (Flatten) (None, 25088) 0 \n",
99
+ " \n",
100
+ " fc1 (Dense) (None, 4096) 102764544 \n",
101
+ " \n",
102
+ " fc2 (Dense) (None, 4096) 16781312 \n",
103
+ " \n",
104
+ "=================================================================\n",
105
+ "Total params: 134,260,544\n",
106
+ "Trainable params: 134,260,544\n",
107
+ "Non-trainable params: 0\n",
108
+ "_________________________________________________________________\n",
109
+ "None\n"
110
+ ]
111
+ }
112
+ ]
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "execution_count": 83,
117
+ "metadata": {
118
+ "id": "tR-lfP51bmp5"
119
+ },
120
+ "outputs": [],
121
+ "source": [
122
+ "from os import listdir\n",
123
+ "from pickle import dump\n",
124
+ "from tensorflow.keras.preprocessing.image import img_to_array, load_img\n",
125
+ "from keras.models import Model\n",
126
+ "\n",
127
+ "# extract feature from each photo in directory\n",
128
+ "def extract_features(directory):\n",
129
+ "\t# extract features from each photo\n",
130
+ "\tfeatures = dict()\n",
131
+ "\tfor name in listdir(directory):\n",
132
+ "\t\t# load an image from file\n",
133
+ "\t\tfilename = directory + '/' + name\n",
134
+ "\t\timage = load_img(filename, target_size=(224, 224))\n",
135
+ "\t\t# convert the image pixels to a numpy array\n",
136
+ "\t\timage = img_to_array(image)\n",
137
+ "\t\t# reshape data for the model\n",
138
+ "\t\timage = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\n",
139
+ "\t\t# prepare the image for the VGG model\n",
140
+ "\t\timage = preprocess_input(image)\n",
141
+ "\t\t# get features\n",
142
+ "\t\tfeature = model.predict(image, verbose=0)\n",
143
+ "\t\t# get image id\n",
144
+ "\t\timage_id = name.split('.')[0]\n",
145
+ "\t\t# store feature\n",
146
+ "\t\tfeatures[image_id] = feature\n",
147
+ "\t\tprint('>%s' % name)\n",
148
+ "\treturn features"
149
+ ]
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "execution_count": 84,
154
+ "metadata": {
155
+ "id": "nc7ks02Gjwgh"
156
+ },
157
+ "outputs": [],
158
+ "source": [
159
+ "# directory = \"/content/drive/MyDrive/Image_Captioning_Project/Images\"\n",
160
+ "# features = extract_features(directory)\n",
161
+ "# dump(features, open('features1.pkl', 'wb'))\n",
162
+ "# print(\"Extracted Features: %d\" %len(features))"
163
+ ]
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "source": [
168
+ "!ls"
169
+ ],
170
+ "metadata": {
171
+ "colab": {
172
+ "base_uri": "https://localhost:8080/"
173
+ },
174
+ "id": "9fp0SwYv0VK6",
175
+ "outputId": "4387bde5-1136-41b9-f03b-52404d2ee015"
176
+ },
177
+ "execution_count": 85,
178
+ "outputs": [
179
+ {
180
+ "output_type": "stream",
181
+ "name": "stdout",
182
+ "text": [
183
+ "drive sample_data\n"
184
+ ]
185
+ }
186
+ ]
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "execution_count": 86,
191
+ "metadata": {
192
+ "id": "-nIfYC9Yj7-b"
193
+ },
194
+ "outputs": [],
195
+ "source": [
196
+ "import string\n",
197
+ "from nltk.tokenize import word_tokenize\n",
198
+ "\n",
199
+ "def load_doc(filename):\n",
200
+ " # open the file as read only\n",
201
+ " file = open(filename, 'r')\n",
202
+ " # read all text\n",
203
+ " text = file.read()\n",
204
+ " # close the file\n",
205
+ " file.close()\n",
206
+ " return text"
207
+ ]
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "execution_count": 87,
212
+ "metadata": {
213
+ "id": "n9FUCV49RnnS"
214
+ },
215
+ "outputs": [],
216
+ "source": [
217
+ "def load_descriptions(doc):\n",
218
+ "\tmapping = dict()\n",
219
+ "\t# process lines\n",
220
+ "\tfor line in doc.split('\\n'):\n",
221
+ "\t\t# split line by white space\n",
222
+ "\t\ttokens = line.split()\n",
223
+ "\t\tif len(line) < 2:\n",
224
+ "\t\t\tcontinue\n",
225
+ "\t\t# take the first token as the image id, the rest as the description\n",
226
+ "\t\timage_id, image_desc = tokens[0], tokens[1:]\n",
227
+ "\t\t# remove filename from image id\n",
228
+ "\t\timage_id = image_id.split('.')[0]\n",
229
+ "\t\t# convert description tokens back to string\n",
230
+ "\t\timage_desc = ' '.join(image_desc)\n",
231
+ "\t\t# create the list if needed\n",
232
+ "\t\tif image_id not in mapping:\n",
233
+ "\t\t\tmapping[image_id] = list()\n",
234
+ "\t\t# store description\n",
235
+ "\t\tmapping[image_id].append(image_desc)\n",
236
+ "\treturn mapping"
237
+ ]
238
+ },
239
+ {
240
+ "cell_type": "markdown",
241
+ "source": [
242
+ "## Preprocessing of Text\n",
243
+ "\n",
244
+ "1. Convert all words to lowercase.\n",
245
+ "2. Remove all punctuation.\n",
246
+ "3. Remove all words that are one character or less in length (e.g. ‘a’).\n",
247
+ "4. Remove all words with numbers in them."
248
+ ],
249
+ "metadata": {
250
+ "id": "l31beBIf2E3h"
251
+ }
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "execution_count": 88,
256
+ "metadata": {
257
+ "id": "e6Dd0Ugej8sf"
258
+ },
259
+ "outputs": [],
260
+ "source": [
261
+ "def clean_descriptions(descriptions):\n",
262
+ " # prepare translation table for removing punctuation\n",
263
+ " table = str.maketrans('', '', string.punctuation)\n",
264
+ " for key, desc_list in descriptions.items():\n",
265
+ " for i in range(len(desc_list)):\n",
266
+ " desc = desc_list[i]\n",
267
+ " # tokenize\n",
268
+ " desc = desc.split()\n",
269
+ " # convert to lower case\n",
270
+ " desc = [word.lower() for word in desc]\n",
271
+ " # remove punctuation from each token\n",
272
+ " desc = [w.translate(table) for w in desc]\n",
273
+ " # remove hanging 's' and 'a'\n",
274
+ " desc = [word for word in desc if len(word)>1]\n",
275
+ " # remove tokens with numbers in them\n",
276
+ " desc = [word for word in desc if word.isalpha()]\n",
277
+ " # store as string\n",
278
+ " desc_list[i] = ' '.join(desc)\n",
279
+ "def to_vocabulary(descriptions):\n",
280
+ " # build a list of all description strings\n",
281
+ " all_desc = set()\n",
282
+ " for key in descriptions.keys():\n",
283
+ " [all_desc.update(d.split()) for d in descriptions[key]]\n",
284
+ " return all_desc"
285
+ ]
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "execution_count": 89,
290
+ "metadata": {
291
+ "id": "o7lzD3qgkCDs"
292
+ },
293
+ "outputs": [],
294
+ "source": [
295
+ "def save_descriptions(descriptions, filename):\n",
296
+ " lines = list()\n",
297
+ " for key, desc_list in descriptions.items():\n",
298
+ " for desc in desc_list:\n",
299
+ " lines.append(key + \" \" + desc)\n",
300
+ " data = '\\n'.join(lines)\n",
301
+ " file = open(filename, 'w')\n",
302
+ " file.write(data)\n",
303
+ " file.close()"
304
+ ]
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "execution_count": 90,
309
+ "metadata": {
310
+ "colab": {
311
+ "base_uri": "https://localhost:8080/"
312
+ },
313
+ "id": "_kjcu6Ug3Lqc",
314
+ "outputId": "4139ef68-a4a0-43f4-f86f-01f52cf73138"
315
+ },
316
+ "outputs": [
317
+ {
318
+ "output_type": "stream",
319
+ "name": "stderr",
320
+ "text": [
321
+ "[nltk_data] Downloading package punkt to /root/nltk_data...\n",
322
+ "[nltk_data] Package punkt is already up-to-date!\n"
323
+ ]
324
+ },
325
+ {
326
+ "output_type": "execute_result",
327
+ "data": {
328
+ "text/plain": [
329
+ "True"
330
+ ]
331
+ },
332
+ "metadata": {},
333
+ "execution_count": 90
334
+ }
335
+ ],
336
+ "source": [
337
+ "import nltk\n",
338
+ "nltk.download('punkt')"
339
+ ]
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "execution_count": 91,
344
+ "metadata": {
345
+ "colab": {
346
+ "base_uri": "https://localhost:8080/"
347
+ },
348
+ "id": "RancEv97kENF",
349
+ "outputId": "8d8214e4-fe45-4e25-a602-74c143971471"
350
+ },
351
+ "outputs": [
352
+ {
353
+ "output_type": "stream",
354
+ "name": "stdout",
355
+ "text": [
356
+ "Loaded: 8092\n"
357
+ ]
358
+ }
359
+ ],
360
+ "source": [
361
+ "filename = \"/content/drive/MyDrive/Image_Captioning_Project/Flickr8k.token.txt\"\n",
362
+ "doc = load_doc(filename)\n",
363
+ "descriptions = load_descriptions(doc)\n",
364
+ "print(\"Loaded: %d\" %len(descriptions))"
365
+ ]
366
+ },
367
+ {
368
+ "cell_type": "code",
369
+ "execution_count": 92,
370
+ "metadata": {
371
+ "colab": {
372
+ "base_uri": "https://localhost:8080/"
373
+ },
374
+ "id": "BD4eqsEukFqE",
375
+ "outputId": "e9e98894-99c3-4ca4-d9bd-94fc4ba22e0e"
376
+ },
377
+ "outputs": [
378
+ {
379
+ "output_type": "stream",
380
+ "name": "stdout",
381
+ "text": [
382
+ "Vocab size: 8763\n"
383
+ ]
384
+ }
385
+ ],
386
+ "source": [
387
+ "#clean desc\n",
388
+ "clean_descriptions(descriptions)\n",
389
+ "vocab = to_vocabulary(descriptions)\n",
390
+ "print(\"Vocab size: %d\" %len(vocab))"
391
+ ]
392
+ },
393
+ {
394
+ "cell_type": "code",
395
+ "execution_count": 93,
396
+ "metadata": {
397
+ "id": "rVZ9RHhbkGIo"
398
+ },
399
+ "outputs": [],
400
+ "source": [
401
+ "# save_descriptions(descriptions, \"descriptions2.txt\")"
402
+ ]
403
+ },
404
+ {
405
+ "cell_type": "markdown",
406
+ "source": [
407
+ "### Developing Deep Learning Model\n",
408
+ "\n",
409
+ "#### This section is divided into the following parts:\n",
410
+ "\n",
411
+ "Loading Data.\n",
412
+ "Defining the Model.\n",
413
+ "Fitting the Model."
414
+ ],
415
+ "metadata": {
416
+ "id": "PnV7xrpPCPrs"
417
+ }
418
+ },
419
+ {
420
+ "cell_type": "code",
421
+ "execution_count": 94,
422
+ "metadata": {
423
+ "id": "dZ8tvUjckG1F"
424
+ },
425
+ "outputs": [],
426
+ "source": [
427
+ "from pickle import dump\n",
428
+ "\n",
429
+ "#load into memory\n",
430
+ "def load_doc(filename):\n",
431
+ "\t# open the file as read only\n",
432
+ "\tfile = open(filename, 'r')\n",
433
+ "\t# read all text\n",
434
+ "\ttext = file.read()\n",
435
+ "\t# close the file\n",
436
+ "\tfile.close()\n",
437
+ "\treturn text\n",
438
+ "\n",
439
+ "#pre-defined list of photo identifier\n",
440
+ "def load_set(filename):\n",
441
+ " doc = load_doc(filename)\n",
442
+ " dataset = list()\n",
443
+ " for line in doc.split(\"\\n\"):\n",
444
+ " if len(line) < 1:\n",
445
+ " continue\n",
446
+ " identifier = line.split('.')[0]\n",
447
+ " dataset.append(identifier)\n",
448
+ " return set(dataset)"
449
+ ]
450
+ },
451
+ {
452
+ "cell_type": "markdown",
453
+ "source": [
454
+ "load_clean_descriptions() that loads the cleaned text descriptions from ‘descriptions.txt‘ for a given set of identifiers and returns a dictionary of identifiers to lists of text descriptions.\n",
455
+ "\n",
456
+ "The model we will develop will generate a caption given a photo, and the caption will be generated one word at a time. The sequence of previously generated words will be provided as input. Therefore, we will need a ‘first word’ to kick-off the generation process and a ‘last word‘ to signal the end of the caption.\n",
457
+ "\n",
458
+ "We will use the strings ‘startseq‘ and ‘endseq‘ for this purpose."
459
+ ],
460
+ "metadata": {
461
+ "id": "NxRnPZr4CZh4"
462
+ }
463
+ },
464
+ {
465
+ "cell_type": "code",
466
+ "execution_count": 95,
467
+ "metadata": {
468
+ "id": "9hF4PUCskHF_"
469
+ },
470
+ "outputs": [],
471
+ "source": [
472
+ "def load_photo_features(features, dataset):\n",
473
+ " all_features = load(open(features, 'rb'))\n",
474
+ " features = {k: all_features[k] for k in dataset}\n",
475
+ " return features"
476
+ ]
477
+ },
478
+ {
479
+ "cell_type": "code",
480
+ "execution_count": 96,
481
+ "metadata": {
482
+ "id": "kPQVXbKqSp6m"
483
+ },
484
+ "outputs": [],
485
+ "source": [
486
+ "def load_clean_descriptions(filename, dataset):\n",
487
+ "\t# load document\n",
488
+ "\tdoc = load_doc(filename)\n",
489
+ "\tdescriptions = dict()\n",
490
+ "\tfor line in doc.split('\\n'):\n",
491
+ "\t\t# split line by white space\n",
492
+ "\t\ttokens = line.split()\n",
493
+ "\t\t# split id from description\n",
494
+ "\t\timage_id, image_desc = tokens[0], tokens[1:]\n",
495
+ "\t\t# skip images not in the set\n",
496
+ "\t\tif image_id in dataset:\n",
497
+ "\t\t\t# create list\n",
498
+ "\t\t\tif image_id not in descriptions:\n",
499
+ "\t\t\t\tdescriptions[image_id] = list()\n",
500
+ "\t\t\t# wrap description in tokens\n",
501
+ "\t\t\tdesc = 'startseq ' + ' '.join(image_desc) + ' endseq'\n",
502
+ "\t\t\t# store\n",
503
+ "\t\t\tdescriptions[image_id].append(desc)\n",
504
+ "\treturn descriptions"
505
+ ]
506
+ },
507
+ {
508
+ "cell_type": "code",
509
+ "source": [
510
+ "from pickle import load\n",
511
+ "\n",
512
+ "# load training dataset (6K)\n",
513
+ "filename = '/content/drive/MyDrive/Image_Captioning_Project/Flickr_8k.trainImages.txt'\n",
514
+ "train = load_set(filename)\n",
515
+ "print('Dataset: %d' % len(train))\n",
516
+ "# descriptions\n",
517
+ "train_descriptions = load_clean_descriptions('/content/drive/MyDrive/Image_Captioning_Project/descriptions1.txt', train)\n",
518
+ "print('Descriptions: train=%d' % len(train_descriptions))\n",
519
+ "# photo features\n",
520
+ "train_features = load_photo_features('/content/drive/MyDrive/Image_Captioning_Project/features.pkl', train)\n",
521
+ "print('Photos: train=%d' % len(train_features))"
522
+ ],
523
+ "metadata": {
524
+ "colab": {
525
+ "base_uri": "https://localhost:8080/"
526
+ },
527
+ "id": "M8Y0VIWrxRdr",
528
+ "outputId": "baef9b0d-885f-4ba6-b792-4d9b0ffcb52b"
529
+ },
530
+ "execution_count": 97,
531
+ "outputs": [
532
+ {
533
+ "output_type": "stream",
534
+ "name": "stdout",
535
+ "text": [
536
+ "Dataset: 6000\n",
537
+ "Descriptions: train=6000\n",
538
+ "Photos: train=6000\n"
539
+ ]
540
+ }
541
+ ]
542
+ },
543
+ {
544
+ "cell_type": "code",
545
+ "execution_count": 98,
546
+ "metadata": {
547
+ "id": "CxCpUVLlZ1M6"
548
+ },
549
+ "outputs": [],
550
+ "source": [
551
+ "def load_doc(filename):\n",
552
+ "\t# open the file as read only\n",
553
+ "\tfile = open(filename, 'r')\n",
554
+ "\t# read all text\n",
555
+ "\ttext = file.read()\n",
556
+ "\t# close the file\n",
557
+ "\tfile.close\n",
558
+ "\treturn text"
559
+ ]
560
+ },
561
+ {
562
+ "cell_type": "code",
563
+ "execution_count": 99,
564
+ "metadata": {
565
+ "id": "pqOcDdqUTHDW"
566
+ },
567
+ "outputs": [],
568
+ "source": [
569
+ "def load_set(filename):\n",
570
+ " doc = load_doc(filename)\n",
571
+ " dataset = list()\n",
572
+ " for line in doc.split(\"\\n\"):\n",
573
+ " if len(line) < 1:\n",
574
+ " continue\n",
575
+ " identifier = line.split('.')[0]\n",
576
+ " dataset.append(identifier)\n",
577
+ " return set(dataset)"
578
+ ]
579
+ },
580
+ {
581
+ "cell_type": "code",
582
+ "execution_count": 100,
583
+ "metadata": {
584
+ "id": "_l3IMXzPZ7mN"
585
+ },
586
+ "outputs": [],
587
+ "source": [
588
+ "def load_clean_descriptions(filename, dataset):\n",
589
+ "\t# load document\n",
590
+ "\tdoc = load_doc(filename)\n",
591
+ "\tdescriptions = dict()\n",
592
+ "\tfor line in doc.split('\\n'):\n",
593
+ "\t\t# split line by white space\n",
594
+ "\t\ttokens = line.split()\n",
595
+ "\t\t# split id from description\n",
596
+ "\t\timage_id, image_desc = tokens[0], tokens[1:]\n",
597
+ "\t\t# skip images not in the set\n",
598
+ "\t\tif image_id in dataset:\n",
599
+ "\t\t\t# create list\n",
600
+ "\t\t\tif image_id not in descriptions:\n",
601
+ "\t\t\t\tdescriptions[image_id] = list()\n",
602
+ "\t\t\t# wrap description in tokens\n",
603
+ "\t\t\tdesc = 'startseq ' + ' '.join(image_desc) + ' endseq'\n",
604
+ "\t\t\t# store\n",
605
+ "\t\t\tdescriptions[image_id].append(desc)\n",
606
+ "\treturn descriptions "
607
+ ]
608
+ },
609
+ {
610
+ "cell_type": "code",
611
+ "execution_count": 101,
612
+ "metadata": {
613
+ "id": "Cf_rfRQpTtu_"
614
+ },
615
+ "outputs": [],
616
+ "source": [
617
+ "def load_photo_features(filename, dataset):\n",
618
+ "\t# load all features\n",
619
+ "\tall_features = load(open(filename, 'rb'))\n",
620
+ "\t# filter features\n",
621
+ "\tfeatures = {k: all_features[k] for k in dataset}\n",
622
+ "\treturn features"
623
+ ]
624
+ },
625
+ {
626
+ "cell_type": "code",
627
+ "execution_count": 102,
628
+ "metadata": {
629
+ "id": "0HHS8lQFkHR-"
630
+ },
631
+ "outputs": [],
632
+ "source": [
633
+ "# dict to clean list\n",
634
+ "def to_lines(descriptions):\n",
635
+ " all_desc = list()\n",
636
+ " for key in descriptions.keys():\n",
637
+ " [all_desc.append(d) for d in descriptions[key]]\n",
638
+ " return all_desc\n",
639
+ "\n",
640
+ "def create_tokenizer(descriptions):\n",
641
+ " lines = to_lines(descriptions)\n",
642
+ " tokenizer = Tokenizer()\n",
643
+ " tokenizer.fit_on_texts(lines)\n",
644
+ " return tokenizer"
645
+ ]
646
+ },
647
+ {
648
+ "cell_type": "code",
649
+ "execution_count": 103,
650
+ "metadata": {
651
+ "id": "FjSt5rpvkXk3"
652
+ },
653
+ "outputs": [],
654
+ "source": [
655
+ "#len of description\n",
656
+ "def max_length(description):\n",
657
+ " lines = to_lines(description)\n",
658
+ " return max(len(d.split()) for d in lines)"
659
+ ]
660
+ },
661
+ {
662
+ "cell_type": "code",
663
+ "execution_count": 104,
664
+ "metadata": {
665
+ "id": "cNko1BPwkX21"
666
+ },
667
+ "outputs": [],
668
+ "source": [
669
+ "# create input and output sequence\n",
670
+ "def create_sequences(tokenizer, max_length, desc_list, photo):\n",
671
+ " X1, X2, y = list(), list(), list()\n",
672
+ " # walk through each description for the image\n",
673
+ " for desc in desc_list:\n",
674
+ " # encode the sequence\n",
675
+ " seq = tokenizer.texts_to_sequences([desc])[0]\n",
676
+ " # split one sequence into multiple X,y pairs\n",
677
+ " for i in range(1, len(seq)):\n",
678
+ " # split into input and output pair\n",
679
+ " in_seq, out_seq = seq[:i], seq[i]\n",
680
+ " # pad input sequence\n",
681
+ " in_seq = pad_sequences([in_seq], maxlen=max_length)[0]\n",
682
+ " # encode output sequence\n",
683
+ " out_seq = to_categorical([out_seq], num_classes=vocab_size)[0]\n",
684
+ " # store\n",
685
+ " X1.append(photo)\n",
686
+ " X2.append(in_seq)\n",
687
+ " y.append(out_seq)\n",
688
+ " return array(X1), array(X2), array(y)"
689
+ ]
690
+ },
691
+ {
692
+ "cell_type": "markdown",
693
+ "metadata": {
694
+ "id": "q5LhU8zQkdqu"
695
+ },
696
+ "source": [
697
+ "## Model building"
698
+ ]
699
+ },
700
+ {
701
+ "cell_type": "code",
702
+ "execution_count": 105,
703
+ "metadata": {
704
+ "id": "zT7KqC6bkYEj"
705
+ },
706
+ "outputs": [],
707
+ "source": [
708
+ "from tensorflow.keras.layers import add\n",
709
+ "def define_model(vocab_size, max_length):\n",
710
+ " # feature extractor model\n",
711
+ " inputs1 = Input(shape=(1000,))\n",
712
+ " fe1 = Dropout(0.5)(inputs1)\n",
713
+ " fe2 = Dense(256, activation='relu')(fe1)\n",
714
+ " # sequence model\n",
715
+ " inputs2 = Input(shape=(max_length,))\n",
716
+ " se1 = Embedding(vocab_size,output_dim=256, mask_zero=True)(inputs2)\n",
717
+ " se2 = Dropout(0.5)(se1)\n",
718
+ " se3 = LSTM(256)(se2)\n",
719
+ " # decoder model\n",
720
+ " decoder1 = add([fe2, se3])\n",
721
+ " decoder2 = Dense(256, activation='relu')(decoder1)\n",
722
+ " outputs = Dense(vocab_size, activation='softmax')(decoder2)\n",
723
+ " # tie it together [image, seq] [word]\n",
724
+ " model = Model(inputs=[inputs1, inputs2], outputs=outputs)\n",
725
+ " model.compile(loss='categorical_crossentropy', optimizer='adam')\n",
726
+ " # summarize model\n",
727
+ " print(model.summary())\n",
728
+ " return model"
729
+ ]
730
+ },
731
+ {
732
+ "cell_type": "code",
733
+ "execution_count": 106,
734
+ "metadata": {
735
+ "id": "fR-dFhrYkYJv"
736
+ },
737
+ "outputs": [],
738
+ "source": [
739
+ "# load batch of data\n",
740
+ "def data_generator(descriptions, photos, tokenizer, max_length):\n",
741
+ " # loop for ever over images\n",
742
+ " while 1:\n",
743
+ " for key, desc_list in descriptions.items():\n",
744
+ " # retrieve the photo feature\n",
745
+ " photo = photos[key][0]\n",
746
+ " in_img, in_seq, out_word = create_sequences(tokenizer, max_length, desc_list, photo)\n",
747
+ " yield [[in_img, in_seq], out_word]"
748
+ ]
749
+ },
750
+ {
751
+ "cell_type": "code",
752
+ "execution_count": 107,
753
+ "metadata": {
754
+ "colab": {
755
+ "base_uri": "https://localhost:8080/"
756
+ },
757
+ "id": "eJ6n7_dEkkis",
758
+ "outputId": "4f0e3daa-18c7-4797-a7a6-5d193b02cf04"
759
+ },
760
+ "outputs": [
761
+ {
762
+ "output_type": "stream",
763
+ "name": "stdout",
764
+ "text": [
765
+ "Dataset: 6000\n",
766
+ "train_descriptions= 6000\n",
767
+ "photos: train= 6000\n",
768
+ "Vocab size: 7579\n",
769
+ "Description Length: 34\n"
770
+ ]
771
+ }
772
+ ],
773
+ "source": [
774
+ "#load train dataset\n",
775
+ "import tensorflow as tf\n",
776
+ "filename = \"/content/drive/MyDrive/Image_Captioning_Project/Flickr_8k.trainImages.txt\"\n",
777
+ "train = load_set(filename)\n",
778
+ "print(\"Dataset: %d\" %len(train))\n",
779
+ "\n",
780
+ "train_descriptions = load_clean_descriptions(\"/content/drive/MyDrive/Image_Captioning_Project/descriptions1.txt\", train)\n",
781
+ "print(\"train_descriptions= %d\" %len(train_descriptions))\n",
782
+ "\n",
783
+ "train_feature = load_photo_features(\"/content/drive/MyDrive/Image_Captioning_Project/features.pkl\", train)\n",
784
+ "print(\"photos: train= %d\" %len(train_feature))\n",
785
+ "\n",
786
+ "tokenizer = create_tokenizer(train_descriptions)\n",
787
+ "vocab_size = len(tokenizer.word_index)+1\n",
788
+ "print(\"Vocab size: %d\" %vocab_size)\n",
789
+ "\n",
790
+ "max_length = max_length(train_descriptions)\n",
791
+ "print('Description Length: %d' % max_length)"
792
+ ]
793
+ },
794
+ {
795
+ "cell_type": "code",
796
+ "execution_count": 108,
797
+ "metadata": {
798
+ "id": "yUnKHod1BIup"
799
+ },
800
+ "outputs": [],
801
+ "source": [
802
+ "import pickle\n",
803
+ "\n",
804
+ "# Dump the tokenizer using pickle\n",
805
+ "with open('tokenizer1.pkl', 'wb') as f:\n",
806
+ " pickle.dump(tokenizer, f)"
807
+ ]
808
+ },
809
+ {
810
+ "cell_type": "code",
811
+ "execution_count": 109,
812
+ "metadata": {
813
+ "id": "-x7HX3aLkk2x"
814
+ },
815
+ "outputs": [],
816
+ "source": [
817
+ "#train model\n",
818
+ "# model = define_model(vocab_size, max_length)\n",
819
+ "# filename = \"/content/drive/MyDrive/Image_Captioning_Project/model_18.h5\"\n",
820
+ "# model = load_model(filename)\n",
821
+ "# epochs = 4\n",
822
+ "# steps = len(train_descriptions)\n",
823
+ "# model.summary()"
824
+ ]
825
+ },
826
+ {
827
+ "cell_type": "code",
828
+ "execution_count": 110,
829
+ "metadata": {
830
+ "id": "JyBqM_6ikk8Y"
831
+ },
832
+ "outputs": [],
833
+ "source": [
834
+ "# for i in range(epochs):\n",
835
+ "# #create data generator\n",
836
+ "# generator = data_generator(train_descriptions, train_feature, tokenizer, max_len)\n",
837
+ "# model.fit(generator, epochs=1, steps_per_epoch = steps, verbose=1)\n",
838
+ "# model.save(\"model_\" + str(i) + \".h5\")"
839
+ ]
840
+ },
841
+ {
842
+ "cell_type": "code",
843
+ "execution_count": 111,
844
+ "metadata": {
845
+ "id": "U4-B7smiaqCH"
846
+ },
847
+ "outputs": [],
848
+ "source": [
849
+ "def load_doc(filename):\n",
850
+ "\t# open the file as read only\n",
851
+ "\tfile = open(filename, 'r')\n",
852
+ "\t# read all text\n",
853
+ "\ttext = file.read()\n",
854
+ "\t# close the file\n",
855
+ "\tfile.close()\n",
856
+ "\treturn text\n",
857
+ "\n",
858
+ "# load a pre-defined list of photo identifiers\n",
859
+ "def load_set(filename):\n",
860
+ "\tdoc = load_doc(filename)\n",
861
+ "\tdataset = list()\n",
862
+ "\t# process line by line\n",
863
+ "\tfor line in doc.split('\\n'):\n",
864
+ "\t\t# skip empty lines\n",
865
+ "\t\tif len(line) < 1:\n",
866
+ "\t\t\tcontinue\n",
867
+ "\t\t# get the image identifier\n",
868
+ "\t\tidentifier = line.split('.')[0]\n",
869
+ "\t\tdataset.append(identifier)\n",
870
+ "\treturn set(dataset)"
871
+ ]
872
+ },
873
+ {
874
+ "cell_type": "code",
875
+ "execution_count": 112,
876
+ "metadata": {
877
+ "id": "y42JWG04a1e2"
878
+ },
879
+ "outputs": [],
880
+ "source": [
881
+ "def load_photo_features(filename, dataset):\n",
882
+ "\t# load all features\n",
883
+ "\tall_features = load(open(filename, 'rb'))\n",
884
+ "\t# filter features\n",
885
+ "\tfeatures = {k: all_features[k] for k in dataset}\n",
886
+ "\treturn features\n",
887
+ "\n",
888
+ "# covert a dictionary of clean descriptions to a list of descriptions\n",
889
+ "def to_lines(descriptions):\n",
890
+ "\tall_desc = list()\n",
891
+ "\tfor key in descriptions.keys():\n",
892
+ "\t\t[all_desc.append(d) for d in descriptions[key]]\n",
893
+ "\treturn all_desc\n",
894
+ "\n",
895
+ "# fit a tokenizer given caption descriptions\n",
896
+ "def create_tokenizer(descriptions):\n",
897
+ "\tlines = to_lines(descriptions)\n",
898
+ "\ttokenizer = Tokenizer()\n",
899
+ "\ttokenizer.fit_on_texts(lines)\n",
900
+ "\treturn tokenizer\n",
901
+ "\n",
902
+ "# calculate the length of the description with the most words\n",
903
+ "def max_length(descriptions):\n",
904
+ "\tlines = to_lines(descriptions)\n",
905
+ "\treturn max(len(d.split()) for d in lines)\n",
906
+ "\n",
907
+ "# map an integer to a word\n",
908
+ "def word_for_id(integer, tokenizer):\n",
909
+ "\tfor word, index in tokenizer.word_index.items():\n",
910
+ "\t\tif index == integer:\n",
911
+ "\t\t\treturn word\n",
912
+ "\treturn None "
913
+ ]
914
+ },
915
+ {
916
+ "cell_type": "code",
917
+ "source": [
918
+ "from tensorflow.keras.preprocessing.sequence import pad_sequences\n",
919
+ "import numpy as np\n",
920
+ "def generate_desc(model, tokenizer, photo, max_length):\n",
921
+ "\t# seed the generation process\n",
922
+ "\tin_text = 'startseq'\n",
923
+ "\t# iterate over the whole length of the sequence\n",
924
+ "\tfor i in range(max_length):\n",
925
+ "\t\t# integer encode input sequence\n",
926
+ "\t\tsequence = tokenizer.texts_to_sequences([in_text])[0]\n",
927
+ "\t\t# pad input\n",
928
+ "\t\tsequence = pad_sequences([sequence], maxlen=max_length)\n",
929
+ "\t\t# predict next word\n",
930
+ "\t\tyhat = model.predict([photo,sequence], verbose=0)\n",
931
+ "\t\t# convert probability to integer\n",
932
+ "\t\tyhat = np.argmax(yhat)\n",
933
+ "\t\t# map integer to word\n",
934
+ "\t\tword = word_for_id(yhat, tokenizer)\n",
935
+ "\t\t# stop if we cannot map the word\n",
936
+ "\t\tif word is None:\n",
937
+ "\t\t\tbreak\n",
938
+ "\t\t# append as input for generating the next word\n",
939
+ "\t\tin_text += ' ' + word\n",
940
+ "\t\t# stop if we predict the end of the sequence\n",
941
+ "\t\tif word == 'endseq':\n",
942
+ "\t\t\tbreak\n",
943
+ "\treturn in_text"
944
+ ],
945
+ "metadata": {
946
+ "id": "Needd4uQm2gZ"
947
+ },
948
+ "execution_count": 113,
949
+ "outputs": []
950
+ },
951
+ {
952
+ "cell_type": "code",
953
+ "execution_count": 114,
954
+ "metadata": {
955
+ "id": "PrCXWKP8E1pt"
956
+ },
957
+ "outputs": [],
958
+ "source": [
959
+ "# evaluated the skill of model\n",
960
+ "from nltk.translate.bleu_score import corpus_bleu\n",
961
+ "def evaluate_model(model, descriptions, photos, tokenizer, max_length):\n",
962
+ "\tactual, predicted = list(), list()\n",
963
+ "\t# step over the whole set\n",
964
+ "\tfor key, desc_list in descriptions.items():\n",
965
+ "\t\t# generate description\n",
966
+ "\t\tyhat = generate_desc(model, tokenizer, photos[key], max_length)\n",
967
+ "\t\t# store actual and predicted\n",
968
+ "\t\treferences = [d.split() for d in desc_list]\n",
969
+ "\t\tactual.append(references)\n",
970
+ "\t\tpredicted.append(yhat.split())\n",
971
+ "\t# calculate BLEU score\n",
972
+ "\tprint('BLEU-1: %f' % corpus_bleu(actual, predicted, weights=(1.0, 0, 0, 0)))\n",
973
+ "\tprint('BLEU-2: %f' % corpus_bleu(actual, predicted, weights=(0.5, 0.5, 0, 0)))\n",
974
+ "\tprint('BLEU-3: %f' % corpus_bleu(actual, predicted, weights=(0.3, 0.3, 0.3, 0)))\n",
975
+ "\tprint('BLEU-4: %f' % corpus_bleu(actual, predicted, weights=(0.25, 0.25, 0.25, 0.25)))"
976
+ ]
977
+ },
978
+ {
979
+ "cell_type": "code",
980
+ "execution_count": 115,
981
+ "metadata": {
982
+ "colab": {
983
+ "base_uri": "https://localhost:8080/"
984
+ },
985
+ "id": "PwYhBAiYbOFN",
986
+ "outputId": "a253af6f-79d6-408b-ade8-ebbe4f8d2426"
987
+ },
988
+ "outputs": [
989
+ {
990
+ "output_type": "stream",
991
+ "name": "stdout",
992
+ "text": [
993
+ "Dataset: 6000\n",
994
+ "train_descriptions= 6000\n",
995
+ "photos: train= 6000\n",
996
+ "Vocab size: 7268\n",
997
+ "Description Length: 33\n"
998
+ ]
999
+ }
1000
+ ],
1001
+ "source": [
1002
+ "#load train dataset\n",
1003
+ "import tensorflow as tf\n",
1004
+ "filename = \"/content/drive/MyDrive/Image_Captioning_Project/Flickr_8k.trainImages.txt\"\n",
1005
+ "train = load_set(filename)\n",
1006
+ "print(\"Dataset: %d\" %len(train))\n",
1007
+ "\n",
1008
+ "train_descriptions = load_clean_descriptions(\"/content/drive/MyDrive/Image_Captioning_Project/descriptions.txt\", train)\n",
1009
+ "print(\"train_descriptions= %d\" %len(train_descriptions))\n",
1010
+ "\n",
1011
+ "train_feature = load_photo_features(\"/content/drive/MyDrive/Image_Captioning_Project/features.pkl\", train)\n",
1012
+ "print(\"photos: train= %d\" %len(train_feature))\n",
1013
+ "\n",
1014
+ "tokenizer = create_tokenizer(train_descriptions)\n",
1015
+ "vocab_size = len(tokenizer.word_index)+1\n",
1016
+ "print(\"Vocab size: %d\" %vocab_size)\n",
1017
+ "\n",
1018
+ "max_length = max_length(train_descriptions)\n",
1019
+ "print('Description Length: %d' % max_length)"
1020
+ ]
1021
+ },
1022
+ {
1023
+ "cell_type": "code",
1024
+ "execution_count": 116,
1025
+ "metadata": {
1026
+ "colab": {
1027
+ "base_uri": "https://localhost:8080/"
1028
+ },
1029
+ "id": "S9p7vYFZ7Y_J",
1030
+ "outputId": "48124f24-c348-4cd7-a8bb-6e30e7c26060"
1031
+ },
1032
+ "outputs": [
1033
+ {
1034
+ "output_type": "stream",
1035
+ "name": "stdout",
1036
+ "text": [
1037
+ "Dataset: 1000\n",
1038
+ "Description= 1000\n",
1039
+ "photos: test=1000"
1040
+ ]
1041
+ },
1042
+ {
1043
+ "output_type": "stream",
1044
+ "name": "stderr",
1045
+ "text": [
1046
+ "WARNING:tensorflow:Layer lstm_1 will not use cuDNN kernels since it doesn't meet the criteria. It will use a generic GPU kernel as fallback when running on GPU.\n"
1047
+ ]
1048
+ },
1049
+ {
1050
+ "output_type": "stream",
1051
+ "name": "stdout",
1052
+ "text": [
1053
+ "\n"
1054
+ ]
1055
+ }
1056
+ ],
1057
+ "source": [
1058
+ "filename = \"/content/drive/MyDrive/Image_Captioning_Project/Flickr_8k.testImages.txt\"\n",
1059
+ "test = load_set(filename)\n",
1060
+ "print(\"Dataset: %d\" %len(test))\n",
1061
+ "test_description = load_clean_descriptions(\"/content/drive/MyDrive/Image_Captioning_Project/descriptions.txt\", test)\n",
1062
+ "print(\"Description= %d\" %len(test_description))\n",
1063
+ "test_features = load_photo_features(\"/content/drive/MyDrive/Image_Captioning_Project/features.pkl\", test)\n",
1064
+ "print(\"photos: test=%d\" % len(test_features))\n",
1065
+ "\n",
1066
+ "from keras.models import load_model\n",
1067
+ "filename = \"/content/drive/MyDrive/Image_Captioning_Project/model_18.h5\"\n",
1068
+ "model = load_model(filename)"
1069
+ ]
1070
+ },
1071
+ {
1072
+ "cell_type": "code",
1073
+ "source": [
1074
+ "# evaluate_model(model, test_description, test_features, tokenizer, max_length)"
1075
+ ],
1076
+ "metadata": {
1077
+ "id": "URns1LFyOaPZ"
1078
+ },
1079
+ "execution_count": 117,
1080
+ "outputs": []
1081
+ },
1082
+ {
1083
+ "cell_type": "code",
1084
+ "execution_count": 118,
1085
+ "metadata": {
1086
+ "id": "9dVz3rRrKvAi"
1087
+ },
1088
+ "outputs": [],
1089
+ "source": [
1090
+ "from pickle import load\n",
1091
+ "from numpy import argmax\n",
1092
+ "from tensorflow.keras.preprocessing.sequence import pad_sequences\n",
1093
+ "from keras.applications.vgg16 import VGG16\n",
1094
+ "from tensorflow.keras.preprocessing.image import load_img\n",
1095
+ "from tensorflow.keras.preprocessing.image import img_to_array\n",
1096
+ "from keras.applications.vgg16 import preprocess_input\n",
1097
+ "from keras.models import Model\n",
1098
+ "from keras.models import load_model\n",
1099
+ "# from keras.preprocessing.text import Tokenizer"
1100
+ ]
1101
+ },
1102
+ {
1103
+ "cell_type": "code",
1104
+ "execution_count": 119,
1105
+ "metadata": {
1106
+ "id": "qvlspE-eitvS"
1107
+ },
1108
+ "outputs": [],
1109
+ "source": [
1110
+ "def extract_features(filename):\n",
1111
+ "\t# load the model\n",
1112
+ "\tmodel = VGG16()\n",
1113
+ "\t# re-structure the model\n",
1114
+ "\tmodel.layers.pop()\n",
1115
+ "\tmodel = Model(inputs=model.inputs, outputs=model.layers[-2].output)\n",
1116
+ "\t# load the photo\n",
1117
+ "\timage = load_img(filename, target_size=(224, 224))\n",
1118
+ "\t# convert the image pixels to a numpy array\n",
1119
+ "\timage = img_to_array(image)\n",
1120
+ "\t# reshape data for the model\n",
1121
+ "\timage = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))\n",
1122
+ "\t# prepare the image for the VGG model\n",
1123
+ "\timage = preprocess_input(image)\n",
1124
+ "\t# get features\n",
1125
+ "\tfeature = model.predict(image, verbose=0)\n",
1126
+ "\treturn feature"
1127
+ ]
1128
+ },
1129
+ {
1130
+ "cell_type": "code",
1131
+ "execution_count": 124,
1132
+ "metadata": {
1133
+ "colab": {
1134
+ "base_uri": "https://localhost:8080/"
1135
+ },
1136
+ "id": "ao4swPUfj1Ql",
1137
+ "outputId": "b6c92906-91c1-44c2-c958-409ca4a30d8b"
1138
+ },
1139
+ "outputs": [
1140
+ {
1141
+ "output_type": "stream",
1142
+ "name": "stderr",
1143
+ "text": [
1144
+ "WARNING:tensorflow:Layer lstm_1 will not use cuDNN kernels since it doesn't meet the criteria. It will use a generic GPU kernel as fallback when running on GPU.\n"
1145
+ ]
1146
+ },
1147
+ {
1148
+ "output_type": "stream",
1149
+ "name": "stdout",
1150
+ "text": [
1151
+ "startseq dog is running through the snow endseq\n"
1152
+ ]
1153
+ }
1154
+ ],
1155
+ "source": [
1156
+ "from pickle import load\n",
1157
+ "from tensorflow.keras.preprocessing.text import Tokenizer\n",
1158
+ "\n",
1159
+ "tokenizer = load(open('/content/tokenizer1.pkl', 'rb'))\n",
1160
+ "max_len = 34\n",
1161
+ "model = load_model('/content/drive/MyDrive/Image_Captioning_Project/model_18.h5')\n",
1162
+ "photo = extract_features(\"/content/drive/MyDrive/Image_Captioning_Project/Images/101654506_8eb26cfb60.jpg\")\n",
1163
+ "tokenizer.analyzer = None\n",
1164
+ "description = generate_desc(model, tokenizer, photo, max_len)\n",
1165
+ "print(description)"
1166
+ ]
1167
+ },
1168
+ {
1169
+ "cell_type": "code",
1170
+ "execution_count": 121,
1171
+ "metadata": {
1172
+ "colab": {
1173
+ "base_uri": "https://localhost:8080/"
1174
+ },
1175
+ "id": "T1IsisClmnJI",
1176
+ "outputId": "cb6f632f-9792-4dce-aa58-174f60a94ecf"
1177
+ },
1178
+ "outputs": [
1179
+ {
1180
+ "output_type": "stream",
1181
+ "name": "stdout",
1182
+ "text": [
1183
+ "man in red shirt is standing on rock\n"
1184
+ ]
1185
+ }
1186
+ ],
1187
+ "source": [
1188
+ "query = description\n",
1189
+ "stopwords = ['startseq','endseq']\n",
1190
+ "querywords = query.split()\n",
1191
+ "\n",
1192
+ "resultwords = [word for word in querywords if word.lower() not in stopwords]\n",
1193
+ "result = ' '.join(resultwords)\n",
1194
+ "\n",
1195
+ "print(result)"
1196
+ ]
1197
+ },
1198
+ {
1199
+ "cell_type": "code",
1200
+ "source": [],
1201
+ "metadata": {
1202
+ "id": "vO4XsnKBEUeg"
1203
+ },
1204
+ "execution_count": 121,
1205
+ "outputs": []
1206
+ }
1207
+ ],
1208
+ "metadata": {
1209
+ "accelerator": "GPU",
1210
+ "colab": {
1211
+ "provenance": [],
1212
+ "gpuType": "T4"
1213
+ },
1214
+ "kernelspec": {
1215
+ "display_name": "Python 3",
1216
+ "name": "python3"
1217
+ },
1218
+ "language_info": {
1219
+ "name": "python"
1220
+ }
1221
+ },
1222
+ "nbformat": 4,
1223
+ "nbformat_minor": 0
1224
+ }
model_18.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:65e82872f924314f4e3701ede68a9e77f56076f0e4a4df50cc12889f96df084f
3
+ size 66382940
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ srsly==2.4.6
2
+ statsmodels==0.14.0
3
+ streamlit==1.21.0
4
+ sympy==1.11.1
5
+ tempora==5.2.2
6
+ tenacity==8.2.2
7
+ tensorboard==2.12.2
8
+ tensorboard-data-server==0.7.0
9
+ tensorboard-plugin-wit==1.8.1
10
+ tensorflow==2.12.0
11
+ tensorflow-estimator==2.12.0
12
+ tensorflow-io-gcs-filesystem==0.31.0
13
+ termcolor==2.2.0
streamlit.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from tensorflow.keras.models import load_model
3
+ from tensorflow.keras.preprocessing.text import Tokenizer
4
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
5
+ from tensorflow.keras.applications.vgg16 import preprocess_input
6
+ from tensorflow.keras.applications.vgg16 import VGG16
7
+ from tensorflow.keras.models import Model
8
+ from tensorflow.keras.preprocessing.image import load_img, img_to_array
9
+ import numpy as np
10
+ from PIL import Image
11
+ from pickle import load
12
+
13
+ # Load tokenizer
14
+ tokenizer = load(open('tokenizer1.pkl', 'rb'))
15
+ max_len = 34
16
+
17
+ # Load image captioning model
18
+ model = load_model('model_18.h5')
19
+
20
+ # Load VGG16 model for feature extraction
21
+ vgg_model = VGG16()
22
+ vgg_model.layers.pop()
23
+ vgg_model = Model(inputs=vgg_model.inputs, outputs=vgg_model.layers[-2].output)
24
+
25
+ # Function to map an integer to a word
26
+ def word_for_id(integer, tokenizer):
27
+ for word, index in tokenizer.word_index.items():
28
+ if index == integer:
29
+ return word
30
+ return None
31
+
32
+ # Function to generate image caption
33
+ def generate_caption(model, tokenizer, photo, max_length):
34
+ # Seed the generation process
35
+ in_text = 'startseq'
36
+ # Iterate over the whole length of the sequence
37
+ for i in range(max_length):
38
+ # Integer encode input sequence
39
+ sequence = tokenizer.texts_to_sequences([in_text])[0]
40
+ # Pad input
41
+ sequence = pad_sequences([sequence], maxlen=max_length)
42
+ # Predict next word
43
+ yhat = model.predict([photo, sequence], verbose=0)
44
+ # Convert probability to integer
45
+ yhat = np.argmax(yhat)
46
+ # Map integer to word
47
+ word = word_for_id(yhat, tokenizer)
48
+ # Stop if we cannot map the word
49
+ if word is None:
50
+ break
51
+ # Append as input for generating the next word
52
+ in_text += ' ' + word
53
+ # Stop if we predict the end of the sequence
54
+ if word == 'endseq':
55
+ break
56
+ return in_text
57
+
58
+ # Function to extract image features
59
+ def extract_features(filename):
60
+ # Load the photo
61
+ image = load_img(filename, target_size=(224, 224))
62
+ # Convert the image pixels to a numpy array
63
+ image = img_to_array(image)
64
+ # Reshape data for the model
65
+ image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
66
+ # Prepare the image for the VGG model
67
+ image = preprocess_input(image)
68
+ # Get features
69
+ feature = vgg_model.predict(image, verbose=0)
70
+ return feature
71
+
72
+ # Remove start and end sequence tokens from the generated caption
73
+ def remove_start_end_tokens(caption):
74
+ stopwords = ['startseq', 'endseq']
75
+ querywords = caption.split()
76
+ resultwords = [word for word in querywords if word.lower() not in stopwords]
77
+ result = ' '.join(resultwords)
78
+ return result
79
+
80
+ def main():
81
+ st.set_page_config(page_title="Image Captioning", page_icon="📷")
82
+ st.title("Image Captioning")
83
+ st.markdown("Upload an image and get a caption for it.")
84
+
85
+ # File uploader
86
+ uploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])
87
+
88
+ if uploaded_file is not None:
89
+ # Display uploaded image
90
+ image = Image.open(uploaded_file)
91
+ resized_image = image.resize((400, 400))
92
+ st.image(resized_image, caption='Uploaded Image')
93
+
94
+ # Extract image features
95
+ photo = extract_features(uploaded_file)
96
+
97
+ # Generate image caption
98
+ if st.button("Generate Caption"):
99
+ with st.spinner("Generating caption..."):
100
+ description = generate_caption(model, tokenizer, photo, max_len)
101
+
102
+ # Remove start and end sequence tokens from the caption
103
+ caption = remove_start_end_tokens(description)
104
+
105
+ # Display caption
106
+ st.subheader(" Generated Caption")
107
+ st.markdown("---")
108
+ st.markdown(f"<p style='font-size: 18px; text-align: center;'>{caption}</p>", unsafe_allow_html=True)
109
+ st.markdown("---")
110
+
111
+
112
+ if __name__ == '__main__':
113
+ main()
tokenizer1.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eaf7e2d2acb76ab36344db7ee8f8bd15efff2057d8e5481089e0219e8d6055dd
3
+ size 299574