import torch
from PIL import Image
from transformers import AutoModelForCausalLM, AutoTokenizer
import os
import time


os.environ["CUDA_VISIBLE_DEVICES"] = "6"

device = "cuda"

tokenizer = AutoTokenizer.from_pretrained("/home/wanglch/projects/GLM-4V/glm-4v-b", trust_remote_code=True)

query = 'OCR这张图片的文字内容'
image = Image.open("/home/wanglch/projects/GLM-4V/images/pic3.jpg").convert('RGB')
inputs = tokenizer.apply_chat_template([{"role": "user", "image": image, "content": query}],
                                       add_generation_prompt=True, tokenize=True, return_tensors="pt",
                                       return_dict=True)  # chat mode

inputs = inputs.to(device)
model = AutoModelForCausalLM.from_pretrained(
    "/home/wanglch/projects/GLM-4V/glm-4v-b",
    torch_dtype=torch.float16,
    low_cpu_mem_usage=True,
    trust_remote_code=True
).to(device).eval()

gen_kwargs = {"max_length": 2500, "do_sample": True, "top_k": 1}
with torch.no_grad():
    outputs = model.generate(**inputs, **gen_kwargs)
    outputs = outputs[:, inputs['input_ids'].shape[1]:]
    print(tokenizer.decode(outputs[0]))