import os
os.system('pip install paddlepaddle==2.4.2')
# os.system('pip install paddlepaddle==0.0.0 -f https://www.paddlepaddle.org.cn/whl/linux/cpu-mkl/develop.html')
os.system('pip install paddleocr')
from paddleocr import PaddleOCR, draw_ocr
from PIL import Image
import gradio as gr
import torch

torch.hub.download_url_to_file('https://i.imgur.com/aqMBT0i.jpg', 'example.jpg')

def inference(img, lang):
    ocr = PaddleOCR(use_angle_cls=True, lang=lang,use_gpu=False)
    img_path = img
    result = ocr.ocr(img_path, cls=True)[0]

    boxes = [line[0] for line in result]
    txts = [line[1][0] for line in result]
    #scores = [line[1][1] for line in result]
    
    image = Image.open(img_path).convert('RGB')
    im_show = draw_ocr(image, boxes, txts=None, #scores=None, # https://github.com/PaddlePaddle/PaddleOCR/blob/release/2.7/tools/infer/utility.py#L365
                       font_path='simfang.ttf')
    im_show = Image.fromarray(im_show)
    im_show.save('result.jpg')
    
    return 'result.jpg', '\n'.join(txts)
    
    # return 'result.jpg'

title = 'PaddleOCR'
description = 'PaddleOCR demo supports Spanish and English'
article = ""
examples = [['english.png','en'],['spanish.png','es']]
css = ".output_image, .input_image {height: 40rem !important; width: 100% !important;}"
app = gr.Interface(
    inference,
    [gr.Image(type='filepath', label='Input'),gr.Dropdown(choices=['Spanish', 'English'], type="value", value='ch', label='language')],
    # gr.outputs.Image(type='file', label='Output'),
    outputs=["image", "text"],
    title=title,
    description=description,
    article=article,
    examples=examples,
    css=css,
    # enable_queue=True
    )
app.queue(max_size=10)
app.launch(debug=True)