|
|
|
|
|
import gradio as gr |
|
import torch |
|
from PIL import Image |
|
from model import load_model |
|
from utils import preprocess_image, decode_predictions |
|
import os |
|
|
|
|
|
MODEL_PATH = "finetuned_recog_model.pth" |
|
FONT_PATH = "NotoSansEthiopic-Regular.ttf" |
|
|
|
|
|
if not os.path.exists(MODEL_PATH): |
|
raise FileNotFoundError(f"Model file not found at {MODEL_PATH}. Please provide the correct path.") |
|
|
|
|
|
if not os.path.exists(FONT_PATH): |
|
raise FileNotFoundError(f"Font file not found at {FONT_PATH}. Please provide the correct path.") |
|
|
|
|
|
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') |
|
model = load_model(MODEL_PATH, device=device) |
|
|
|
def recognize_text(image: Image.Image) -> str: |
|
""" |
|
Function to recognize text from an image. |
|
""" |
|
if image is None: |
|
return "No image provided." |
|
|
|
|
|
input_tensor = preprocess_image(image).unsqueeze(0).to(device) |
|
|
|
|
|
with torch.no_grad(): |
|
log_probs = model(input_tensor) |
|
|
|
|
|
recognized_texts = decode_predictions(log_probs) |
|
|
|
|
|
return recognized_texts[0] |
|
|
|
|
|
iface = gr.Interface( |
|
fn=recognize_text, |
|
inputs=gr.Image(type="pil", label="Upload Image"), |
|
outputs=gr.Textbox(label="Recognized Amharic Text"), |
|
title="Amharic Text Recognition", |
|
description="Upload an image containing Amharic text, and the model will recognize and display the text." |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
iface.launch() |
|
|