Spaces:
Build error
Build error
Upload 3 files
Browse files
README.md
CHANGED
|
@@ -1,14 +1,53 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
-
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
readme_content = """# Image Captioning Model
|
| 2 |
+
|
| 3 |
+
This is an Image Captioning model trained on a custom dataset with 6000 training images and 1000 validation images. It uses ResNet50 for image feature extraction and an LSTM with fine-tuned GloVe embeddings for caption generation.
|
| 4 |
+
|
| 5 |
+
## Model Details
|
| 6 |
+
- **Image Encoder**: ResNet50
|
| 7 |
+
- **Text Decoder**: LSTM with fine-tuned GloVe embeddings
|
| 8 |
+
- **Vocabulary Size**: 3478
|
| 9 |
+
- **Embedding Dimension**: 512
|
| 10 |
+
- **Hidden Size**: 1024
|
| 11 |
+
- **Number of Layers**: 2
|
| 12 |
+
- **Max Caption Length**: 30
|
| 13 |
+
|
| 14 |
+
## Usage
|
| 15 |
+
Load the model and tokenizer using PyTorch and the provided `model.py`.
|
| 16 |
+
|
| 17 |
+
### Example
|
| 18 |
+
```python
|
| 19 |
+
import torch
|
| 20 |
+
from PIL import Image
|
| 21 |
+
import pickle
|
| 22 |
+
from huggingface_hub import hf_hub_download
|
| 23 |
+
from model import image_captioning_model
|
| 24 |
+
|
| 25 |
+
# Download files
|
| 26 |
+
repo_id = "Pumponchik/image_caption_weak"
|
| 27 |
+
model_path = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin")
|
| 28 |
+
config_path = hf_hub_download(repo_id=repo_id, filename="config.json")
|
| 29 |
+
tokenizer_path = hf_hub_download(repo_id=repo_id, filename="tokenizer.pkl")
|
| 30 |
+
transform_path = hf_hub_download(repo_id=repo_id, filename="image_transforms.pkl")
|
| 31 |
+
|
| 32 |
+
# Load config
|
| 33 |
+
with open(config_path, "r") as f:
|
| 34 |
+
config = json.load(f)
|
| 35 |
+
|
| 36 |
+
# Load model
|
| 37 |
+
model = image_captioning_model(**config)
|
| 38 |
+
model.load_state_dict(torch.load(model_path))
|
| 39 |
+
model.eval()
|
| 40 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 41 |
+
model.to(device)
|
| 42 |
+
|
| 43 |
+
# Load tokenizer and transforms
|
| 44 |
+
with open(tokenizer_path, "rb") as f:
|
| 45 |
+
tokenizer = pickle.load(f)
|
| 46 |
+
with open(transform_path, "rb") as f:
|
| 47 |
+
transform = pickle.load(f)
|
| 48 |
+
|
| 49 |
+
# Generate caption
|
| 50 |
+
image = Image.open("example.png").convert("RGB")
|
| 51 |
+
image_tensor = transform(image).unsqueeze(0).to(device)
|
| 52 |
+
caption = model.generate_caption(image_tensor, tokenizer, max_length=config["max_len"], device=device)
|
| 53 |
+
print("Generated Caption:", caption)
|
app.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn.functional as F
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import pickle
|
| 6 |
+
import json
|
| 7 |
+
from huggingface_hub import hf_hub_download
|
| 8 |
+
from model import image_captioning_model
|
| 9 |
+
|
| 10 |
+
# Загрузка файлов
|
| 11 |
+
repo_id = "Pumponchik/image_caption_weak"
|
| 12 |
+
model_path = hf_hub_download(repo_id=repo_id, filename="pytorch_model.bin")
|
| 13 |
+
config_path = hf_hub_download(repo_id=repo_id, filename="config.json")
|
| 14 |
+
tokenizer_path = hf_hub_download(repo_id=repo_id, filename="tokenizer.pkl")
|
| 15 |
+
transform_path = hf_hub_download(repo_id=repo_id, filename="image_transforms.pkl")
|
| 16 |
+
|
| 17 |
+
# Загрузка конфигурации
|
| 18 |
+
with open(config_path, "r") as f:
|
| 19 |
+
config = json.load(f)
|
| 20 |
+
|
| 21 |
+
# Загрузка модели
|
| 22 |
+
model = image_captioning_model(**config)
|
| 23 |
+
model.load_state_dict(torch.load(model_path, map_location="cpu"))
|
| 24 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 25 |
+
model.to(device)
|
| 26 |
+
model.eval()
|
| 27 |
+
|
| 28 |
+
# Загрузка токенизатора и трансформаций
|
| 29 |
+
with open(tokenizer_path, "rb") as f:
|
| 30 |
+
tokenizer = pickle.load(f)
|
| 31 |
+
with open(transform_path, "rb") as f:
|
| 32 |
+
transform = pickle.load(f)
|
| 33 |
+
|
| 34 |
+
title_width = 43
|
| 35 |
+
|
| 36 |
+
def wrap_text(text, max_width):
|
| 37 |
+
words = text.split(" ")
|
| 38 |
+
result = [[words[0]]]
|
| 39 |
+
for word in words[1:]:
|
| 40 |
+
if len(" ".join(result[-1])) + len(word) + 1 > max_width:
|
| 41 |
+
result[-1] = " ".join(result[-1])
|
| 42 |
+
result.append([])
|
| 43 |
+
result[-1].append(word)
|
| 44 |
+
result[-1] = " ".join(result[-1])
|
| 45 |
+
return "\n".join(result)
|
| 46 |
+
|
| 47 |
+
def generate(model, image, tokenizer, max_seq_len=20, top_p=None, top_k=1):
|
| 48 |
+
assert top_p is None or top_k is None, "Не используйте одновременно top_p и top_k"
|
| 49 |
+
|
| 50 |
+
model.eval()
|
| 51 |
+
device = next(model.parameters()).device
|
| 52 |
+
image = image.to(device)
|
| 53 |
+
batch_size = image.size(0)
|
| 54 |
+
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
img_emb = model.img_features(image) # [batch_size, 512]
|
| 57 |
+
h_0 = model.text_features.img_to_hidden(img_emb) # [batch_size, hidden_size]
|
| 58 |
+
h_0 = h_0.unsqueeze(0).repeat(model.text_features.num_layers, 1, 1) # [num_layers, batch_size, hidden_size]
|
| 59 |
+
c_0 = h_0.clone()
|
| 60 |
+
|
| 61 |
+
input_token = torch.full((batch_size,), tokenizer.tok_to_ind['<BOS>'], dtype=torch.long, device=device)
|
| 62 |
+
result_tokens = [[] for _ in range(batch_size)]
|
| 63 |
+
mask = torch.ones(batch_size, dtype=torch.bool, device=device)
|
| 64 |
+
|
| 65 |
+
for _ in range(max_seq_len):
|
| 66 |
+
input_emb = model.text_features.embed(input_token).unsqueeze(1) # [batch_size, 1, embed_dim]
|
| 67 |
+
input_emb = model.text_features.text_to_hidden(input_emb)
|
| 68 |
+
output, (h_0, c_0) = model.text_features.rnn(input_emb, (h_0, c_0)) # [batch_size, 1, hidden_size]
|
| 69 |
+
logits = model.fc_out(output.squeeze(1)) # [batch_size, vocab_size]
|
| 70 |
+
probs = F.softmax(logits, dim=-1) # [batch_size, vocab_size]
|
| 71 |
+
|
| 72 |
+
next_tokens = torch.zeros(batch_size, dtype=torch.long, device=device)
|
| 73 |
+
for i in range(batch_size):
|
| 74 |
+
if not mask[i]:
|
| 75 |
+
continue
|
| 76 |
+
prob = probs[i]
|
| 77 |
+
if top_k is not None:
|
| 78 |
+
sorted_probs, sorted_indices = torch.sort(prob, descending=True)
|
| 79 |
+
sorted_probs = sorted_probs[:top_k]
|
| 80 |
+
sorted_indices = sorted_indices[:top_k]
|
| 81 |
+
sorted_probs = sorted_probs / sorted_probs.sum()
|
| 82 |
+
next_token_idx = torch.multinomial(sorted_probs, 1)
|
| 83 |
+
next_tokens[i] = sorted_indices[next_token_idx]
|
| 84 |
+
elif top_p is not None:
|
| 85 |
+
sorted_probs, sorted_indices = torch.sort(prob, descending=True)
|
| 86 |
+
cumulative_probs = torch.cumsum(sorted_probs, dim=0)
|
| 87 |
+
mask_p = cumulative_probs <= top_p
|
| 88 |
+
sorted_probs = sorted_probs[mask_p]
|
| 89 |
+
sorted_indices = sorted_indices[mask_p]
|
| 90 |
+
sorted_probs = sorted_probs / sorted_probs.sum()
|
| 91 |
+
next_token_idx = torch.multinomial(sorted_probs, 1)
|
| 92 |
+
next_tokens[i] = sorted_indices[next_token_idx]
|
| 93 |
+
else:
|
| 94 |
+
next_tokens[i] = torch.multinomial(prob, 1)
|
| 95 |
+
|
| 96 |
+
token_id = next_tokens[i].item()
|
| 97 |
+
result_tokens[i].append(token_id)
|
| 98 |
+
if token_id == tokenizer.tok_to_ind['<EOS>']:
|
| 99 |
+
mask[i] = False
|
| 100 |
+
|
| 101 |
+
input_token = next_tokens
|
| 102 |
+
if not mask.any():
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
# Декодирование токенов в текст
|
| 106 |
+
result_text = []
|
| 107 |
+
for tokens in result_tokens:
|
| 108 |
+
caption = " ".join([tokenizer.ind_to_tok.get(t, "<UNK>") for t in tokens
|
| 109 |
+
if t not in [tokenizer.tok_to_ind.get("<BOS>", -1),
|
| 110 |
+
tokenizer.tok_to_ind.get("<EOS>", -1),
|
| 111 |
+
tokenizer.tok_to_ind.get("<PAD>", -1)]])
|
| 112 |
+
result_text.append(caption)
|
| 113 |
+
|
| 114 |
+
return result_text[0] if batch_size == 1 else result_text
|
| 115 |
+
|
| 116 |
+
def generate_caption(image):
|
| 117 |
+
image = image.convert("RGB")
|
| 118 |
+
image_tensor = transform(image).unsqueeze(0).to(device)
|
| 119 |
+
caption = generate(model, image_tensor, tokenizer, max_seq_len=config.get("max_len", 20), top_k=5)
|
| 120 |
+
caption = wrap_text(caption, title_width)
|
| 121 |
+
return caption
|
| 122 |
+
|
| 123 |
+
# Создание Gradio-интерфейса
|
| 124 |
+
iface = gr.Interface(
|
| 125 |
+
fn=generate_caption,
|
| 126 |
+
inputs=gr.Image(type="pil"),
|
| 127 |
+
outputs="text",
|
| 128 |
+
title="Image Captioning Demo",
|
| 129 |
+
description="Upload an image to generate a caption."
|
| 130 |
+
)
|
| 131 |
+
iface.launch()
|
model.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torchvision.models as models
|
| 4 |
+
|
| 5 |
+
class img_fe_class(nn.Module):
|
| 6 |
+
def __init__(self):
|
| 7 |
+
super(img_fe_class, self).__init__()
|
| 8 |
+
weights = models.ResNet50_Weights.DEFAULT
|
| 9 |
+
self.resnet = models.resnet50(weights=weights)
|
| 10 |
+
self.resnet = nn.Sequential(*list(self.resnet.children())[:-1])
|
| 11 |
+
for param in self.resnet.parameters():
|
| 12 |
+
param.requires_grad = False
|
| 13 |
+
|
| 14 |
+
def forward(self, imgs):
|
| 15 |
+
features = self.resnet(imgs)
|
| 16 |
+
return features.reshape(features.size(0), -1)
|
| 17 |
+
|
| 18 |
+
class text_fe_class(nn.Module):
|
| 19 |
+
def __init__(self, vocab_size, embedding_dim, hidden_size, num_layers):
|
| 20 |
+
super(text_fe_class, self).__init__()
|
| 21 |
+
self.embedding = nn.Embedding(vocab_size, embedding_dim)
|
| 22 |
+
self.rnn = nn.LSTM(embedding_dim, hidden_size, num_layers, batch_first=True)
|
| 23 |
+
|
| 24 |
+
def forward(self, captions, hidden):
|
| 25 |
+
embeddings = self.embedding(captions)
|
| 26 |
+
outputs, hidden = self.rnn(embeddings, hidden)
|
| 27 |
+
return outputs, hidden
|
| 28 |
+
|
| 29 |
+
class image_captioning_model(nn.Module):
|
| 30 |
+
def __init__(self, vocab_size, embedding_dim, hidden_size, num_layers):
|
| 31 |
+
super(image_captioning_model, self).__init__()
|
| 32 |
+
self.img_fe = img_fe_class()
|
| 33 |
+
self.text_fe = text_fe_class(vocab_size, embedding_dim, hidden_size, num_layers)
|
| 34 |
+
self.fc_out = nn.Linear(hidden_size, vocab_size)
|
| 35 |
+
self.hidden_size = hidden_size
|
| 36 |
+
self.num_layers = num_layers
|
| 37 |
+
self.img_to_hidden = nn.Linear(2048, hidden_size) # 2048 - размер выхода ResNet50
|
| 38 |
+
|
| 39 |
+
def forward(self, imgs, captions):
|
| 40 |
+
img_features = self.img_fe(imgs)
|
| 41 |
+
hidden = self.img_to_hidden(img_features).unsqueeze(0).repeat(self.num_layers, 1, 1)
|
| 42 |
+
cell = torch.zeros_like(hidden) # Для LSTM нужно также cell state
|
| 43 |
+
outputs, _ = self.text_fe(captions, (hidden, cell))
|
| 44 |
+
outputs = self.fc_out(outputs)
|
| 45 |
+
return outputs
|
| 46 |
+
|
| 47 |
+
def generate_caption(self, img, tokenizer, max_len=30, device="cuda"):
|
| 48 |
+
self.eval()
|
| 49 |
+
with torch.no_grad():
|
| 50 |
+
img = img.unsqueeze(0).to(device)
|
| 51 |
+
img_features = self.img_fe(img)
|
| 52 |
+
hidden = self.img_to_hidden(img_features).unsqueeze(0).repeat(self.num_layers, 1, 1)
|
| 53 |
+
cell = torch.zeros_like(hidden)
|
| 54 |
+
caption = [tokenizer.tok_to_ind["<BOS>"]]
|
| 55 |
+
for _ in range(max_len):
|
| 56 |
+
inputs = torch.LongTensor(caption[-1]).unsqueeze(0).unsqueeze(0).to(device)
|
| 57 |
+
outputs, (hidden, cell) = self.text_fe(inputs, (hidden, cell))
|
| 58 |
+
outputs = self.fc_out(outputs[:, -1, :])
|
| 59 |
+
next_token = outputs.argmax(dim=-1).item()
|
| 60 |
+
caption.append(next_token)
|
| 61 |
+
if next_token == tokenizer.tok_to_ind["<EOS>"]:
|
| 62 |
+
break
|
| 63 |
+
return tokenizer.decode(caption)
|