File size: 1,201 Bytes
83c00db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7952898
 
83c00db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
from PIL import Image
from models.base import OCRModel
from transformers import AutoModelForVision2Seq, AutoProcessor, pipeline

class TrOCROCR(OCRModel):
    """
    TrOCR implementation using Hugging Face
    """

    def __init__(
        self,
        model_name: str = "microsoft/trocr-base-handwritten",
        device: str | None = None,
    ):
        self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")

        self.processor = AutoProcessor.from_pretrained(model_name)
        self.model = AutoModelForVision2Seq.from_pretrained(model_name)
        # self.model = AutoModelForVision2Seq.from_pretrained(model_name, torch_dtype=torch.float16)
        self.model.to(self.device)
        self.model.eval()

    @torch.no_grad()
    def predict(self, image: Image.Image) -> str:
        # image = preprocess(image)

        pixel_values = self.processor(
            images=image,
            return_tensors="pt"
        ).pixel_values.to(self.device)

        generated_ids = self.model.generate(pixel_values)
        text = self.processor.batch_decode(
            generated_ids,
            skip_special_tokens=True
        )[0]

        return text.strip()