|
| 1 | +from typing import Optional |
| 2 | +import os |
| 3 | +import torch |
| 4 | +from torch import nn |
| 5 | +import numpy as np |
| 6 | +import json |
| 7 | + |
| 8 | +try: |
| 9 | + from torch.utils.data.dataloader import default_collate |
| 10 | +except ImportError: |
| 11 | + from torch.utils.data import default_collate |
| 12 | +from torchvision import models, transforms |
| 13 | +from huggingface_hub import hf_hub_url, cached_download |
| 14 | + |
| 15 | +from DPF.filters.utils import FP16Module, identical_collate_fn |
| 16 | +from DPF.utils import read_image_rgb_from_bytes |
| 17 | +from .img_filter import ImageFilter |
| 18 | + |
| 19 | +from .ocr_model.utils import AttnLabelConverter |
| 20 | +from .ocr_model.dataset import AlignCollate |
| 21 | +from .ocr_model.model import Model |
| 22 | + |
| 23 | + |
| 24 | +class Options: |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +class OCRFilter(ImageFilter): |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + weights_path: str, |
| 33 | + model_name: Optional[str] = None, |
| 34 | + device: str = "cuda:0", |
| 35 | + workers: int = 16, |
| 36 | + pad: int = 5, |
| 37 | + pbar: bool = True, |
| 38 | + ): |
| 39 | + super().__init__(pbar) |
| 40 | + |
| 41 | + self.num_workers = workers |
| 42 | + self.batch_size = 1 |
| 43 | + self.device = device |
| 44 | + |
| 45 | + self.weights_path = weights_path |
| 46 | + self.model_name = model_name or os.path.basename(self.weights_path).split('.')[0] |
| 47 | + # load model |
| 48 | + self.opt = Options() |
| 49 | + self.opt.workers = 4 |
| 50 | + self.opt.batch_size = 192 |
| 51 | + self.opt.batch_max_length = 32 |
| 52 | + self.opt.imgH = 32 |
| 53 | + self.opt.imgW = 100 |
| 54 | + self.opt.rgb = False |
| 55 | + self.opt.character = '0123456789abcdefghijklmnopqrstuvwxyz' |
| 56 | + self.opt.sensitive = False |
| 57 | + self.opt.PAD = False |
| 58 | + self.opt.Transformation = "TPS" |
| 59 | + self.opt.FeatureExtraction = "ResNet" |
| 60 | + self.opt.SequenceModeling = "BiLSTM" |
| 61 | + self.opt.Prediction = "Attn" |
| 62 | + self.opt.num_fiducial = 20 |
| 63 | + self.opt.input_channel = 1 |
| 64 | + self.opt.output_channel = 512 |
| 65 | + self.opt.hidden_size = 256 |
| 66 | + |
| 67 | + self.converter = AttnLabelConverter(self.opt.character) |
| 68 | + self.opt.num_class = len(self.converter.character) |
| 69 | + |
| 70 | + self.model = Model(self.opt) |
| 71 | + weights = torch.load(self.weights_path) |
| 72 | + keys = list(weights.keys()) |
| 73 | + for key in keys: |
| 74 | + weights[key.lstrip('module.')] = weights[key] |
| 75 | + weights.pop(key) |
| 76 | + |
| 77 | + self.model.load_state_dict(weights) |
| 78 | + self.model.to(self.device) |
| 79 | + self.model.eval() |
| 80 | + |
| 81 | + self.AlignCollate = AlignCollate(imgH=self.opt.imgH, imgW=self.opt.imgW, keep_ratio_with_pad=self.opt.PAD) |
| 82 | + # |
| 83 | + self.text_box_col = "text_boxes" |
| 84 | + self.ocr_col = f"OCR_{self.model_name}" |
| 85 | + |
| 86 | + self.schema = ["image_path", self.ocr_col] |
| 87 | + self.dataloader_kwargs = { |
| 88 | + "num_workers": self.num_workers, |
| 89 | + "batch_size": self.batch_size, |
| 90 | + "preprocess_f": self.preprocess, |
| 91 | + "collate_fn": lambda x: x, |
| 92 | + "drop_last": False, |
| 93 | + "cols_to_return": [self.text_box_col], |
| 94 | + } |
| 95 | + |
| 96 | + def preprocess(self, img_bytes: bytes, data: dict): |
| 97 | + image_path = data["image_path"] |
| 98 | + boxes = json.loads(data[self.text_box_col]) |
| 99 | + pil_img = read_image_rgb_from_bytes(img_bytes).convert('L') |
| 100 | + return image_path, pil_img, boxes |
| 101 | + |
| 102 | + def process_batch(self, batch) -> dict: |
| 103 | + df_batch_labels = self._generate_dict_from_schema() |
| 104 | + image_path, pil_img, boxes = batch[0] |
| 105 | + w, h = pil_img.size |
| 106 | + |
| 107 | + input_data = [] |
| 108 | + for box in boxes: |
| 109 | + left = max(box[0][0], 0) |
| 110 | + upper = max(box[0][1], 0) |
| 111 | + right = min(box[1][0], w) |
| 112 | + lower = min(box[1][1], h) |
| 113 | + if upper > lower: |
| 114 | + upper, lower = lower, upper |
| 115 | + if left > right: |
| 116 | + left, right = right, left |
| 117 | + |
| 118 | + crop = pil_img.crop( |
| 119 | + (left, upper, right, lower) |
| 120 | + ) |
| 121 | + input_data.append((crop, '')) |
| 122 | + |
| 123 | + if len(input_data) == 0: |
| 124 | + df_batch_labels[self.ocr_col].append("[]") |
| 125 | + df_batch_labels["image_path"].append(image_path) |
| 126 | + return df_batch_labels |
| 127 | + |
| 128 | + data_preproc = self.AlignCollate(input_data) |
| 129 | + image_tensors = data_preproc[0] |
| 130 | + |
| 131 | + batch_size = image_tensors.size(0) |
| 132 | + image = image_tensors.to(self.device) |
| 133 | + length_for_pred = torch.IntTensor([self.opt.batch_max_length] * batch_size).to(self.device) |
| 134 | + text_for_pred = torch.LongTensor(batch_size, self.opt.batch_max_length + 1).fill_(0).to(self.device) |
| 135 | + |
| 136 | + preds = self.model(image, text_for_pred, is_train=False) |
| 137 | + _, preds_index = preds.max(2) |
| 138 | + preds_str = self.converter.decode(preds_index, length_for_pred) |
| 139 | + preds_str = [s.replace('[s]', '') for s in preds_str] |
| 140 | + |
| 141 | + res = [] |
| 142 | + for box, prediction in zip(boxes, preds_str): |
| 143 | + res.append((box, prediction)) |
| 144 | + |
| 145 | + df_batch_labels[self.ocr_col].append(json.dumps(res)) |
| 146 | + df_batch_labels["image_path"].append(image_path) |
| 147 | + |
| 148 | + return df_batch_labels |
0 commit comments