|
import gradio as gr |
|
from transformers import TrOCRProcessor, VisionEncoderDecoderModel |
|
import requests |
|
from PIL import Image |
|
from craft_text_detector import ( |
|
read_image, |
|
load_craftnet_model, |
|
load_refinenet_model, |
|
get_prediction, |
|
export_detected_regions, |
|
export_extra_results, |
|
empty_cuda_cache |
|
) |
|
from craft_text_detector import Craft |
|
import torch |
|
import numpy as np |
|
|
|
processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-handwritten") |
|
model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-handwritten") |
|
craft = Craft(output_dir=None, |
|
crop_type="poly", |
|
export_extra=False, |
|
link_threshold=0.1, |
|
text_threshold=0.3, |
|
cuda=torch.cuda.is_available()) |
|
|
|
|
|
|
|
urls = ['https://cdn.shopify.com/s/files/1/0275/6457/2777/files/Penwritten_2048x.jpg'] |
|
for idx, url in enumerate(urls): |
|
image = Image.open(requests.get(url, stream=True).raw) |
|
image.save(f"image_{idx}.png") |
|
|
|
def process_image(image): |
|
img = np.array(image) |
|
prediction_result = craft.detect_text(img) |
|
text = [] |
|
for i,j in enumerate(prediction_result['boxes']): |
|
roi = img[int(prediction_result['boxes'][i][0][1]): int(prediction_result['boxes'][i][2][1]), |
|
int(prediction_result['boxes'][i][0][0]): int(prediction_result['boxes'][i][2][0])] |
|
image = Image.fromarray(roi).convert("RGB") |
|
pixel_values = processor(image, return_tensors="pt").pixel_values |
|
generated_ids = model.generate(pixel_values) |
|
generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] |
|
text.append(generated_text) |
|
print('line ' + str(i) + ' has been recoginized') |
|
|
|
generated_text = ('\n').join(text) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return generated_text |
|
|
|
title = "Interactive demo: TrOCR" |
|
description = "Demo for Microsoft's TrOCR, an encoder-decoder model consisting of an image Transformer encoder and a text Transformer decoder for state-of-the-art optical character recognition (OCR) on single-text line images. This particular model is fine-tuned on IAM, a dataset of annotated handwritten images. To use it, simply upload an image or use the example image below and click 'submit'. Results will show up in a few seconds." |
|
article = "<p style='text-align: center'><a href='https://arxiv.org/abs/2109.10282'>TrOCR: Transformer-based Optical Character Recognition with Pre-trained Models</a> | <a href='https://github.com/microsoft/unilm/tree/master/trocr'>Github Repo</a></p>" |
|
examples =[["image_0.png"]] |
|
|
|
iface = gr.Interface(fn=process_image, |
|
inputs=gr.inputs.Image(type="pil"), |
|
outputs=gr.outputs.Textbox(), |
|
title=title, |
|
description=description, |
|
article=article, |
|
examples=examples) |
|
iface.launch(debug=True) |
|
|