simple_ocr / app.py
scking13's picture
Update app.py
2dd1d73 verified
raw
history blame contribute delete
No virus
1.45 kB
#IMPORTS
import fastai
from fastai.vision.all import *
import gradio as gr
# FILE NAME OF PRETRAINED MODEL
model_name = 'ocr_2.pkl'
# LOAD MODEL
learn = load_learner(model_name)
# RETRIEVE VOCABULARY
categories = learn.dls.vocab
#print('-- MODEL VOCABULARY --')
#print(learn.dls.vocab)
# MAIN FUNCTION (To categorize our image)
def checkImage(test_image):
img = PILImage.create(test_image)
# prediction = the models most likely category as text
# pred_idx = index in the categories list where the prediction is
# probabilities is a rank 2 tensor with the first rank being the probability
# and the second rank being the index of that category
prediction, pred_idx, probabilities = learn.predict(img)
# This retrieves just the top 5 results
top_5_probabilities, top_5_indices = probabilities.topk(5)
#print(probabilities.topk(5))
#print('-- TOP 5 PROBABILITIES --')
result = {}
for idx, probability in zip(top_5_indices, top_5_probabilities):
print(f"Type: {categories[idx]}- Probability: {probabilities[idx].item():.2f}")
result[f"{categories[idx]}"] = f"{probabilities[idx].item():.4f}"
#print('----------------')
return prediction,result
# USER INTERFACE BUILDER
iface = gr.Interface(
fn=checkImage,
title="SK Simple OCR",
inputs="image",
outputs=["label","label"]
)
# LAUNCHER share=True means its publically available
iface.launch(share=True)