Karthikraj Sivakumar commited on
Commit
df3b1c8
Β·
1 Parent(s): 608d548
Files changed (1) hide show
  1. app.py +146 -50
app.py CHANGED
@@ -1,90 +1,174 @@
1
  import gradio as gr
2
  import torch
3
  import torch.nn as nn
 
4
  import cv2
5
  import numpy as np
6
  from PIL import Image
7
 
8
  # ==========================================
9
- # 1. Model Architecture (Copy from notebook)
10
  # ==========================================
11
 
12
- class ResBlock(nn.Module):
13
- def __init__(self, in_channels, out_channels, stride=1):
14
- super().__init__()
 
 
 
 
15
  self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
16
  stride=stride, padding=1, bias=False)
17
  self.bn1 = nn.BatchNorm2d(out_channels)
18
  self.relu = nn.ReLU(inplace=True)
19
- self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3,
20
  stride=1, padding=1, bias=False)
21
  self.bn2 = nn.BatchNorm2d(out_channels)
 
22
 
23
- self.shortcut = nn.Sequential()
24
- if stride != 1 or in_channels != out_channels:
25
- self.shortcut = nn.Sequential(
26
- nn.Conv2d(in_channels, out_channels, kernel_size=1,
27
- stride=stride, bias=False),
28
- nn.BatchNorm2d(out_channels)
29
- )
30
-
31
  def forward(self, x):
32
- out = self.relu(self.bn1(self.conv1(x)))
33
- out = self.bn2(self.conv2(out))
34
- out += self.shortcut(x)
 
 
 
 
 
 
 
 
 
 
 
35
  out = self.relu(out)
 
36
  return out
37
 
38
  class CRNN(nn.Module):
39
- def __init__(self, num_classes, img_height=80, img_width=280, hidden_size=128):
40
- super().__init__()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- # CNN layers
43
  self.conv1 = nn.Sequential(
44
- nn.Conv2d(1, 64, kernel_size=3, padding=1, bias=False),
45
  nn.BatchNorm2d(64),
46
  nn.ReLU(inplace=True)
47
  )
 
 
48
  self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
49
 
50
- self.layer1 = ResBlock(64, 128)
 
 
 
51
  self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
52
 
53
- self.layer2 = ResBlock(128, 256)
54
- self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2)
55
 
56
- self.layer3 = ResBlock(256, 512)
57
- self.pool4 = nn.MaxPool2d(kernel_size=2, stride=2)
58
 
 
 
 
 
 
 
 
59
  self.dropout = nn.Dropout2d(0.2)
60
 
61
- # RNN layers
62
- rnn_input_size = 512 * 5
63
- self.rnn = nn.LSTM(rnn_input_size, hidden_size, num_layers=2,
64
- bidirectional=True, dropout=0.1, batch_first=False)
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- # FC layer
67
  self.fc = nn.Linear(hidden_size * 2, num_classes)
