Aff77 commited on
Commit
8a02ba2
·
verified ·
1 Parent(s): 73bec2e

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import string
4
+ from PIL import Image
5
+ import torchvision.transforms as transforms
6
+ from torch import nn
7
+ import torch.nn.functional as F
8
+ from torchvision import models
9
+
10
+ # Device configuration
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+
13
+ # Character mapping
14
+ characters = string.ascii_letters + string.digits
15
+ char_to_idx = {c: i for i, c in enumerate(characters)}
16
+ idx_to_char = {i: c for i, c in enumerate(characters)}
17
+ VOCAB_SIZE = len(characters) + 1 # +1 for blank token for CTC
18
+ MAX_LABEL_LENGTH = 6
19
+ IMG_HEIGHT = 32
20
+ IMG_WIDTH = 128
21
+
22
+ # --------------------------
23
+ # Your Model Architecture
24
+ # --------------------------
25
+ class STN(nn.Module):
26
+ def __init__(self):
27
+ super().__init__()
28
+ self.localization = nn.Sequential(
29
+ nn.Conv2d(1, 8, kernel_size=7),
30
+ nn.MaxPool2d(2, stride=2),
31
+ nn.ReLU(True),
32
+ nn.Conv2d(8, 10, kernel_size=5),
33
+ nn.MaxPool2d(2, stride=2),
34
+ nn.ReLU(True)
35
+ )
36
+
37
+ # Calculate flattened size
38
+ with torch.no_grad():
39
+ dummy = torch.zeros(1, 1, IMG_HEIGHT, IMG_WIDTH)
40
+ out = self.localization(dummy)
41
+ self.flat_size = out.view(1, -1).shape[1]
42
+
43
+ self.fc_loc = nn.Sequential(
44
+ nn.Linear(self.flat_size, 32),
45
+ nn.ReLU(True),
46
+ nn.Linear(32, 6)
47
+ )
48
+
49
+ # Initialize as identity transform
50
+ self.fc_loc[2].weight.data.zero_()
51
+ self.fc_loc[2].bias.data.copy_(torch.tensor([1, 0, 0, 0, 1, 0], dtype=torch.float))
52
+
53
+ def forward(self, x):
54
+ xs = self.localization(x)
55
+ xs = xs.view(xs.size(0), -1)
56
+ theta = self.fc_loc(xs)
57
+ theta = theta.view(-1, 2, 3)
58
+ grid = F.affine_grid(theta, x.size(), align_corners=False)
59
+ x = F.grid_sample(x, grid, align_corners=False)
60
+ return x
61
+
62
+ class FastCRNN(nn.Module):
63
+ def __init__(self, num_classes):
64
+ super().__init__()
65
+ self.stn = STN()
66
+ resnet = models.resnet18(pretrained=False)
67
+ resnet.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
68
+ self.cnn = nn.Sequential(*list(resnet.children())[:-3])
69
+
70
+ self.lstm_input_size = 128 * (IMG_HEIGHT // 8)
71
+ self.rnn = nn.LSTM(self.lstm_input_size, 256, num_layers=2, bidirectional=True, dropout=0.1)
72
+ self.fc = nn.Linear(512, num_classes)
73
+
74
+ def forward(self, x):
75
+ x = self.stn(x)
76
+ x = self.cnn(x)
77
+ x = x.permute(3, 0, 1, 2)
78
+ x = x.contiguous().view(x.size(0), x.size(1), -1)
79
+ x, _ = self.rnn(x)
80
+ x = self.fc(x)
81
+ return x
82
+
83
+ # --------------------------
84
+ # Helper Functions
85
+ # --------------------------
86
+ def decode_predictions(preds):
87
+ """Convert model output to text using CTC decoding"""
88
+ preds = preds.permute(1, 0, 2) # [B, W, C]
89
+ preds = torch.softmax(preds, dim=2)
90
+ preds = torch.argmax(preds, dim=2)
91
+
92
+ texts = []
93
+ for pred in preds:
94
+ # CTC decoding: merge repeated and remove blank (if needed)
95
+ decoded = []
96
+ prev_char = -1
97
+ for char in pred:
98
+ if char != prev_char and char < len(characters): # Skip blank if present
99
+ decoded.append(char.item())
100
+ prev_char = char
101
+ text = ''.join([idx_to_char[c] for c in decoded])
102
+ texts.append(text)
103
+ return texts[0] if len(texts) == 1 else texts
104
+
105
+ # --------------------------
106
+ # Model Loading
107
+ # --------------------------
108
+ def load_model():
109
+ model = FastCRNN(num_classes=VOCAB_SIZE).to(device)
110
+ model.load_state_dict(torch.load('model/fast_crnn.pth', map_location=device))
111
+ model.eval()
112
+ return model
113
+
114
+ model = load_model()
115
+
116
+ # --------------------------
117
+ # Prediction Function
118
+ # --------------------------
119
+ def predict_captcha(image):
120
+ try:
121
+ # Convert Gradio input to PIL Image
122
+ if isinstance(image, dict): # Gradio might pass a dict
123
+ image = image['image'] if 'image' in image else image['data']
124
+ if not isinstance(image, Image.Image):
125
+ image = Image.fromarray(image) if isinstance(image, np.ndarray) else Image.open(image)
126
+
127
+ # Preprocess
128
+ transform = transforms.Compose([
129
+ transforms.Resize((IMG_HEIGHT, IMG_WIDTH)),
130
+ transforms.Grayscale(),
131
+ transforms.ToTensor(),
132
+ transforms.Normalize((0.5,), (0.5,))
133
+ ])
134
+
135
+ image_tensor = transform(image).unsqueeze(0).to(device)
136
+
137
+ # Predict
138
+ with torch.no_grad():
139
+ outputs = model(image_tensor)
140
+ prediction = decode_predictions(outputs)
141
+
142
+ return prediction
143
+
144
+ except Exception as e:
145
+ return f"Error: {str(e)}"
146
+
147
+ # --------------------------
148
+ # Gradio Interface
149
+ # --------------------------
150
+ iface = gr.Interface(
151
+ fn=predict_captcha,
152
+ inputs=gr.Image(type="pil", label="Upload CAPTCHA Image"),
153
+ outputs=gr.Textbox(label="Predicted Text"),
154
+ title="CAPTCHA Recognition with FastCRNN",
155
+ description="Upload a CAPTCHA image to get the predicted text.",
156
+ examples=[
157
+ ["examples/example1.png"],
158
+ ["examples/example2.png"]
159
+ ]
160
+ )
161
+
162
+ if __name__ == "__main__":
163
+ iface.launch()