from transformers import DonutProcessor, VisionEncoderDecoderModel
import gradio as gr
from PIL import Image
import torch
import re


processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa")
model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa")


def vqa(image, question):
    inp = Image.fromarray(image.astype('uint8'), 'RGB')
    pixel_values = processor(inp, return_tensors="pt").pixel_values
    task_prompt = "{user_input}"
    prompt = task_prompt.replace("{user_input}", question)
    decoder_input_ids = processor.tokenizer(prompt, add_special_tokens=False, return_tensors="pt")["input_ids"]
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model.to(device)

    outputs = model.generate(pixel_values.to(device),
                               decoder_input_ids=decoder_input_ids.to(device),
                               max_length=model.decoder.config.max_position_embeddings,
                               early_stopping=True,
                               pad_token_id=processor.tokenizer.pad_token_id,
                               eos_token_id=processor.tokenizer.eos_token_id,
                               use_cache=True,
                               num_beams=1,
                               bad_words_ids=[[processor.tokenizer.unk_token_id]],
                               return_dict_in_generate=True,
                               output_scores=True)


    seq = processor.batch_decode(outputs.sequences)[0]
    seq = seq.replace(processor.tokenizer.eos_token, "").replace(processor.tokenizer.pad_token, "")
    seq = re.sub(r"<.*?>", "", seq, count=1).strip()

    return processor.token2json(seq)


demo = gr.Interface(fn=vqa,
                    inputs=['image', 'text'],
                    outputs='text',
                    title = "vqa",
                    examples = [['income.png', 'What are the 2020 net sales?'], ['invoice.png','What is the invoice number?']])


if __name__ == "__main__":
    demo.queue(concurrency_count=3).launch(server_name = "0.0.0.0", server_port = 7026)