68
- self.log_softmax = nn.LogSoftmax(dim=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
  def forward(self, x):
71
- x = self.conv1(x)
72
- x = self.pool1(x)
73
- x = self.layer1(x)
74
- x = self.pool2(x)
75
- x = self.layer2(x)
76
- x = self.pool3(x)
77
- x = self.layer3(x)
78
- x = self.pool4(x)
79
- conv_out = self.dropout(x)
 
 
 
 
 
 
80
 
81
  batch_size, channels, height, width = conv_out.size()
82
- conv_out = conv_out.view(batch_size, channels * height, width)
83
- conv_out = conv_out.permute(2, 0, 1)
84
 
85
- rnn_out, _ = self.rnn(conv_out)
86
- output = self.fc(rnn_out)
87
- log_probs = self.log_softmax(output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
  return log_probs
90
 
@@ -153,9 +237,15 @@ num_classes = len(CHARS) + 1
153
 
154
  # Load model
155
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
156
- model = CRNN(num_classes=num_classes).to(device)
 
 
 
 
 
 
157
 
158
- # Load checkpoint (update path to your .pth file)
159
  checkpoint = torch.load('best_model.pth', map_location=device)
160
  model.load_state_dict(checkpoint['model_state_dict'])
161
  model.eval()
@@ -213,14 +303,19 @@ demo = gr.Interface(
213
  Upload a CAPTCHA image to see the model's prediction.
214
 
215
  **Model Architecture:**
216
- - ResNet-based CNN feature extraction
217
- - Bidirectional LSTM for sequence modeling
218
  - CTC Loss for alignment-free training
219
 
220
  **Performance:**
221
  - Sequence Accuracy: ~54%
222
  - Character Accuracy: ~86%
223
  - Trained on 9,000 samples with heavy augmentation
 
 
 
 
 
224
  """,
225
  examples=[
226
  # Add example image paths here if you want
@@ -232,4 +327,5 @@ demo = gr.Interface(
232
  )
233
 
234
  if __name__ == "__main__":
235
- demo.launch()
 
 
1
  import gradio as gr
2
  import torch
3
  import torch.nn as nn
4
+ import torch.nn.functional as F
5
  import cv2
6
  import numpy as np
7
  from PIL import Image
8
 
9
  # ==========================================
10
+ # 1. Model Architecture (Match notebook exactly)
11
  # ==========================================
12
 
13
+ class ResidualBlock(nn.Module):
14
+ """
15
+ Residual block with skip connection
16
+ Helps with gradient flow and fine-grained feature discrimination
17
+ """
18
+ def __init__(self, in_channels, out_channels, stride=1, downsample=None):
19
+ super(ResidualBlock, self).__init__()
20
  self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3,
21
  stride=stride, padding=1, bias=False)
22
  self.bn1 = nn.BatchNorm2d(out_channels)
23
  self.relu = nn.ReLU(inplace=True)
24
+ self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3,
25
  stride=1, padding=1, bias=False)
26
  self.bn2 = nn.BatchNorm2d(out_channels)
27
+ self.downsample = downsample
28
 
 
 
 
 
 
 
 
 
29
  def forward(self, x):
30
+ identity = x
31
+
32
+ out = self.conv1(x)
33
+ out = self.bn1(out)
34
+ out = self.relu(out)
35
+
36
+ out = self.conv2(out)
37
+ out = self.bn2(out)
38
+
39
+ # Skip connection (the key to ResNet!)
40
+ if self.downsample is not None:
41
+ identity = self.downsample(x)
42
+
43
+ out += identity # Add residual
44
  out = self.relu(out)
45
+
46
  return out
47
 
48
  class CRNN(nn.Module):
49
+ """
50
+ Convolutional Recurrent Neural Network with ResNet-style CNN
51
+ Architecture: ResNet CNN + Bidirectional LSTM + CTC Loss
52
+ """
53
+ def __init__(
54
+ self,
55
+ img_height=80,
56
+ img_width=280,
57
+ num_classes=63, # 62 alphanumeric + 1 blank
58
+ hidden_size=384,
59
+ num_lstm_layers=2,
60
+ dropout=0.4
61
+ ):
62
+ super(CRNN, self).__init__()
63
+
64
+ self.img_height = img_height
65
+ self.img_width = img_width
66
+ self.num_classes = num_classes
67
+ self.hidden_size = hidden_size
68
 
69
+ # Initial conv: (1, 80, 280) β†’ (64, 80, 280)
70
  self.conv1 = nn.Sequential(
71
+ nn.Conv2d(1, 64, kernel_size=3, stride=1, padding=1, bias=False),
72
  nn.BatchNorm2d(64),
73
  nn.ReLU(inplace=True)
74
  )
75
+
76
+ # Pool1: (64, 80, 280) β†’ (64, 40, 140)
77
  self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
78
 
79
+ # ResBlock layer1: (64, 40, 140) β†’ (128, 40, 140)
80
+ self.layer1 = self._make_layer(64, 128, blocks=2)
81
+
82
+ # Pool2: (128, 40, 140) β†’ (128, 20, 70)
83
  self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
84
 
85
+ # ResBlock layer2: (128, 20, 70) β†’ (256, 20, 70)
86
+ self.layer2 = self._make_layer(128, 256, blocks=2)
87
 
88
+ # Pool3: (256, 20, 70) β†’ (256, 10, 70)
89
+ self.pool3 = nn.MaxPool2d(kernel_size=(2, 1)) # Only height
90
 
91
+ # ResBlock layer3: (256, 10, 70) β†’ (512, 10, 70)
92
+ self.layer3 = self._make_layer(256, 512, blocks=2)
93
+
94
+ # Pool4: (512, 10, 70) β†’ (512, 5, 70)
95
+ self.pool4 = nn.MaxPool2d(kernel_size=(2, 1)) # Only height
96
+
97
+ # Optional dropout
98
  self.dropout = nn.Dropout2d(0.2)
99
 
100
+ # Calculate RNN input size
101
+ # After all conv layers: (512 channels, 5 height, 70 width)
102
+ self.map_to_seq_height = 5
103
+ self.map_to_seq_channels = 512
104
+ self.rnn_input_size = self.map_to_seq_height * self.map_to_seq_channels
105
+
106
+ # Recurrent Layers (Bidirectional LSTM)
107
+ self.rnn = nn.LSTM(
108
+ input_size=self.rnn_input_size,
109
+ hidden_size=hidden_size,
110
+ num_layers=num_lstm_layers,
111
+ bidirectional=True,
112
+ dropout=0.3 if num_lstm_layers > 1 else 0,
113
+ batch_first=False # (T, N, C) format for CTC
114
+ )
115
 
116
+ # Fully Connected Layer
117
  self.fc = nn.Linear(hidden_size * 2, num_classes)
118
+
119
+ def _make_layer(self, in_channels, out_channels, blocks):
120
+ """Create a layer with multiple residual blocks"""
121
+ downsample = None
122
+ if in_channels != out_channels:
123
+ downsample = nn.Sequential(
124
+ nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, bias=False),
125
+ nn.BatchNorm2d(out_channels)
126
+ )
127
+
128
+ layers = []
129
+ layers.append(ResidualBlock(in_channels, out_channels, stride=1, downsample=downsample))
130
+ for _ in range(1, blocks):
131
+ layers.append(ResidualBlock(out_channels, out_channels))
132
+
133
+ return nn.Sequential(*layers)
134
 
135
  def forward(self, x):
136
+ """Forward pass"""
137
+ # CNN Feature Extraction
138
+ x = self.conv1(x) # (N, 64, 80, 280)
139
+ x = self.pool1(x) # (N, 64, 40, 140)
140
+
141
+ x = self.layer1(x) # (N, 128, 40, 140)
142
+ x = self.pool2(x) # (N, 128, 20, 70)
143
+
144
+ x = self.layer2(x) # (N, 256, 20, 70)
145
+ x = self.pool3(x) # (N, 256, 10, 70)
146
+
147
+ x = self.layer3(x) # (N, 512, 10, 70)
148
+ x = self.pool4(x) # (N, 512, 5, 70)
149
+
150
+ conv_out = self.dropout(x) # (N, 512, 5, 70)
151
 
152
  batch_size, channels, height, width = conv_out.size()
 
 
153
 
154
+ # Map to Sequence
155
+ conv_out = conv_out.permute(0, 3, 1, 2) # (N, 70, 512, 5)
156
+ conv_out = conv_out.reshape(batch_size, width, channels * height) # (N, 70, 2560)
157
+
158
+ # Prepare for LSTM
159
+ rnn_input = conv_out.permute(1, 0, 2) # (70, N, 2560)
160
+
161
+ # Bidirectional LSTM
162
+ rnn_output, _ = self.rnn(rnn_input) # (70, N, 768)
163
+
164
+ # Fully Connected Layer
165
+ T, N, hidden = rnn_output.size()
166
+ rnn_output = rnn_output.reshape(T * N, hidden) # (70*N, 768)
167
+ output = self.fc(rnn_output) # (70*N, 63)
168
+ output = output.reshape(T, N, self.num_classes) # (70, N, 63)
169
+
170
+ # Log Softmax for CTC Loss
171
+ log_probs = F.log_softmax(output, dim=2) # (70, N, 63)
172
 
173
  return log_probs
174
 
 
237
 
238
  # Load model
239
  device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
240
+ model = CRNN(
241
+ img_height=80,
242
+ img_width=280,
243
+ num_classes=63,
244
+ hidden_size=384, # IMPORTANT: Must match training
245
+ num_lstm_layers=2
246
+ ).to(device)
247
 
248
+ # Load checkpoint
249
  checkpoint = torch.load('best_model.pth', map_location=device)
250
  model.load_state_dict(checkpoint['model_state_dict'])
251
  model.eval()
 
303
  Upload a CAPTCHA image to see the model's prediction.
304
 
305
  **Model Architecture:**
306
+ - ResNet-based CNN feature extraction (4 layers, 2 blocks each)
307
+ - Bidirectional LSTM (hidden_size=384, 2 layers)
308
  - CTC Loss for alignment-free training
309
 
310
  **Performance:**
311
  - Sequence Accuracy: ~54%
312
  - Character Accuracy: ~86%
313
  - Trained on 9,000 samples with heavy augmentation
314
+
315
+ **Training Details:**
316
+ - 14 iterations of experimentation
317
+ - Data augmentation: rotation, shear, black lines, noise
318
+ - Regularization: dropout, weight decay, early stopping
319
  """,
320
  examples=[
321
  # Add example image paths here if you want
 
327
  )
328
 
329
  if __name__ == "__main__":
330
+ demo.launch()
331
+