yonigozlan HF staff commited on
Commit
4a5190b
·
verified ·
1 Parent(s): 813b588

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +223 -157
README.md CHANGED
@@ -1,199 +1,265 @@
1
  ---
 
2
  library_name: transformers
3
- tags: []
 
 
 
 
 
 
4
  ---
5
 
6
- # Model Card for Model ID
 
7
 
8
- <!-- Provide a quick summary of what the model is/does. -->
9
 
10
 
 
11
 
12
- ## Model Details
13
 
14
- ### Model Description
15
 
16
- <!-- Provide a longer summary of what this model is. -->
17
 
18
- This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
19
 
20
- - **Developed by:** [More Information Needed]
21
- - **Funded by [optional]:** [More Information Needed]
22
- - **Shared by [optional]:** [More Information Needed]
23
- - **Model type:** [More Information Needed]
24
- - **Language(s) (NLP):** [More Information Needed]
25
- - **License:** [More Information Needed]
26
- - **Finetuned from model [optional]:** [More Information Needed]
27
 
28
- ### Model Sources [optional]
 
29
 
30
- <!-- Provide the basic links for the model. -->
 
31
 
32
- - **Repository:** [More Information Needed]
33
- - **Paper [optional]:** [More Information Needed]
34
- - **Demo [optional]:** [More Information Needed]
35
 
36
- ## Uses
37
 
38
- <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
 
39
 
40
- ### Direct Use
 
 
41
 
42
- <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
 
43
 
44
- [More Information Needed]
 
 
 
 
 
 
45
 
46
- ### Downstream Use [optional]
 
 
47
 
48
- <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
 
50
- [More Information Needed]
 
51
 
52
- ### Out-of-Scope Use
 
 
53
 
54
- <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
 
55
 
56
- [More Information Needed]
57
 
58
- ## Bias, Risks, and Limitations
 
 
 
 
 
 
59
 
60
- <!-- This section is meant to convey both technical and sociotechnical limitations. -->
 
 
61
 
62
- [More Information Needed]
63
 
64
- ### Recommendations
65
 
66
- <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
 
67
 
68
- Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
 
 
69
 
70
- ## How to Get Started with the Model
 
71
 
72
- Use the code below to get started with the model.
 
 
 
 
 
 
73
 
74
- [More Information Needed]
 
 
75
 
76
- ## Training Details
77
 
78
- ### Training Data
 
79
 
80
- <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
 
82
- [More Information Needed]
 
83
 
84
- ### Training Procedure
 
 
85
 
86
- <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
 
 
87
 
88
- #### Preprocessing [optional]
89
-
90
- [More Information Needed]
91
-
92
-
93
- #### Training Hyperparameters
94
-
95
- - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
-
97
- #### Speeds, Sizes, Times [optional]
98
-
99
- <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
-
101
- [More Information Needed]
102
-
103
- ## Evaluation
104
-
105
- <!-- This section describes the evaluation protocols and provides the results. -->
106
-
107
- ### Testing Data, Factors & Metrics
108
-
109
- #### Testing Data
110
-
111
- <!-- This should link to a Dataset Card if possible. -->
112
-
113
- [More Information Needed]
114
-
115
- #### Factors
116
-
117
- <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
-
119
- [More Information Needed]
120
-
121
- #### Metrics
122
-
123
- <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
-
125
- [More Information Needed]
126
-
127
- ### Results
128
-
129
- [More Information Needed]
130
-
131
- #### Summary
132
-
133
-
134
-
135
- ## Model Examination [optional]
136
-
137
- <!-- Relevant interpretability work for the model goes here -->
138
-
139
- [More Information Needed]
140
-
141
- ## Environmental Impact
142
-
143
- <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
-
145
- Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
-
147
- - **Hardware Type:** [More Information Needed]
148
- - **Hours used:** [More Information Needed]
149
- - **Cloud Provider:** [More Information Needed]
150
- - **Compute Region:** [More Information Needed]
151
- - **Carbon Emitted:** [More Information Needed]
152
-
153
- ## Technical Specifications [optional]
154
-
155
- ### Model Architecture and Objective
156
-
157
- [More Information Needed]
158
-
159
- ### Compute Infrastructure
160
-
161
- [More Information Needed]
162
-
163
- #### Hardware
164
-
165
- [More Information Needed]
166
-
167
- #### Software
168
-
169
- [More Information Needed]
170
-
171
- ## Citation [optional]
172
-
173
- <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
-
175
- **BibTeX:**
176
-
177
- [More Information Needed]
178
-
179
- **APA:**
180
-
181
- [More Information Needed]
182
-
183
- ## Glossary [optional]
184
-
185
- <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
-
187
- [More Information Needed]
188
-
189
- ## More Information [optional]
190
-
191
- [More Information Needed]
192
-
193
- ## Model Card Authors [optional]
194
-
195
- [More Information Needed]
196
-
197
- ## Model Card Contact
198
-
199
- [More Information Needed]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ pipeline_tag: image-text-to-text
3
  library_name: transformers
