Views
No views yet
1# load dependencies
2import torch
3from transformers import DonutSwinModel, DonutSwinPreTrainedModel,DonutProcessor
4from torch import nn
5from PIL import Image
6
7#
8class DonutForImageClassification(DonutSwinPreTrainedModel):
9 def __init__(self, config):
10 super().__init__(config)
11 self.num_labels = config.num_labels
12 self.swin = DonutSwinModel(config)
13 self.dropout = nn.Dropout(0.5)
14 self.classifier = nn.Linear(self.swin.num_features, config.num_labels)
15
16 def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
17 outputs = self.swin(pixel_values)
18 pooled_output = outputs[1]
19 pooled_output = self.dropout(pooled_output)
20 logits = self.classifier(pooled_output)
21 return logits
22
23sModelName = 'hsarfraz/donut-irs-tax-docs-classifier'
24processor = DonutProcessor.from_pretrained(sModelName)
25model = DonutForImageClassification.from_pretrained(sModelName)
26
27device = 'cuda' if torch.cuda.is_available() else 'cpu'
28model.to(device)
29
30model.eval()
31
32# load test image
33sTestImagePath ='replace this with document image path' # i.e.
34# open image
35img = Image.open(sTestImagePath)
36# resize image to width 1920 and height 2560 - fine tuned model is trained with this width and height
37img_new = img.resize((1920,2560),Image.Resampling.LANCZOS)
38
39# perfoem inference
40predicted_label = ''
41with torch.no_grad():
42 pixel_values = processor(img_new.convert("RGB"), return_tensors="pt").pixel_values
43 print(pixel_values.shape)
44 pixel_values = pixel_values.to(device)
45 outputs = model(pixel_values)
46 logits, predicted = torch.max(outputs.data, 1)
47 pval = predicted.cpu().numpy()[0]
48 predicted_label = model.config.id2label[pval]
49
50print('---------------------------------- ')
51print('Document Image Classification: ',predicted_label)
52
53