Spaces:
Sleeping
Sleeping
Delete flickr30k.py
Browse files- flickr30k.py +0 -155
flickr30k.py
DELETED
|
@@ -1,155 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import cv2
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pickle
|
| 5 |
-
from PIL import Image
|
| 6 |
-
import matplotlib.pyplot as plt
|
| 7 |
-
import tensorflow as tf
|
| 8 |
-
from tensorflow.keras import layers
|
| 9 |
-
from tensorflow.keras.models import load_model, Model
|
| 10 |
-
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction, corpus_bleu
|
| 11 |
-
from tensorflow.keras.applications import EfficientNetV2B0
|
| 12 |
-
from tensorflow.keras.applications.efficientnet import preprocess_input as efficientnet_preprocess
|
| 13 |
-
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 14 |
-
from tensorflow.keras.preprocessing.image import img_to_array
|
| 15 |
-
from tqdm import tqdm
|
| 16 |
-
from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction, corpus_bleu
|
| 17 |
-
import random
|
| 18 |
-
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
| 19 |
-
from PIL import Image
|
| 20 |
-
import pickle
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
# -----------------------------
|
| 25 |
-
# Custom attention layers
|
| 26 |
-
# -----------------------------
|
| 27 |
-
|
| 28 |
-
class ChannelAttention(layers.Layer):
|
| 29 |
-
def __init__(self, ratio=8, **kwargs):
|
| 30 |
-
super(ChannelAttention, self).__init__(**kwargs)
|
| 31 |
-
self.ratio = ratio
|
| 32 |
-
|
| 33 |
-
def build(self, input_shape):
|
| 34 |
-
self.gap = layers.GlobalAveragePooling1D()
|
| 35 |
-
self.gmp = layers.GlobalMaxPooling1D()
|
| 36 |
-
self.shared_mlp = tf.keras.Sequential([
|
| 37 |
-
layers.Dense(units=1280 // self.ratio, activation='relu'),
|
| 38 |
-
layers.Dense(units=1280)
|
| 39 |
-
])
|
| 40 |
-
self.sigmoid = layers.Activation('sigmoid')
|
| 41 |
-
super(ChannelAttention, self).build(input_shape)
|
| 42 |
-
|
| 43 |
-
def call(self, inputs):
|
| 44 |
-
gap = self.gap(inputs)
|
| 45 |
-
gmp = self.gmp(inputs)
|
| 46 |
-
gap_mlp = self.shared_mlp(gap)
|
| 47 |
-
gmp_mlp = self.shared_mlp(gmp)
|
| 48 |
-
channel_attention = self.sigmoid(gap_mlp + gmp_mlp)
|
| 49 |
-
return inputs * tf.expand_dims(channel_attention, axis=1)
|
| 50 |
-
|
| 51 |
-
def get_config(self):
|
| 52 |
-
config = super(ChannelAttention, self).get_config()
|
| 53 |
-
config.update({'ratio': self.ratio})
|
| 54 |
-
return config
|
| 55 |
-
|
| 56 |
-
@classmethod
|
| 57 |
-
def from_config(cls, config):
|
| 58 |
-
return cls(**config)
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
class SpatialAttention(layers.Layer):
|
| 63 |
-
def __init__(self, **kwargs):
|
| 64 |
-
super(SpatialAttention, self).__init__(**kwargs)
|
| 65 |
-
|
| 66 |
-
def build(self, input_shape):
|
| 67 |
-
self.conv = layers.Conv1D(1, kernel_size=3, padding='same', activation='sigmoid')
|
| 68 |
-
super(SpatialAttention, self).build(input_shape)
|
| 69 |
-
|
| 70 |
-
def call(self, inputs):
|
| 71 |
-
spatial_attention = self.conv(inputs)
|
| 72 |
-
return inputs * spatial_attention
|
| 73 |
-
|
| 74 |
-
def get_config(self):
|
| 75 |
-
return super(SpatialAttention, self).get_config()
|
| 76 |
-
|
| 77 |
-
@classmethod
|
| 78 |
-
def from_config(cls, config):
|
| 79 |
-
return cls(**config)
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
# -----------------------------
|
| 84 |
-
# Load model + tokenizer
|
| 85 |
-
# -----------------------------
|
| 86 |
-
|
| 87 |
-
def load_caption_model(model_path='best_model.keras'):
|
| 88 |
-
custom_objects = {
|
| 89 |
-
'ChannelAttention': ChannelAttention,
|
| 90 |
-
'SpatialAttention': SpatialAttention
|
| 91 |
-
}
|
| 92 |
-
model = load_model(model_path, custom_objects=custom_objects)
|
| 93 |
-
print("✅ Đã load model thành công!")
|
| 94 |
-
return model
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
def load_tokenizer_and_config():
|
| 98 |
-
with open('tokenizer.pkl', 'rb') as f:
|
| 99 |
-
tokenizer = pickle.load(f)
|
| 100 |
-
with open('model_config.pkl', 'rb') as f:
|
| 101 |
-
config = pickle.load(f)
|
| 102 |
-
return tokenizer, config['max_length'], config['vocab_size']
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
# -----------------------------
|
| 106 |
-
# Feature extractor - EfficientNetV2B0
|
| 107 |
-
# -----------------------------
|
| 108 |
-
|
| 109 |
-
def load_feature_extractor():
|
| 110 |
-
base_model = EfficientNetV2B0(include_top=False, weights='imagenet', pooling='avg')
|
| 111 |
-
return Model(inputs=base_model.input, outputs=base_model.output)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
def extract_features_from_image(image_path, extractor):
|
| 115 |
-
image = cv2.imread(image_path)
|
| 116 |
-
if image is None:
|
| 117 |
-
print(f"❌ Không đọc được ảnh: {image_path}")
|
| 118 |
-
return None
|
| 119 |
-
image = cv2.resize(image, (224, 224))
|
| 120 |
-
image = img_to_array(image)
|
| 121 |
-
image = np.expand_dims(image, axis=0)
|
| 122 |
-
image = efficientnet_preprocess(image)
|
| 123 |
-
feature = extractor.predict(image, verbose=0)
|
| 124 |
-
return feature
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
# -----------------------------
|
| 128 |
-
# Generate caption
|
| 129 |
-
# -----------------------------
|
| 130 |
-
|
| 131 |
-
def generate_caption(model, tokenizer, image_features, max_length):
|
| 132 |
-
in_text = 'startseq'
|
| 133 |
-
for _ in range(max_length):
|
| 134 |
-
sequence = tokenizer.texts_to_sequences([in_text])[0]
|
| 135 |
-
sequence = pad_sequences([sequence], maxlen=max_length)
|
| 136 |
-
yhat = model.predict([image_features, sequence], verbose=0)
|
| 137 |
-
yhat = np.argmax(yhat)
|
| 138 |
-
word = tokenizer.index_word.get(yhat)
|
| 139 |
-
if word is None or word == 'endseq':
|
| 140 |
-
break
|
| 141 |
-
in_text += ' ' + word
|
| 142 |
-
return in_text.replace('startseq ', '')
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
# -----------------------------
|
| 146 |
-
# Hiển thị ảnh và caption
|
| 147 |
-
# -----------------------------
|
| 148 |
-
|
| 149 |
-
def display_caption(image_path, caption):
|
| 150 |
-
img = Image.open(image_path)
|
| 151 |
-
img = img.resize((1024, 768)) # Resize for better display
|
| 152 |
-
plt.imshow(img)
|
| 153 |
-
plt.axis('off')
|
| 154 |
-
plt.title(f"Caption: {caption}", fontsize=14, pad=10)
|
| 155 |
-
plt.show()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|