Spaces:
Sleeping
Sleeping
Upload model_prediction_wrapper.py
Browse files- model_prediction_wrapper.py +60 -0
model_prediction_wrapper.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from PIL import Image
|
| 3 |
+
import os
|
| 4 |
+
import torchvision.transforms as transforms
|
| 5 |
+
from Model.OCR_Model import OCRModel
|
| 6 |
+
import torchvision.transforms.functional as F
|
| 7 |
+
import torch.nn.functional as C
|
| 8 |
+
|
| 9 |
+
def prediction_decode(output):
|
| 10 |
+
probabilities = C.softmax(output, dim=1)
|
| 11 |
+
conf, index_t = torch.max(probabilities, dim=1)
|
| 12 |
+
predicted_index = index_t.item()
|
| 13 |
+
conf_p = conf.item() * 100
|
| 14 |
+
labels = [
|
| 15 |
+
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
|
| 16 |
+
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
|
| 17 |
+
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
|
| 18 |
+
'U', 'V', 'W', 'X', 'Y', 'Z',
|
| 19 |
+
'a', 'b', 'd', 'e', 'f', 'g', 'h', 'n', 'q', 'r', 't'
|
| 20 |
+
]
|
| 21 |
+
predicted_char = labels[predicted_index]
|
| 22 |
+
|
| 23 |
+
return predicted_char, conf_p
|
| 24 |
+
|
| 25 |
+
def predict(image):
|
| 26 |
+
print("[Status] Opening Image...")
|
| 27 |
+
try:
|
| 28 |
+
image_input = Image.open(image).convert("L")
|
| 29 |
+
|
| 30 |
+
transform = transforms.Compose([
|
| 31 |
+
transforms.Resize((28, 28)),
|
| 32 |
+
transforms.ToTensor(),
|
| 33 |
+
transforms.Normalize(mean=(0.1751,), std=(0.3332,))
|
| 34 |
+
])
|
| 35 |
+
|
| 36 |
+
x = transform(image_input).unsqueeze(0)
|
| 37 |
+
x = torch.transpose(x, 2, 3)
|
| 38 |
+
|
| 39 |
+
print(f"[AI] AI is thinking...")
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
predicted = model(x)
|
| 42 |
+
|
| 43 |
+
print(f"[AI] Decoding prediction...")
|
| 44 |
+
predicted_digit, conf = prediction_decode(predicted)
|
| 45 |
+
output = f"[AI] I feel {conf:.2f}% confident that I read the digit {predicted_digit}"
|
| 46 |
+
print(output)
|
| 47 |
+
return output
|
| 48 |
+
except Exception as e:
|
| 49 |
+
print(f"[Error] {e}")
|
| 50 |
+
return "Error"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
print("[Status] Loading Model...")
|
| 54 |
+
script_dir = os.path.dirname(os.path.abspath(__file__))
|
| 55 |
+
model_path = os.path.join(script_dir, "OCR_Model.pt")
|
| 56 |
+
state_dic = torch.load(model_path, weights_only=True)
|
| 57 |
+
model = OCRModel()
|
| 58 |
+
model.load_state_dict(state_dic)
|
| 59 |
+
model.eval()
|
| 60 |
+
print("[Info] Model Loaded")
|