4
+ language:
5
+ - multilingual
6
+ tags:
7
+ - got
8
+ - vision-language
9
+ - ocr2.0
10
+ license: apache-2.0
11
  ---
12
 
13
+ <h1>General OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model - HF Transformers 🤗 implementation
14
+ </h1>
15
 
16
+ [🤗 Spaces Demo](https://huggingface.co/spaces/yonigozlan/GOT-OCR-Transformers) | [🌟GitHub](https://github.com/Ucas-HaoranWei/GOT-OCR2.0/) | [📜Paper](https://arxiv.org/abs/2409.01704)</a>
17
 
18
 
19
+ [Haoran Wei*](https://scholar.google.com/citations?user=J4naK0MAAAAJ&hl=en), Chenglong Liu*, Jinyue Chen, Jia Wang, Lingyu Kong, Yanming Xu, [Zheng Ge](https://joker316701882.github.io/), Liang Zhao, [Jianjian Sun](https://scholar.google.com/citations?user=MVZrGkYAAAAJ&hl=en), [Yuang Peng](https://scholar.google.com.hk/citations?user=J0ko04IAAAAJ&hl=zh-CN&oi=ao), Chunrui Han, [Xiangyu Zhang](https://scholar.google.com/citations?user=yuB-cfoAAAAJ&hl=en)
20
 
 
21
 
 
22
 
23
+ ![image/jpeg](https://cdn-uploads.huggingface.co/production/uploads/6653eee7a2d7a882a805ab95/QCEFY-M_YG3Bp5fn1GQ8X.jpeg)
24
 
 
25
 
26
+ Tips:
 
 
 
 
 
 
27
 
28
+ GOT-OCR2 works on a wide range of tasks, including plain document OCR, scene text OCR, formatted document OCR, and even OCR for tables, charts, mathematical formulas, geometric shapes, molecular formulas and sheet music. While this implementation of the model will only output plain text, the outputs can be further processed to render the desired format, with packages like `pdftex`, `mathpix`, `matplotlib`, `tikz`, `verovio` or `pyecharts`.
29
+ The model can also be used for interactive OCR, where the user can specify the region to be recognized by providing the coordinates or the color of the region's bounding box.
30
 
31
+ This model was contributed by [yonigozlan](https://huggingface.co/yonigozlan).
32
+ The original code can be found [here](https://github.com/Ucas-HaoranWei/GOT-OCR2.0).
33
 
34
+ ## Usage example
 
 
35
 
36
+ ### Plain text inference
37
 
38
+ ```python
39
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
40
 
41
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
42
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", device_map=device)
43
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
44
 
45
+ >>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg"
46
+ >>> inputs = processor(image, return_tensors="pt").to(device)
47
 
48
+ >>> generate_ids = model.generate(
49
+ ... **inputs,
50
+ ... do_sample=False,
51
+ ... tokenizer=processor.tokenizer,
52
+ ... stop_strings="<|im_end|>",
53
+ ... max_new_tokens=4096,
54
+ ... )
55
 
56
+ >>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
57
+ "R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM\nName/Phone Ext. : (...)"
58
+ ```
59
 
60
+ ### Plain text inference batched
61
 
62
+ ```python
63
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
64
 
65
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
66
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", device_map=device)
67
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
68
 
69
+ >>> image1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
70
+ >>> image2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg"
71
 
72
+ >>> inputs = processor([image1, image2], return_tensors="pt").to(device)
73
 
74
+ >>> generate_ids = model.generate(
75
+ ... **inputs,
76
+ ... do_sample=False,
77
+ ... tokenizer=processor.tokenizer,
78
+ ... stop_strings="<|im_end|>",
79
+ ... max_new_tokens=4,
80
+ ... )
81
 
82
+ >>> processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
83
+ ["Reducing the number", "R&D QUALITY"]
84
+ ```
85
 
86
+ ### Formatted text inference
87
 
88
+ GOT-OCR2 can also generate formatted text, such as markdown or LaTeX. Here is an example of how to generate formatted text:
89
 
90
+ ```python
91
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
92
 
93
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
94
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", device_map=device)
95
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
96
 
97
+ >>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/latex.png"
98
+ >>> inputs = processor(image, return_tensors="pt", format=True).to(device)
99
 
100
+ >>> generate_ids = model.generate(
101
+ ... **inputs,
102
+ ... do_sample=False,
103
+ ... tokenizer=processor.tokenizer,
104
+ ... stop_strings="<|im_end|>",
105
+ ... max_new_tokens=4096,
106
+ ... )
107
 
108
+ >>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
109
+ "\\author{\nHanwen Jiang* \\(\\quad\\) Arjun Karpur \\({ }^{\\dagger} \\quad\\) Bingyi Cao \\({ }^{\\dagger} \\quad\\) (...)"
110
+ ```
111
 
112
+ ### Inference on multiple pages
113
 
114
+ Although it might be reasonable in most cases to use a “for loop” for multi-page processing, some text data with formatting across several pages make it necessary to process all pages at once. GOT introduces a multi-page OCR (without “for loop”) feature, where multiple pages can be processed by the model at once, whith the output being one continuous text.
115
+ Here is an example of how to process multiple pages at once:
116
 
 
117
 
118
+ ```python
119
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
120
 
121
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
122
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", device_map=device)
123
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
124
 
125
+ >>> image1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/page1.png"
126
+ >>> image2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/page2.png"
127
+ >>> inputs = processor([image1, image2], return_tensors="pt", multi_page=True, format=True).to(device)
128
 
129
+ >>> generate_ids = model.generate(
130
+ ... **inputs,
131
+ ... do_sample=False,
132
+ ... tokenizer=processor.tokenizer,
133
+ ... stop_strings="<|im_end|>",
134
+ ... max_new_tokens=4096,
135
+ ... )
136
+
137
+ >>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
138
+ "\\title{\nGeneral OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model\n}\n\\author{\nHaoran Wei (...)"
139
+ ```
140
+
141
+ ### Inference on cropped patches
142
+
143
+ GOT supports a 1024×1024 input resolution, which is sufficient for most OCR tasks, such as scene OCR or processing A4-sized PDF pages. However, certain scenarios, like horizontally stitched two-page PDFs commonly found in academic papers or images with unusual aspect ratios, can lead to accuracy issues when processed as a single image. To address this, GOT can dynamically crop an image into patches, process them all at once, and merge the results for better accuracy with such inputs.
144
+ Here is an example of how to process cropped patches:
145
+
146
+ ```python
147
+ >>> import torch
148
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
149
+
150
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
151
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", torch_dtype=torch.bfloat16, device_map=device)
152
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
153
+
154
+ >>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/one_column.png"
155
+ >>> inputs = processor(image, return_tensors="pt", format=True, crop_to_patches=True, max_patches=3).to(device)
156
+
157
+ >>> generate_ids = model.generate(
158
+ ... **inputs,
159
+ ... do_sample=False,
160
+ ... tokenizer=processor.tokenizer,
161
+ ... stop_strings="<|im_end|>",
162
+ ... max_new_tokens=4096,
163
+ ... )
164
+
165
+ >>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
166
+ "on developing architectural improvements to make learnable matching methods generalize.\nMotivated by the above observations, (...)"
167
+ ```
168
+
169
+ ### Inference on a specific region
170
+
171
+ GOT supports interactive OCR, where the user can specify the region to be recognized by providing the coordinates or the color of the region's bounding box. Here is an example of how to process a specific region:
172
+
173
+ ```python
174
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
175
+
176
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
177
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", device_map=device)
178
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
179
+
180
+ >>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
181
+ >>> inputs = processor(image, return_tensors="pt", color="green").to(device) # or box=[x1, y1, x2, y2] for coordinates (image pixels)
182
+
183
+ >>> generate_ids = model.generate(
184
+ ... **inputs,
185
+ ... do_sample=False,
186
+ ... tokenizer=processor.tokenizer,
187
+ ... stop_strings="<|im_end|>",
188
+ ... max_new_tokens=4096,
189
+ ... )
190
+
191
+ >>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
192
+ "You should keep in mind what features from the module should be used, especially \nwhen you’re planning to sell a template."
193
+ ```
194
+
195
+ ### Inference on general OCR data example: sheet music
196
+
197
+ Although this implementation of the model will only output plain text, the outputs can be further processed to render the desired format, with packages like `pdftex`, `mathpix`, `matplotlib`, `tikz`, `verovio` or `pyecharts`.
198
+ Here is an example of how to process sheet music:
199
+
200
+ ```python
201
+ >>> from transformers import AutoProcessor, AutoModelForImageTextToText
202
+ >>> import verovio
203
+
204
+ >>> device = "cuda" if torch.cuda.is_available() else "cpu"
205
+ >>> model = AutoModelForImageTextToText.from_pretrained("yonigozlan/GOT-OCR-2.0-hf", device_map=device)
206
+ >>> processor = AutoProcessor.from_pretrained("yonigozlan/GOT-OCR-2.0-hf")
207
+
208
+ >>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/sheet_music.png"
209
+ >>> inputs = processor(image, return_tensors="pt", format=True).to(device)
210
+
211
+ >>> generate_ids = model.generate(
212
+ ... **inputs,
213
+ ... do_sample=False,
214
+ ... tokenizer=processor.tokenizer,
215
+ ... stop_strings="<|im_end|>",
216
+ ... max_new_tokens=4096,
217
+ ... )
218
+
219
+ >>> outputs = processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
220
+ >>> tk = verovio.toolkit()
221
+ >>> tk.loadData(outputs)
222
+ >>> tk.setOptions(
223
+ ... {
224
+ ... "pageWidth": 2100,
225
+ ... "pageHeight": 800,
226
+ ... "footer": "none",
227
+ ... "barLineWidth": 0.5,
228
+ ... "beamMaxSlope": 15,
229
+ ... "staffLineWidth": 0.2,
230
+ ... "spacingStaff": 6,
231
+ ... }
232
+ ... )
233
+ >>> tk.getPageCount()
234
+ >>> svg = tk.renderToSVG()
235
+ >>> svg = svg.replace('overflow="inherit"', 'overflow="visible"')
236
+ >>> with open("output.svg", "w") as f:
237
+ >>> f.write(svg)
238
+ ```
239
+ <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/sheet_music.svg"
240
+ alt="drawing" width="600"/>
241
+
242
+ ## Citation
243
+
244
+ If you find our work helpful, please consider citing our papers 📝 and liking this project ❤️!
245
+
246
+ ```bib
247
+ @article{wei2024general,
248
+ title={General OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model},
249
+ 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},
250
+ journal={arXiv preprint arXiv:2409.01704},
251
+ year={2024}
252
+ }
253
+ @article{liu2024focus,
254
+ title={Focus Anywhere for Fine-grained Multi-page Document Understanding},
255
+ 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},
256
+ journal={arXiv preprint arXiv:2405.14295},
257
+ year={2024}
258
+ }
259
+ @article{wei2023vary,
260
+ title={Vary: Scaling up the Vision Vocabulary for Large Vision-Language Models},
261
+ 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},
262
+ journal={arXiv preprint arXiv:2312.06109},
263
+ year={2023}
264
+ }
265
+ ```