Views
No views yet
verovio dependency since most people don't need to OCR musical annotation.float16 if their GPU doesn't support bfloat16.Transformers==4.48.3 so it no longer gives a bunch of warning messages.
torch==2.0.1
torchvision==0.15.2
transformers==4.37.2
tiktoken==0.6.0
verovio==4.3.1
accelerate==0.28.01from transformers import AutoModel, AutoTokenizer
2
3tokenizer = AutoTokenizer.from_pretrained('ucaslcl/GOT-OCR2_0', trust_remote_code=True)
4model = AutoModel.from_pretrained('ucaslcl/GOT-OCR2_0', trust_remote_code=True, low_cpu_mem_usage=True, device_map='cuda', use_safetensors=True, pad_token_id=tokenizer.eos_token_id)
5model = model.eval().cuda()
6
7
8# input your test image
9image_file = 'xxx.jpg'
10
11# plain texts OCR
12res = model.chat(tokenizer, image_file, ocr_type='ocr')
13
14# format texts OCR:
15# res = model.chat(tokenizer, image_file, ocr_type='format')
16
17# fine-grained OCR:
18# res = model.chat(tokenizer, image_file, ocr_type='ocr', ocr_box='')
19# res = model.chat(tokenizer, image_file, ocr_type='format', ocr_box='')
20# res = model.chat(tokenizer, image_file, ocr_type='ocr', ocr_color='')
21# res = model.chat(tokenizer, image_file, ocr_type='format', ocr_color='')
22
23# multi-crop OCR:
24# res = model.chat_crop(tokenizer, image_file, ocr_type='ocr')
25# res = model.chat_crop(tokenizer, image_file, ocr_type='format')
26
27# render the formatted OCR results:
28# res = model.chat(tokenizer, image_file, ocr_type='format', render=True, save_render_file = './demo.html')
29
30print(res)
31
321@article{wei2024general,
2 title={General OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model},
3 author={Wei, Haoran and Liu, Chenglong and Chen, Jinyue and Wang, Jia and Kong, Lingyu and Xu, Yanming and Ge, Zheng and Zhao, Liang and Sun, Jianjian and Peng, Yuang and others},
4 journal={arXiv preprint arXiv:2409.01704},
5 year={2024}
6}
7@article{liu2024focus,
8 title={Focus Anywhere for Fine-grained Multi-page Document Understanding},
9 author={Liu, Chenglong and Wei, Haoran and Chen, Jinyue and Kong, Lingyu and Ge, Zheng and Zhu, Zining and Zhao, Liang and Sun, Jianjian and Han, Chunrui and Zhang, Xiangyu},
10 journal={arXiv preprint arXiv:2405.14295},
11 year={2024}
12}
13@article{wei2023vary,
14 title={Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models},
15 author={Wei, Haoran and Kong, Lingyu and Chen, Jinyue and Zhao, Liang and Ge, Zheng and Yang, Jinrong and Sun, Jianjian and Han, Chunrui and Zhang, Xiangyu},
16 journal={arXiv preprint arXiv:2312.06109},
17 year={2023}
18}1import fitz
2from PIL import Image
3from transformers import AutoModel, AutoTokenizer
4import torch
5
6# The following three lines are optional - removes the last remaining logging message from Transformers.
7# import warnings
8# from transformers import logging as transformers_logging
9# transformers_logging.set_verbosity_error()
10
11MODEL_PATH = "ctranslate2-4you/GOT-OCR2_0-Customized" # Replace with local path if desired
12tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, trust_remote_code=True)
13model = AutoModel.from_pretrained(
14 MODEL_PATH,
15 trust_remote_code=True,
16 low_cpu_mem_usage=True,
17 device_map='cuda',
18 use_safetensors=True,
19 pad_token_id=tokenizer.convert_tokens_to_ids("<|endoftext|>")
20)
21model = model.eval().cuda()
22
23def clean_repetitive_lines(text):
24 """
25 Removes repetitive lines from the OCR output before saving the .txt file. This is necessary because
26 the model sometimes produces OCR artifacts. All duplicates above 2 instances are removed.
27 """
28 lines = text.split('\n')
29 cleaned_lines = []
30 i = 0
31 while i < len(lines):
32 cleaned_lines.append(lines[i])
33 repeat_count = 1
34 j = i + 1
35 while j < len(lines) and lines[j] == lines[i]:
36 repeat_count += 1
37 j += 1
38 if repeat_count > 2:
39 if i + 1 < len(lines):
40 cleaned_lines.append(lines[i + 1])
41 i = j
42 else:
43 i += 1
44 return '\n'.join(cleaned_lines)
45
46@torch.inference_mode()
47def process_pdf_for_ocr(tokenizer, model, pdf_path):
48 pdf_document = fitz.open(pdf_path)
49 full_text = []
50
51 for page_num in range(len(pdf_document)):
52 page = pdf_document[page_num]
53 zoom = 2
54 matrix = fitz.Matrix(zoom, zoom)
55 pix = page.get_pixmap(matrix=matrix)
56 img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
57 # gradio_input=True is used because we're creating images for each page of a .pdf using PyMuPDF and Pillow instead of relying on the model's internal code
58 res = model.chat_crop(tokenizer, img, ocr_type='ocr', gradio_input=True)
59
60 if res.strip():
61 full_text.append(res)
62
63 complete_text = '\n'.join(full_text)
64 cleaned_text = clean_repetitive_lines(complete_text)
65
66 with open("extracted_text_got_ocr.txt", "w", encoding="utf-8") as f:
67 f.write(cleaned_text)
68
69 pdf_document.close()
70 print("Results have been saved to extracted_text_got_ocr.txt")
71
72# Example usage
73pdf_path = "path/to/your/pdf"
74process_pdf_for_ocr(tokenizer, model, pdf_path)