Jwalit commited on
Commit
9425176
Β·
verified Β·
1 Parent(s): dcc6dd7

Add complete inference pipeline script

Browse files
Files changed (1) hide show
  1. inference_pipeline.py +155 -0
inference_pipeline.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ KYC Document Cropping & Rotation - Complete Inference Pipeline
4
+
5
+ Models:
6
+ - Segmentation (corner detection): https://huggingface.co/Jwalit/kyc-document-corner-detector
7
+ - Rotation classifier: https://huggingface.co/Jwalit/kyc-document-rotation-classifier
8
+
9
+ Usage:
10
+ python inference_pipeline.py --image path/to/image.jpg --output out.jpg
11
+ """
12
+
13
+ import argparse, warnings
14
+ from pathlib import Path
15
+ import numpy as np
16
+ import cv2
17
+ from PIL import Image
18
+ import torch, torch.nn as nn
19
+ from torchvision import transforms
20
+
21
+ warnings.filterwarnings("ignore")
22
+
23
+ # ── Model Classes ──
24
+ class SegModel(nn.Module):
25
+ def __init__(self):
26
+ super().__init__()
27
+ from torchvision import models
28
+ self.enc = models.mobilenet_v3_small(weights=None).features
29
+ self.dec = nn.Sequential(
30
+ nn.Conv2d(576,256,3,padding=1), nn.ReLU(),
31
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
32
+ nn.Conv2d(256,128,3,padding=1), nn.ReLU(),
33
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
34
+ nn.Conv2d(128,64,3,padding=1), nn.ReLU(),
35
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
36
+ nn.Conv2d(64,32,3,padding=1), nn.ReLU(),
37
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
38
+ nn.Conv2d(32,16,3,padding=1), nn.ReLU(),
39
+ nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False),
40
+ nn.Conv2d(16,1,3,padding=1),
41
+ )
42
+ def forward(self, x):
43
+ return self.dec(self.enc(x))
44
+
45
+ class RotModel(nn.Module):
46
+ def __init__(self):
47
+ super().__init__()
48
+ from torchvision import models
49
+ self.m = models.mobilenet_v3_small(weights=None)
50
+ self.m.classifier[3] = nn.Linear(self.m.classifier[3].in_features, 4)
51
+ def forward(self, x):
52
+ return self.m(x)
53
+
54
+ # ── Preprocessing ──
55
+ seg_tf = transforms.Compose([
56
+ transforms.Resize((224,224)),
57
+ transforms.ToTensor(),
58
+ transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]),
59
+ ])
60
+ rot_tf = transforms.Compose([
61
+ transforms.Resize((224,224)),
62
+ transforms.ToTensor(),
63
+ transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]),
64
+ ])
65
+
66
+ # ── Helpers ──
67
+ def mask_to_corners(mask):
68
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
69
+ if not contours:
70
+ return None
71
+ cnt = max(contours, key=cv2.contourArea)
72
+ peri = cv2.arcLength(cnt, True)
73
+ for eps in [0.02, 0.05, 0.1]:
74
+ approx = cv2.approxPolyDP(cnt, eps*peri, True)
75
+ if len(approx) == 4:
76
+ pts = approx.reshape(4,2).astype(np.float32)
77
+ s, d = pts.sum(axis=1), np.diff(pts, axis=1).flatten()
78
+ rect = np.zeros((4,2), dtype=np.float32)
79
+ rect[0] = pts[np.argmin(s)]
80
+ rect[2] = pts[np.argmax(s)]
81
+ rect[1] = pts[np.argmin(d)]
82
+ rect[3] = pts[np.argmax(d)]
83
+ return rect
84
+ rect = cv2.minAreaRect(cnt)
85
+ return cv2.boxPoints(rect).astype(np.float32)
86
+
87
+ def predict_corners(seg_model, img_path, device='cpu'):
88
+ img = Image.open(img_path).convert('RGB')
89
+ orig_w, orig_h = img.size
90
+ t = seg_tf(img).unsqueeze(0).to(device)
91
+ seg_model.eval()
92
+ with torch.no_grad():
93
+ pred = torch.sigmoid(seg_model(t))[0,0].cpu().numpy()
94
+ mask = (pred > 0.5).astype(np.uint8) * 255
95
+ mask = cv2.resize(mask, (orig_w, orig_h), interpolation=cv2.INTER_NEAREST)
96
+ return mask_to_corners(mask)
97
+
98
+ def predict_rotation(rot_model, img_path, device='cpu'):
99
+ img = Image.open(img_path).convert('RGB')
100
+ t = rot_tf(img).unsqueeze(0).to(device)
101
+ rot_model.eval()
102
+ with torch.no_grad():
103
+ pred = torch.argmax(rot_model(t), 1).item()
104
+ return [0, 90, 180, 270][pred]
105
+
106
+ def crop_and_rotate(img_path, corners, angle):
107
+ img = cv2.imread(str(img_path))
108
+ if img is None:
109
+ return None
110
+ if corners is not None:
111
+ pts = corners.astype(np.float32)
112
+ w = int(max(np.linalg.norm(pts[1]-pts[0]), np.linalg.norm(pts[2]-pts[3])))
113
+ h = int(max(np.linalg.norm(pts[3]-pts[0]), np.linalg.norm(pts[2]-pts[1])))
114
+ dst = np.array([[0,0],[w-1,0],[w-1,h-1],[0,h-1]], dtype=np.float32)
115
+ M = cv2.getPerspectiveTransform(pts, dst)
116
+ cropped = cv2.warpPerspective(img, M, (w, h))
117
+ else:
118
+ cropped = img.copy()
119
+ if angle == 90:
120
+ cropped = cv2.rotate(cropped, cv2.ROTATE_90_COUNTERCLOCKWISE)
121
+ elif angle == 180:
122
+ cropped = cv2.rotate(cropped, cv2.ROTATE_180)
123
+ elif angle == 270:
124
+ cropped = cv2.rotate(cropped, cv2.ROTATE_90_CLOCKWISE)
125
+ return cropped
126
+
127
+ def process_image(img_path, seg_weights, rot_weights, output_path=None, device='cpu'):
128
+ seg_model = SegModel()
129
+ seg_model.load_state_dict(torch.load(seg_weights, map_location=device))
130
+ seg_model.to(device)
131
+ rot_model = RotModel()
132
+ rot_model.load_state_dict(torch.load(rot_weights, map_location=device))
133
+ rot_model.to(device)
134
+ print(f"Processing: {img_path}")
135
+ corners = predict_corners(seg_model, img_path, device)
136
+ angle = predict_rotation(rot_model, img_path, device)
137
+ print(f" Rotation: {angle}Β°, Corners: {corners is not None}")
138
+ result = crop_and_rotate(img_path, corners, angle)
139
+ if output_path:
140
+ cv2.imwrite(str(output_path), result)
141
+ print(f" Saved: {output_path}")
142
+ return result
143
+
144
+ def main():
145
+ parser = argparse.ArgumentParser()
146
+ parser.add_argument("--image", required=True)
147
+ parser.add_argument("--seg-weights", default="pytorch_model.bin")
148
+ parser.add_argument("--rot-weights", required=True)
149
+ parser.add_argument("--output", default="output.jpg")
150
+ parser.add_argument("--device", default="cpu")
151
+ args = parser.parse_args()
152
+ process_image(args.image, args.seg_weights, args.rot_weights, args.output, args.device)
153
+
154
+ if __name__ == "__main__":
155
+ main()