Download model.py from tinylens/tiny-manga-ocr-base: direct link, hf CLI and curl.
- Browser
- Download file 3.33 kB
-
https://huggingface.co/tinylens/tiny-manga-ocr-base/resolve/main/model.py
- Command line
-
hf download hf://tinylens/tiny-manga-ocr-base/model.py
-
curl -L -o model.py https://huggingface.co/tinylens/tiny-manga-ocr-base/resolve/main/model.py
3.33 kB
| """小さな漫画の文字読み取りのモデル。timm の骨格の 1/16 の特徴を記憶にして、小さな Transformer のデコーダが 1 文字ずつ出す。 | |
| 文字の表は kha-white/manga-ocr-base の tokenizer (文字単位、6144 語、Apache-2.0) をそのまま使う。 | |
| """ | |
| import timm | |
| import torch | |
| from torch import nn | |
| PAD, BOS, EOS = 0, 2, 3 # manga-ocr-base の tokenizer の [PAD]、[CLS]、[SEP] | |
| class TinyOCR(nn.Module): | |
| def __init__(self, arch: str, size: int = 224, d: int = 256, layers: int = 4, heads: int = 4, vocab: int = 6144, max_len: int = 128, pretrained: bool = True): | |
| super().__init__() | |
| enc = timm.create_model(arch, pretrained=False, features_only=True) | |
| idx = enc.feature_info.reduction().index(16) # 224 なら 14x14 の特徴 | |
| self.encoder = timm.create_model(arch, pretrained=pretrained, features_only=True, out_indices=(idx,)) | |
| c = self.encoder.feature_info.channels()[0] | |
| n = (size // 16) ** 2 | |
| self.proj = nn.Linear(c, d) | |
| self.enc_pos = nn.Parameter(torch.zeros(1, n, d)) | |
| self.embed = nn.Embedding(vocab, d) | |
| self.pos = nn.Parameter(torch.zeros(1, max_len, d)) | |
| layer = nn.TransformerDecoderLayer(d, heads, 4 * d, dropout=0.1, batch_first=True, norm_first=True) | |
| self.decoder = nn.TransformerDecoder(layer, layers) | |
| self.norm = nn.LayerNorm(d) | |
| self.head = nn.Linear(d, vocab, bias=False) | |
| self.head.weight = self.embed.weight | |
| nn.init.trunc_normal_(self.enc_pos, std=0.02) | |
| nn.init.trunc_normal_(self.pos, std=0.02) | |
| nn.init.trunc_normal_(self.embed.weight, std=0.02) # 出力の重みと共有するので小さく始める | |
| self.max_len = max_len | |
| def encode(self, x: torch.Tensor) -> torch.Tensor: | |
| f = self.encoder(x)[0] | |
| if f.ndim == 4: | |
| f = f.flatten(2).transpose(1, 2) | |
| return self.proj(f) + self.enc_pos | |
| def decode(self, mem: torch.Tensor, ids: torch.Tensor) -> torch.Tensor: | |
| n = ids.shape[1] | |
| mask = torch.triu(torch.full((n, n), float("-inf"), device=ids.device), 1) | |
| # mask は作りからして因果なので、値を比べて確かめる処理 (ONNX への書き出しを止める) を飛ばす | |
| h = self.decoder(self.embed(ids) + self.pos[:, :n], mem, tgt_mask=mask, tgt_is_causal=True) | |
| return self.head(self.norm(h)) | |
| def forward(self, x: torch.Tensor, ids: torch.Tensor) -> torch.Tensor: | |
| return self.decode(self.encode(x), ids) | |
| def greedy(self, x: torch.Tensor, max_len: int | None = None) -> list[list[int]]: | |
| mem = self.encode(x) | |
| ids = torch.full((x.shape[0], 1), BOS, dtype=torch.long, device=x.device) | |
| done = torch.zeros(x.shape[0], dtype=torch.bool, device=x.device) | |
| for _ in range((max_len or self.max_len) - 1): | |
| nxt = self.decode(mem, ids)[:, -1].argmax(-1) | |
| nxt = torch.where(done, torch.full_like(nxt, PAD), nxt) | |
| ids = torch.cat([ids, nxt[:, None]], 1) | |
| done |= nxt == EOS | |
| if done.all(): | |
| break | |
| out = [] | |
| for row in ids[:, 1:].tolist(): | |
| out.append([t for t in row[: row.index(EOS)] if t != PAD] if EOS in row else [t for t in row if t != PAD]) | |
| return out | |