Upload model.py with huggingface_hub
Browse files
model.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
| 3 |
+
from PIL import Image
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import Optional, Union, List
|
| 6 |
+
import json
|
| 7 |
+
|
| 8 |
+
class Pix2TextConfig(PretrainedConfig):
|
| 9 |
+
model_type = "pix2text"
|
| 10 |
+
|
| 11 |
+
def __init__(
|
| 12 |
+
self,
|
| 13 |
+
vocab_size=30000,
|
| 14 |
+
hidden_size=768,
|
| 15 |
+
num_attention_heads=12,
|
| 16 |
+
num_hidden_layers=12,
|
| 17 |
+
intermediate_size=3072,
|
| 18 |
+
max_position_embeddings=512,
|
| 19 |
+
dropout_prob=0.1,
|
| 20 |
+
**kwargs
|
| 21 |
+
):
|
| 22 |
+
super().__init__(**kwargs)
|
| 23 |
+
self.vocab_size = vocab_size
|
| 24 |
+
self.hidden_size = hidden_size
|
| 25 |
+
self.num_attention_heads = num_attention_heads
|
| 26 |
+
self.num_hidden_layers = num_hidden_layers
|
| 27 |
+
self.intermediate_size = intermediate_size
|
| 28 |
+
self.max_position_embeddings = max_position_embeddings
|
| 29 |
+
self.dropout_prob = dropout_prob
|
| 30 |
+
|
| 31 |
+
class Pix2TextModel(PreTrainedModel):
|
| 32 |
+
config_class = Pix2TextConfig
|
| 33 |
+
|
| 34 |
+
def __init__(self, config):
|
| 35 |
+
super().__init__(config)
|
| 36 |
+
self.config = config
|
| 37 |
+
|
| 38 |
+
# Basit bir CNN encoder
|
| 39 |
+
self.image_encoder = torch.nn.Sequential(
|
| 40 |
+
torch.nn.Conv2d(3, 64, 3, padding=1),
|
| 41 |
+
torch.nn.ReLU(),
|
| 42 |
+
torch.nn.MaxPool2d(2),
|
| 43 |
+
torch.nn.Conv2d(64, 128, 3, padding=1),
|
| 44 |
+
torch.nn.ReLU(),
|
| 45 |
+
torch.nn.MaxPool2d(2),
|
| 46 |
+
torch.nn.Conv2d(128, 256, 3, padding=1),
|
| 47 |
+
torch.nn.ReLU(),
|
| 48 |
+
torch.nn.AdaptiveAvgPool2d((8, 8)),
|
| 49 |
+
torch.nn.Flatten(),
|
| 50 |
+
torch.nn.Linear(256 * 8 * 8, config.hidden_size)
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Text decoder
|
| 54 |
+
self.text_decoder = torch.nn.Sequential(
|
| 55 |
+
torch.nn.Linear(config.hidden_size, config.intermediate_size),
|
| 56 |
+
torch.nn.ReLU(),
|
| 57 |
+
torch.nn.Dropout(config.dropout_prob),
|
| 58 |
+
torch.nn.Linear(config.intermediate_size, config.vocab_size)
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Basit tokenizer için vocab
|
| 62 |
+
self.vocab = {str(i): i for i in range(10)} # 0-9 rakamları
|
| 63 |
+
self.vocab.update({chr(i): i+10 for i in range(ord('a'), ord('z')+1)}) # a-z
|
| 64 |
+
self.vocab.update({chr(i): i+36 for i in range(ord('A'), ord('Z')+1)}) # A-Z
|
| 65 |
+
self.vocab.update({' ': 62, '.': 63, ',': 64, '!': 65, '?': 66})
|
| 66 |
+
self.inv_vocab = {v: k for k, v in self.vocab.items()}
|
| 67 |
+
|
| 68 |
+
def forward(self, pixel_values, labels=None):
|
| 69 |
+
# Görüntüyü encode et
|
| 70 |
+
image_features = self.image_encoder(pixel_values)
|
| 71 |
+
|
| 72 |
+
# Text'e decode et
|
| 73 |
+
logits = self.text_decoder(image_features)
|
| 74 |
+
|
| 75 |
+
loss = None
|
| 76 |
+
if labels is not None:
|
| 77 |
+
loss_fct = torch.nn.CrossEntropyLoss()
|
| 78 |
+
loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
|
| 79 |
+
|
| 80 |
+
return {"loss": loss, "logits": logits}
|
| 81 |
+
|
| 82 |
+
def predict(self, image: Union[Image.Image, np.ndarray]) -> str:
|
| 83 |
+
"""Görüntüden metin çıkarma fonksiyonu"""
|
| 84 |
+
if isinstance(image, Image.Image):
|
| 85 |
+
image = np.array(image)
|
| 86 |
+
|
| 87 |
+
# Görüntüyü ön işle
|
| 88 |
+
if len(image.shape) == 3:
|
| 89 |
+
image = torch.tensor(image).permute(2, 0, 1).float() / 255.0
|
| 90 |
+
else:
|
| 91 |
+
image = torch.tensor(image).unsqueeze(0).float() / 255.0
|
| 92 |
+
|
| 93 |
+
image = image.unsqueeze(0) # Batch dimension
|
| 94 |
+
|
| 95 |
+
with torch.no_grad():
|
| 96 |
+
outputs = self.forward(image)
|
| 97 |
+
logits = outputs["logits"]
|
| 98 |
+
|
| 99 |
+
# En yüksek olasılıklı tokenları seç
|
| 100 |
+
predicted_ids = torch.argmax(logits, dim=-1)
|
| 101 |
+
|
| 102 |
+
# Token'ları metne çevir
|
| 103 |
+
text = ""
|
| 104 |
+
for token_id in predicted_ids[0][:10]: # İlk 10 token
|
| 105 |
+
if token_id.item() in self.inv_vocab:
|
| 106 |
+
text += self.inv_vocab[token_id.item()]
|
| 107 |
+
|
| 108 |
+
return text
|