Spaces:
Sleeping
Sleeping
File size: 4,595 Bytes
95d3f9a 23aa32d 0afc645 919e333 23aa32d c2ae097 23aa32d 95d3f9a 23aa32d 919e333 23aa32d 7c9877c 23aa32d |
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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
import gradio as gr
import random
import os
from typing import Tuple , Dict
import time
import torch
from PIL import Image
import numpy as np
from torchvision import transforms
import torch.nn as nn
from torch.nn.functional import relu
import requests
from io import BytesIO
class GlobalAttention(nn.Module):
def __init__(self, num_channels):
super(GlobalAttention, self).__init__()
self.attention = nn.Sequential(
nn.Conv2d(num_channels, 1, kernel_size=1),
nn.BatchNorm2d(1),
nn.Sigmoid()
)
def forward(self, x):
attention_weights = self.attention(x)
return x * attention_weights
class ModelWithAttention(nn.Module):
def __init__(self, num_characters):
super(ModelWithAttention, self).__init__()
self.conv1 = nn.Conv2d(1, 64, kernel_size=(3, 3), padding='same')
self.bn1 = nn.BatchNorm2d(64)
self.pool = nn.MaxPool2d(kernel_size=(2, 2))
self.conv2 = nn.Conv2d(64, 128, kernel_size=(3, 3), padding='same')
self.bn2 = nn.BatchNorm2d(128)
self.conv3 = nn.Conv2d(128, 256, kernel_size=(3, 3), padding='same')
self.bn3 = nn.BatchNorm2d(256)
self.conv4 = nn.Conv2d(256, 512, kernel_size=(3, 3), padding='same')
self.bn4 = nn.BatchNorm2d(512)
self.pool2 = nn.MaxPool2d(kernel_size=(1, 2))
self.attention = GlobalAttention(512)
self.flatten = nn.Flatten()
self.fc1 = nn.Linear(16384, 512)
self.bn5 = nn.BatchNorm1d(512)
self.dropout1 = nn.Dropout(0.5)
self.fc2 = nn.Linear(512, 512)
self.bn6 = nn.BatchNorm1d(512)
self.dropout2 = nn.Dropout(0.75)
self.output = nn.Linear(512, num_characters)
self.sm = nn.Softmax()
def forward(self, x):
x = self.pool(relu(self.bn1(self.conv1(x))))
x = self.pool(relu(self.bn2(self.conv2(x))))
x = self.pool(relu(self.bn3(self.conv3(x))))
x = self.pool2(relu(self.bn4(self.conv4(x))))
# x = self.attention(x)
x = self.flatten(x)
x = relu(self.bn5(self.fc1(x)))
x = self.dropout1(x)
x = relu(self.bn6(self.fc2(x)))
x = self.dropout2(x)
x = self.output(x)
x = self.sm(x)
return x
device = "cpu"
path = "Captcha(Best).pt"
from torchvision import transforms
model = ModelWithAttention(10).to(device)
model.load_state_dict(torch.load(path , map_location=torch.device('cpu')))
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Grayscale(),
transforms.Resize((64,64))
])
def predict(img= None , link:str = None) -> str:
sizes = [
[15,-5 , 15,27 ],
[15,-5 , 28,40 ],
[15,-5 , 41,53 ],
[15,-5 , 53,65 ],
[15,-5 , 66,78 ]]
answer = ""
if img != None:
imgss = np.array((img))
model.eval()
for size in (sizes):
img = imgss[size[0]:size[1], size[2]:size[3]]
img = Image.fromarray(img)
img = transform(img)
img = img.unsqueeze(0)
answer += str((torch.argmax(model(img.to(device)))).numpy())
return answer , imgss
if link != None:
response = requests.get(str(link))
if response.status_code == 200:
imgss = np.array(Image.open(BytesIO(response.content)))
# print("Image downloaded and converted to numpy array successfully!")
# print(imgss.shape)
model.eval()
for size in (sizes):
img = imgss[size[0]:size[1], size[2]:size[3]]
img = Image.fromarray(img)
img = transform(img)
img = img.unsqueeze(0)
answer += str((torch.argmax(model(img.to(device)))).cpu().numpy())
return answer , imgss
from pathlib import Path
path = "example"
list_path = []
list_paths = os.listdir(path)
for i in list_paths:
list_path.append(os.path.join(path , i))
# print(list_path)
import gradio as gr
title = "GIGA Captcha Solver"
description = "This Model can solve persian numbers Captcha easly"
article = "Created By A.M.Parviz <3"
# Create the Gradio demo
demo = gr.Interface(
fn=predict,
inputs=[gr.Image(type="pil"),
gr.Text()],
outputs=[
gr.Label(num_top_classes=10, label="Predictions"),
gr.Image()
],
examples = [[img_path, ""] for img_path in list_path],
title=title,
description=description,
article=article,
)
demo.launch()
# share=True)
|