Spaces:
Sleeping
Sleeping
File size: 5,828 Bytes
40243b5 4e28109 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 4e28109 d75e81d 40243b5 d75e81d 40243b5 18eb267 d75e81d 18eb267 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d 40243b5 d75e81d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.models as models
from PIL import Image
import pickle
import os
import re
from collections import Counter
from huggingface_hub import hf_hub_download
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
EMBED_DIM = 512
HIDDEN_DIM = 512
MAX_LEN = 25
# -----------------------
# Vocabulary
# -----------------------
class Vocabulary:
def __init__(self, freq_threshold=5):
self.freq_threshold = freq_threshold
self.itos = {0: "pad", 1: "startofseq", 2: "endofseq", 3: "unk"}
self.stoi = {v: k for k, v in self.itos.items()}
self.index = 4
def __len__(self):
return len(self.itos)
def tokenizer(self, text):
text = text.lower()
tokens = re.findall(r"\w+", text)
return tokens
def build_vocabulary(self, sentence_list):
frequencies = Counter()
for sentence in sentence_list:
tokens = self.tokenizer(sentence)
frequencies.update(tokens)
for word, freq in frequencies.items():
if freq >= self.freq_threshold:
self.stoi[word] = self.index
self.itos[self.index] = word
self.index += 1
def numericalize(self, text):
tokens = self.tokenizer(text)
numericalized = []
for token in tokens:
numericalized.append(self.stoi.get(token, self.stoi["unk"]))
return numericalized
# -----------------------
# Encoder
# -----------------------
class ResNetEncoder(nn.Module):
def __init__(self, embed_dim):
super().__init__()
resnet = models.resnet50(weights=None)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.fc = nn.Linear(resnet.fc.in_features, embed_dim)
self.batch_norm = nn.BatchNorm1d(embed_dim, momentum=0.01)
def forward(self, images):
with torch.no_grad():
features = self.resnet(images)
features = features.view(features.size(0), -1)
features = self.fc(features)
features = self.batch_norm(features)
return features
# -----------------------
# Decoder
# -----------------------
class DecoderLSTM(nn.Module):
def __init__(self, embed_dim, hidden_dim, vocab_size, num_layers=1):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.lstm = nn.LSTM(embed_dim, hidden_dim, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_dim, vocab_size)
def forward(self, features, captions):
captions = captions[:, :-1]
emb = self.embedding(captions)
features = features.unsqueeze(1)
lstm_input = torch.cat((features, emb), dim=1)
outputs, _ = self.lstm(lstm_input)
logits = self.fc(outputs)
return logits
# -----------------------
# Caption Model
# -----------------------
class ImageCaptioningModel(nn.Module):
def __init__(self, encoder, decoder):
super().__init__()
self.encoder = encoder
self.decoder = decoder
def forward(self, images, captions):
features = self.encoder(images)
outputs = self.decoder(features, captions)
return outputs
# -----------------------
# Caption Generator
# -----------------------
def generate_caption(model, image, vocab):
model.eval()
image = image.unsqueeze(0).to(DEVICE)
sentence = []
with torch.no_grad():
features = model.encoder(image)
word_idx = vocab.stoi["startofseq"]
hidden = None
for _ in range(MAX_LEN):
word_tensor = torch.tensor([word_idx]).to(DEVICE)
emb = model.decoder.embedding(word_tensor)
if hidden is None:
lstm_input = torch.cat(
[features.unsqueeze(1), emb.unsqueeze(1)], dim=1
)
else:
lstm_input = emb.unsqueeze(1)
output, hidden = model.decoder.lstm(lstm_input, hidden)
logits = model.decoder.fc(output[:, -1, :])
predicted = logits.argmax(1).item()
token = vocab.itos[predicted]
if token == "endofseq":
break
sentence.append(token)
word_idx = predicted
return " ".join(sentence)
# -----------------------
# Image Transform
# -----------------------
transform = transforms.Compose(
[
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
),
]
)
# -----------------------
# Load Model Once
# -----------------------
script_dir = os.path.dirname(os.path.abspath(__file__))
CHECKPOINT_PATH = hf_hub_download(
repo_id="VIKRAM989/image-label",
filename="best_checkpoint.pth"
)
VOCAB_PATH = os.path.join(script_dir, "vocab.pkl")
class CustomUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if name == "Vocabulary":
return Vocabulary
return super().find_class(module, name)
with open(VOCAB_PATH, "rb") as f:
vocab = CustomUnpickler(f).load()
vocab_size = len(vocab)
encoder = ResNetEncoder(EMBED_DIM)
decoder = DecoderLSTM(EMBED_DIM, HIDDEN_DIM, vocab_size)
model = ImageCaptioningModel(encoder, decoder).to(DEVICE)
checkpoint = torch.load(CHECKPOINT_PATH, map_location=DEVICE)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
# -----------------------
# Public Function for API
# -----------------------
def caption_image(pil_image):
img = transform(pil_image).to(DEVICE)
caption = generate_caption(model, img, vocab)
return caption |