import torch
import requests
from PIL import Image
from transformers import Blip2Processor, Blip2ForConditionalGeneration
import gradio as gr


processor = Blip2Processor.from_pretrained("Salesforce/blip2-opt-2.7b")
model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16).to("cuda")


def image2text(image):
    inp = Image.fromarray(image.astype('uint8'), 'RGB')
    text = "a photography of"
    inputs = processor(inp, text, return_tensors="pt").to("cuda", torch.float16)
    out = model.generate(**inputs)

    return processor.decode(out[0], skip_special_tokens=True)


demo = gr.Interface(fn=image2text,
                    inputs='image',
                    outputs='text',
                    title = "image2text",
                    examples = ['soccer.jpg'])


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