Spaces:
Build error
Build error
File size: 17,277 Bytes
a328423 | 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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 | import gradio as gr
import torch
import torch.nn as nn
import torch.nn.functional as F
import pickle
import numpy as np
from PIL import Image
from torchvision import models, transforms
# ==============================================================================
# EXACT MODEL ARCHITECTURE β copied 1-to-1 from training code
# ==============================================================================
class Encoder(nn.Module):
def __init__(self, feature_size=2048, hidden_size=512, dropout=0.5):
super(Encoder, self).__init__()
self.fc = nn.Linear(feature_size, hidden_size)
self.dropout = nn.Dropout(dropout)
self.bn = nn.BatchNorm1d(hidden_size)
def forward(self, features):
encoded = self.fc(features)
encoded = self.bn(encoded)
encoded = F.relu(encoded)
encoded = self.dropout(encoded)
return encoded
class Attention(nn.Module):
def __init__(self, encoder_dim, decoder_dim, attention_dim):
super(Attention, self).__init__()
self.encoder_att = nn.Linear(encoder_dim, attention_dim)
self.decoder_att = nn.Linear(decoder_dim, attention_dim)
self.full_att = nn.Linear(attention_dim, 1)
self.relu = nn.ReLU()
self.softmax = nn.Softmax(dim=1)
def forward(self, encoder_out, decoder_hidden):
att1 = self.encoder_att(encoder_out)
att2 = self.decoder_att(decoder_hidden)
att = self.full_att(self.relu(att1 + att2)).squeeze(-1)
alpha = self.softmax(att.unsqueeze(1))
attention_weighted_encoding = encoder_out * alpha
return attention_weighted_encoding, alpha
class Decoder(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1, dropout=0.5):
super(Decoder, self).__init__()
self.embed_size = embed_size
self.hidden_size = hidden_size
self.vocab_size = vocab_size
self.num_layers = num_layers
self.embedding = nn.Embedding(vocab_size, embed_size)
self.dropout = nn.Dropout(dropout)
self.lstm = nn.LSTM(
embed_size + hidden_size,
hidden_size,
num_layers,
batch_first=True,
dropout=dropout if num_layers > 1 else 0
)
self.attention = Attention(hidden_size, hidden_size, hidden_size)
self.fc = nn.Linear(hidden_size, vocab_size)
self._init_weights()
def _init_weights(self):
self.embedding.weight.data.uniform_(-0.1, 0.1)
self.fc.bias.data.fill_(0)
self.fc.weight.data.uniform_(-0.1, 0.1)
def generate(self, features, max_len=50, start_token=1, end_token=2):
"""Greedy search"""
h = features.unsqueeze(0).repeat(self.num_layers, 1, 1)
c = torch.zeros_like(h)
input_token = torch.LongTensor([start_token]).to(features.device)
generated = []
for _ in range(max_len):
embed = self.embedding(input_token).unsqueeze(1)
hiddens = h[-1]
context, _ = self.attention(features, hiddens)
lstm_input = torch.cat([embed.squeeze(1), context], dim=1).unsqueeze(1)
_, (h, c) = self.lstm(lstm_input, (h, c))
output = self.fc(h[-1])
predicted = output.argmax(1)
generated.append(predicted.item())
if predicted.item() == end_token:
break
input_token = predicted
return generated
def beam_search(self, features, beam_width=5, max_len=50, start_token=1, end_token=2):
"""Beam search"""
device = features.device
h = features.unsqueeze(0).repeat(self.num_layers, 1, 1)
c = torch.zeros_like(h)
beams = [([start_token], 0.0, h, c)]
completed_beams = []
for _ in range(max_len):
all_candidates = []
for seq, score, h_state, c_state in beams:
if seq[-1] == end_token:
completed_beams.append((seq, score))
continue
input_token = torch.LongTensor([seq[-1]]).to(device)
embed = self.embedding(input_token).unsqueeze(1)
hiddens = h_state[-1]
context, _ = self.attention(features, hiddens)
lstm_input = torch.cat([embed.squeeze(1), context], dim=1).unsqueeze(1)
_, (h_new, c_new) = self.lstm(lstm_input, (h_state, c_state))
log_probs = F.log_softmax(self.fc(h_new[-1]), dim=1)
topk_probs, topk_idx = log_probs.topk(beam_width, dim=1)
for i in range(beam_width):
all_candidates.append((
seq + [topk_idx[0, i].item()],
score + topk_probs[0, i].item(),
h_new, c_new
))
beams = sorted(all_candidates, key=lambda x: x[1], reverse=True)[:beam_width]
if not beams:
break
completed_beams.extend([(seq, score) for seq, score, _, _ in beams])
if completed_beams:
best_seq, _ = max(completed_beams, key=lambda x: x[1])
return best_seq
return beams[0][0] if beams else [start_token, end_token]
class ImageCaptioningModel(nn.Module):
def __init__(self, encoder, decoder):
super(ImageCaptioningModel, self).__init__()
self.encoder = encoder
self.decoder = decoder
def forward(self, features, captions, lengths):
return self.decoder(self.encoder(features), captions, lengths)
# ==============================================================================
# LOAD MODELS & VOCAB (runs once at startup)
# ==============================================================================
DEVICE = torch.device("cpu") # HF free-tier has no GPU
# ββ Hyperparameters β must match training exactly ββββββββββββββββββββββββββββββ
FEATURE_SIZE = 2048
HIDDEN_SIZE = 512
EMBED_SIZE = 512
NUM_LAYERS = 2
DROPOUT = 0.5
def load_vocab(path="vocab.pkl"):
with open(path, "rb") as f:
return pickle.load(f)
def load_model(vocab, path="best_model.pth"):
encoder = Encoder(feature_size=FEATURE_SIZE, hidden_size=HIDDEN_SIZE, dropout=DROPOUT)
decoder = Decoder(
embed_size=EMBED_SIZE,
hidden_size=HIDDEN_SIZE,
vocab_size=len(vocab),
num_layers=NUM_LAYERS,
dropout=DROPOUT
)
model = ImageCaptioningModel(encoder, decoder).to(DEVICE)
checkpoint = torch.load(path, map_location=DEVICE, weights_only=False)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
return model
def load_resnet():
resnet = models.resnet50(weights=models.ResNet50_Weights.DEFAULT)
resnet = nn.Sequential(*list(resnet.children())[:-1]) # drop classifier
resnet = resnet.to(DEVICE)
resnet.eval()
return resnet
print("Loading vocab...")
vocab = load_vocab("vocab.pkl")
print(f" Vocab size: {len(vocab)} words")
print("Loading captioning model...")
model = load_model(vocab, "best_model.pth")
print(" Model ready.")
print("Loading ResNet50 feature extractor...")
resnet = load_resnet()
print(" ResNet50 ready.")
# ββ Image pre-processing β same as training ββββββββββββββββββββββββββββββββββββ
IMG_TRANSFORM = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
])
# ==============================================================================
# INFERENCE HELPERS
# ==============================================================================
def extract_features(pil_image: Image.Image) -> torch.Tensor:
"""Run image through ResNet50 β (1, 2048) feature vector."""
img_tensor = IMG_TRANSFORM(pil_image).unsqueeze(0).to(DEVICE)
with torch.no_grad():
features = resnet(img_tensor).view(1, -1) # (1, 2048)
return features
def ids_to_caption(ids, vocab) -> str:
"""Convert list of token ids β clean sentence string."""
words = []
for idx in ids:
if idx == vocab.stoi["<end>"]:
break
if idx not in (vocab.stoi["<start>"], vocab.stoi["<pad>"]):
words.append(vocab.itos[idx])
return " ".join(words).capitalize() if words else "Could not generate a caption."
def caption_image(pil_image: Image.Image, method: str, beam_width: int) -> tuple[str, str]:
"""
Main inference function called by Gradio.
Returns (caption_string, info_string).
"""
if pil_image is None:
return "Please upload an image.", ""
# 1. Extract features
features = extract_features(pil_image)
# 2. Encode
with torch.no_grad():
encoded = model.encoder(features) # (1, 512)
# 3. Decode
with torch.no_grad():
if method == "Beam Search":
ids = model.decoder.beam_search(
encoded,
beam_width=beam_width,
max_len=50,
start_token=vocab.stoi["<start>"],
end_token=vocab.stoi["<end>"],
)
else: # Greedy
ids = model.decoder.generate(
encoded,
max_len=50,
start_token=vocab.stoi["<start>"],
end_token=vocab.stoi["<end>"],
)
caption = ids_to_caption(ids, vocab)
info = f"Method: {method}" + (f" | Beam width: {beam_width}" if method == "Beam Search" else "")
return caption, info
# ==============================================================================
# GRADIO UI
# ==============================================================================
CSS = """
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,700;1,400&family=DM+Mono:wght@400;500&display=swap');
:root {
--cream: #F5F0E8;
--ink: #1A1208;
--sienna: #B85C2A;
--gold: #D4A843;
--warm-gray: #8C7B6B;
--border: #D9CFC2;
}
body, .gradio-container {
background: var(--cream) !important;
font-family: 'DM Mono', monospace !important;
}
/* ββ Header ββ */
#header {
text-align: center;
padding: 2.5rem 1rem 1rem;
border-bottom: 2px solid var(--ink);
margin-bottom: 2rem;
}
#header h1 {
font-family: 'Playfair Display', serif !important;
font-size: clamp(2rem, 5vw, 3.5rem) !important;
font-weight: 700 !important;
color: var(--ink) !important;
letter-spacing: -0.02em;
margin: 0 !important;
line-height: 1.1;
}
#header .subtitle {
font-family: 'Playfair Display', serif;
font-style: italic;
font-size: 1.1rem;
color: var(--sienna);
margin-top: 0.4rem;
}
#header .tag-line {
font-size: 0.72rem;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--warm-gray);
margin-top: 0.6rem;
}
/* ββ Main columns ββ */
.main-col { padding: 0 0.5rem; }
/* ββ Image upload box ββ */
.image-upload .wrap { border: 2px dashed var(--border) !important; border-radius: 4px !important; background: white !important; }
.image-upload .wrap:hover { border-color: var(--sienna) !important; }
/* ββ Caption output ββ */
#caption-box textarea {
font-family: 'Playfair Display', serif !important;
font-style: italic !important;
font-size: 1.35rem !important;
color: var(--ink) !important;
background: white !important;
border: 2px solid var(--ink) !important;
border-radius: 4px !important;
padding: 1.2rem !important;
line-height: 1.6 !important;
min-height: 80px !important;
}
/* ββ Info box ββ */
#info-box textarea {
font-family: 'DM Mono', monospace !important;
font-size: 0.78rem !important;
color: var(--warm-gray) !important;
background: transparent !important;
border: none !important;
border-top: 1px solid var(--border) !important;
padding: 0.6rem 0 0 !important;
}
/* ββ Controls ββ */
.gr-radio label, .gr-slider label {
font-family: 'DM Mono', monospace !important;
font-size: 0.8rem !important;
letter-spacing: 0.05em !important;
color: var(--ink) !important;
}
/* ββ Generate button ββ */
#generate-btn {
background: var(--ink) !important;
color: var(--cream) !important;
border: none !important;
border-radius: 2px !important;
font-family: 'DM Mono', monospace !important;
font-size: 0.85rem !important;
letter-spacing: 0.12em !important;
text-transform: uppercase !important;
padding: 0.75rem 2rem !important;
cursor: pointer !important;
transition: background 0.2s, transform 0.1s !important;
width: 100% !important;
}
#generate-btn:hover {
background: var(--sienna) !important;
transform: translateY(-1px) !important;
}
/* ββ Section labels ββ */
.section-label {
font-size: 0.68rem;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--warm-gray);
border-bottom: 1px solid var(--border);
padding-bottom: 0.4rem;
margin-bottom: 0.8rem;
}
/* ββ Examples strip ββ */
.examples-label {
font-size: 0.68rem;
letter-spacing: 0.18em;
text-transform: uppercase;
color: var(--warm-gray);
margin-top: 1.5rem;
margin-bottom: 0.5rem;
}
/* ββ Footer ββ */
#footer {
text-align: center;
padding: 1.5rem;
border-top: 1px solid var(--border);
margin-top: 2rem;
font-size: 0.72rem;
letter-spacing: 0.1em;
color: var(--warm-gray);
}
/* hide default Gradio labels where we use custom ones */
.hide-label > label { display: none !important; }
"""
def run(image, method, beam_width):
return caption_image(image, method, int(beam_width))
with gr.Blocks(css=CSS, title="Neural Storyteller") as demo:
# ββ Header ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
gr.HTML("""
<div id="header">
<div class="tag-line">ResNet50 Β· LSTM Β· Bahdanau Attention Β· Flickr30k</div>
<h1>Neural Storyteller</h1>
<div class="subtitle">Image Captioning with Seq2Seq</div>
</div>
""")
# ββ Main layout βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Row():
# Left β image upload
with gr.Column(scale=5, elem_classes="main-col"):
gr.HTML('<div class="section-label">Upload Image</div>')
image_input = gr.Image(
type="pil",
label="",
elem_classes=["image-upload", "hide-label"],
height=380,
)
# Right β controls + output
with gr.Column(scale=5, elem_classes="main-col"):
gr.HTML('<div class="section-label">Decoding Strategy</div>')
method = gr.Radio(
choices=["Beam Search", "Greedy"],
value="Beam Search",
label="",
elem_classes="hide-label",
)
beam_width = gr.Slider(
minimum=1, maximum=10, value=5, step=1,
label="Beam Width (only applies to Beam Search)",
)
gr.HTML('<div class="section-label" style="margin-top:1.2rem">Generated Caption</div>')
caption_out = gr.Textbox(
label="",
elem_id="caption-box",
elem_classes="hide-label",
lines=3,
interactive=False,
placeholder="Your caption will appear hereβ¦",
)
info_out = gr.Textbox(
label="",
elem_id="info-box",
elem_classes="hide-label",
lines=1,
interactive=False,
)
generate_btn = gr.Button("Generate Caption", elem_id="generate-btn")
# ββ Wire up βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
generate_btn.click(
fn=run,
inputs=[image_input, method, beam_width],
outputs=[caption_out, info_out],
)
# Also trigger on image upload for instant feel
image_input.upload(
fn=run,
inputs=[image_input, method, beam_width],
outputs=[caption_out, info_out],
)
# ββ Footer ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
gr.HTML("""
<div id="footer">
Neural Storyteller Β· Seq2Seq with Bahdanau Attention
Β· Trained on Flickr30k Β· Built with PyTorch
</div>
""")
if __name__ == "__main__":
demo.launch()
|