Views
No views yet
##. Math expressions are guaranteed to be wrapped in brackets \( inline math \) \[ display math \] for easier parsing. This model does not require line-detection or math formula detection.
1# check out https://huggingface.co/microsoft/Phi-3.5-vision-instruct for more details
2
3import torch
4from transformers import AutoModelForCausalLM, AutoProcessor, BitsAndBytesConfig
5from PIL import Image
6import requests
7
8model_id = "yifeihu/TB-OCR-preview-0.1"
9
10DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
12model = AutoModelForCausalLM.from_pretrained(
13 model_id,
14 device_map="cuda",
15 trust_remote_code=True,
16 torch_dtype="auto",
17 _attn_implementation='flash_attention_2',
18 quantization_config=BitsAndBytesConfig(load_in_4bit=True) # Optional: Load model in 4-bit mode to save memory
19)
20
21processor = AutoProcessor.from_pretrained(model_id,
22 trust_remote_code=True,
23 num_crops=16
24)
25
26def phi_ocr(image_url):
27 question = "Convert the text to markdown format." # this is required
28 image = Image.open(requests.get(image_url, stream=True).raw)
29 prompt_message = [{
30 'role': 'user',
31 'content': f'<|image_1|>\n{question}',
32 }]
33
34 prompt = processor.tokenizer.apply_chat_template(prompt_message, tokenize=False, add_generation_prompt=True)
35 inputs = processor(prompt, [image], return_tensors="pt").to("cuda")
36
37 generation_args = {
38 "max_new_tokens": 1024,
39 "temperature": 0.1,
40 "do_sample": False
41 }
42
43 generate_ids = model.generate(**inputs, eos_token_id=processor.tokenizer.eos_token_id, **generation_args
44 )
45
46 generate_ids = generate_ids[:, inputs['input_ids'].shape[1]:]
47 response = processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
48
49 response = response.split("<image_end>")[0] # remove the image_end token
50
51 return response
52
53test_image_url = "https://huggingface.co/yifeihu/TB-OCR-preview-0.1/resolve/main/sample_input_1.png?download=true"
54
55response = phi_ocr(test_image_url)
56
57print(response)