first commit
Some checks failed
Self-hosted runner (nightly-past-ci-caller) / Get number (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.11 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.10 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.9 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.8 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.7 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.6 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.5 (push) Has been cancelled
Self-hosted runner (benchmark) / Benchmark (aws-g5-4xlarge-cache) (push) Has been cancelled
Build documentation / build (push) Has been cancelled
Build documentation / build_other_lang (push) Has been cancelled
CodeQL Security Analysis / CodeQL Analysis (push) Has been cancelled
New model PR merged notification / Notify new model (push) Has been cancelled
PR CI / pr-ci (push) Has been cancelled
Slow tests on important models (on Push - A10) / Get all modified files (push) Has been cancelled
Secret Leaks / trufflehog (push) Has been cancelled
Update Transformers metadata / build_and_package (push) Has been cancelled
Slow tests on important models (on Push - A10) / Model CI (push) Has been cancelled
Check Tiny Models / Check tiny models (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Model CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Pipeline CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Example CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / DeepSpeed CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI - Flash Attn / Setup (push) Has been cancelled
Nvidia CI - Flash Attn / Model CI (push) Has been cancelled
Nvidia CI / Setup (push) Has been cancelled
Nvidia CI / Model CI (push) Has been cancelled
Nvidia CI / Torch pipeline CI (push) Has been cancelled
Nvidia CI / Example CI (push) Has been cancelled
Nvidia CI / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI / DeepSpeed CI (push) Has been cancelled
Nvidia CI / Quantization CI (push) Has been cancelled
Nvidia CI / Kernels CI (push) Has been cancelled
Doctests / Setup (push) Has been cancelled
Doctests / Call doctest jobs (push) Has been cancelled
Doctests / Send results to webhook (push) Has been cancelled
Extras Smoke Test / Get supported Python versions (push) Has been cancelled
Extras Smoke Test / Test extras on Python ${{ matrix.python-version }} (push) Has been cancelled
Extras Smoke Test / Check Slack token availability (push) Has been cancelled
Extras Smoke Test / Notify failures to Slack (push) Has been cancelled
Self-hosted runner (AMD scheduled CI caller) / Trigger Scheduled AMD CI (push) Has been cancelled
Stale Bot / Close Stale Issues (push) Has been cancelled

This commit is contained in:
陈赣
2026-06-05 16:53:03 +08:00
commit 06f1fd69a6
6047 changed files with 1895387 additions and 0 deletions

View File

View File

@@ -0,0 +1,297 @@
# Copyright 2023 HuggingFace Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import numpy as np
from huggingface_hub import hf_hub_download
from transformers.image_utils import SizeDict, load_image
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
from ...test_processing_common import url_to_local_path
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
class NougatImageProcessingTester:
def __init__(
self,
parent,
batch_size=7,
num_channels=3,
image_size=18,
min_resolution=30,
max_resolution=400,
do_crop_margin=True,
do_resize=True,
size=None,
do_thumbnail=True,
do_align_long_axis: bool = False,
do_pad=True,
do_normalize: bool = True,
image_mean=[0.5, 0.5, 0.5],
image_std=[0.5, 0.5, 0.5],
):
size = size if size is not None else {"height": 20, "width": 20}
self.parent = parent
self.batch_size = batch_size
self.num_channels = num_channels
self.image_size = image_size
self.min_resolution = min_resolution
self.max_resolution = max_resolution
self.do_crop_margin = do_crop_margin
self.do_resize = do_resize
self.size = size
self.do_thumbnail = do_thumbnail
self.do_align_long_axis = do_align_long_axis
self.do_pad = do_pad
self.do_normalize = do_normalize
self.image_mean = image_mean
self.image_std = image_std
self.data_format = "channels_first"
self.input_data_format = "channels_first"
def prepare_image_processor_dict(self):
return {
"do_crop_margin": self.do_crop_margin,
"do_resize": self.do_resize,
"size": self.size,
"do_thumbnail": self.do_thumbnail,
"do_align_long_axis": self.do_align_long_axis,
"do_pad": self.do_pad,
"do_normalize": self.do_normalize,
"image_mean": self.image_mean,
"image_std": self.image_std,
}
def expected_output_image_shape(self, images):
return self.num_channels, self.size["height"], self.size["width"]
def prepare_dummy_image(self):
revision = "ec57bf8c8b1653a209c13f6e9ee66b12df0fc2db"
filepath = hf_hub_download(
repo_id="hf-internal-testing/fixtures_docvqa",
filename="nougat_pdf.png",
repo_type="dataset",
revision=revision,
)
image = Image.open(filepath).convert("RGB")
return image
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
return prepare_image_inputs(
batch_size=self.batch_size,
num_channels=self.num_channels,
min_resolution=self.min_resolution,
max_resolution=self.max_resolution,
equal_resolution=equal_resolution,
numpify=numpify,
torchify=torchify,
)
@require_torch
@require_vision
class NougatImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
def setUp(self):
super().setUp()
self.image_processor_tester = NougatImageProcessingTester(self)
@property
def image_processor_dict(self):
return self.image_processor_tester.prepare_image_processor_dict()
def test_image_processor_properties(self):
for image_processing_class in self.image_processing_classes.values():
image_processing = image_processing_class(**self.image_processor_dict)
self.assertTrue(hasattr(image_processing, "do_resize"))
self.assertTrue(hasattr(image_processing, "size"))
self.assertTrue(hasattr(image_processing, "do_normalize"))
self.assertTrue(hasattr(image_processing, "image_mean"))
self.assertTrue(hasattr(image_processing, "image_std"))
def test_image_processor_from_dict_with_kwargs(self):
for image_processing_class in self.image_processing_classes.values():
image_processor = image_processing_class(**self.image_processor_dict)
self.assertEqual(image_processor.size, {"height": 20, "width": 20})
kwargs = dict(self.image_processor_dict)
kwargs.pop("size", None)
image_processor = image_processing_class(**kwargs, size=42)
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
def test_expected_output(self):
dummy_image = self.image_processor_tester.prepare_dummy_image()
for image_processing_class in self.image_processing_classes.values():
image_processor = image_processing_class(**self.image_processor_dict)
inputs = image_processor(dummy_image, return_tensors="pt")
torch.testing.assert_close(inputs["pixel_values"].mean(), torch.tensor(0.4906), rtol=1e-3, atol=1e-3)
def test_crop_margin_all_white(self):
image = np.uint8(np.ones((3, 100, 100)) * 255)
for backend_name, image_processing_class in self.image_processing_classes.items():
if backend_name == "torchvision":
image = torch.from_numpy(image)
image_processor = image_processing_class(**self.image_processor_dict)
cropped_image = image_processor.crop_margin(image)
self.assertTrue(torch.equal(image, cropped_image))
else:
image_processor = image_processing_class(**self.image_processor_dict)
cropped_image = image_processor.crop_margin(image)
self.assertTrue(np.array_equal(image, cropped_image))
def test_crop_margin_centered_black_square(self):
image = np.ones((3, 100, 100), dtype=np.uint8) * 255
image[:, 45:55, 45:55] = 0
expected_cropped = image[:, 45:55, 45:55]
for backend_name, image_processing_class in self.image_processing_classes.items():
if backend_name == "torchvision":
image = torch.from_numpy(image)
expected_cropped = torch.from_numpy(expected_cropped)
image_processor = image_processing_class(**self.image_processor_dict)
cropped_image = image_processor.crop_margin(image)
self.assertTrue(torch.equal(expected_cropped, cropped_image))
else:
image_processor = image_processing_class(**self.image_processor_dict)
cropped_image = image_processor.crop_margin(image)
self.assertTrue(np.array_equal(expected_cropped, cropped_image))
def test_align_long_axis_no_rotation(self):
image = np.uint8(np.ones((3, 100, 200)) * 255)
for backend_name, image_processing_class in self.image_processing_classes.items():
size = SizeDict(height=200, width=300)
image_processor = image_processing_class(**self.image_processor_dict)
if backend_name == "torchvision":
image = torch.from_numpy(image)
aligned_image = image_processor.align_long_axis(image, size)
self.assertEqual(image.shape, aligned_image.shape)
else:
aligned_image = image_processor.align_long_axis(image, size)
self.assertEqual(image.shape, aligned_image.shape)
def test_align_long_axis_with_rotation(self):
image = np.uint8(np.ones((3, 200, 100)) * 255)
for backend_name, image_processing_class in self.image_processing_classes.items():
image_processor = image_processing_class(**self.image_processor_dict)
size = SizeDict(height=300, width=200)
if backend_name == "torchvision":
image = torch.from_numpy(image)
aligned_image = image_processor.align_long_axis(image, size)
self.assertEqual(torch.Size([3, 200, 100]), aligned_image.shape)
else:
aligned_image = image_processor.align_long_axis(image, size)
self.assertEqual((3, 200, 100), aligned_image.shape)
def test_align_long_axis_data_format(self):
image = np.uint8(np.ones((3, 100, 200)) * 255)
for backend_name, image_processing_class in self.image_processing_classes.items():
size = SizeDict(height=200, width=300)
image_processor = image_processing_class(**self.image_processor_dict)
if backend_name == "torchvision":
image = torch.from_numpy(image)
aligned_image = image_processor.align_long_axis(image, size)
self.assertEqual(torch.Size([3, 100, 200]), aligned_image.shape)
else:
aligned_image = image_processor.align_long_axis(image, size)
self.assertEqual((3, 100, 200), aligned_image.shape)
def prepare_dummy_np_image(self):
revision = "ec57bf8c8b1653a209c13f6e9ee66b12df0fc2db"
filepath = hf_hub_download(
repo_id="hf-internal-testing/fixtures_docvqa",
filename="nougat_pdf.png",
repo_type="dataset",
revision=revision,
)
image = Image.open(filepath).convert("RGB")
return np.array(image).transpose(2, 0, 1)
def test_crop_margin_equality_cv2_python(self):
image = self.prepare_dummy_np_image()
for backend_name, image_processing_class in self.image_processing_classes.items():
image_processor = image_processing_class(**self.image_processor_dict)
if backend_name == "torchvision":
image = torch.from_numpy(image)
image_cropped_python = image_processor.crop_margin(image)
self.assertEqual(image_cropped_python.shape, torch.Size([3, 850, 685]))
self.assertAlmostEqual(image_cropped_python.float().mean().item(), 237.43881150708458, delta=0.001)
else:
image_cropped_python = image_processor.crop_margin(image)
self.assertEqual(image_cropped_python.shape, (3, 850, 685))
self.assertAlmostEqual(image_cropped_python.mean(), 237.43881150708458, delta=0.001)
def test_call_numpy_4_channels(self):
for backend_name, image_processing_class in self.image_processing_classes.items():
if backend_name == "pil":
# Test that can process images which have an arbitrary number of channels
# Initialize image_processing
image_processor = image_processing_class(**self.image_processor_dict)
# create random numpy tensors
self.image_processor_tester.num_channels = 4
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
# Test not batched input
encoded_images = image_processor(
image_inputs[0],
return_tensors="pt",
input_data_format="channels_last",
image_mean=(0.0, 0.0, 0.0, 0.0),
image_std=(1.0, 1.0, 1.0, 1.0),
).pixel_values
expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(
[image_inputs[0]]
)
self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))
# Test batched
encoded_images = image_processor(
image_inputs,
return_tensors="pt",
input_data_format="channels_last",
image_mean=(0.0, 0.0, 0.0, 0.0),
image_std=(1.0, 1.0, 1.0, 1.0),
).pixel_values
expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
self.assertEqual(
tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)
)
def test_backends_equivalence(self):
"""Test equivalence across backends. PIL backend delegates to Torchvision for pixel-perfect match."""
if len(self.image_processing_classes) < 2:
self.skipTest(reason="Skipping backends equivalence test as there are less than 2 backends")
dummy_image = load_image(url_to_local_path("http://images.cocodataset.org/val2017/000000039769.jpg"))
encodings = {}
for backend_name, image_processing_class in self.image_processing_classes.items():
image_processor = image_processing_class(**self.image_processor_dict)
encodings[backend_name] = image_processor(dummy_image, return_tensors="pt")
backend_names = list(encodings.keys())
reference_backend = backend_names[0]
reference_pixel_values = encodings[reference_backend].pixel_values
for backend_name in backend_names[1:]:
self._assert_tensors_equivalence(reference_pixel_values, encodings[backend_name].pixel_values)

View File

@@ -0,0 +1,110 @@
# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from transformers import NougatTokenizer
from transformers.models.nougat.tokenization_nougat import markdown_compatible, normalize_list_like_lines
from transformers.testing_utils import require_levenshtein, require_nltk, require_tokenizers
from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class NougatTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
from_pretrained_id = "facebook/nougat-base"
tokenizer_class = NougatTokenizer
integration_expected_tokens = ['This', 'Ġis', 'Ġa', 'Ġtest', 'Ġ', 'ð', 'Ł', 'ĺ', 'Ĭ', 'Ċ', 'I', 'Ġwas', 'Ġborn', 'Ġin', 'Ġ', '9', '2', '0', '0', '0', ',', 'Ġand', 'Ġthis', 'Ġis', 'Ġfals', 'é', '.', 'Ċ', 'çĶ', 'Ł', 'æ', '´', '»', 'çļĦ', 'ç', 'ľ', 'Ł', 'è', '°', 'Ľ', 'æ', 'ĺ', '¯', 'Ċ', 'Hi', 'Ġ', 'ĠH', 'ello', 'Ċ', 'Hi', 'ĠĠ', 'ĠH', 'ello', 'Ċ', 'Ċ', 'Ġ', 'Ċ', 'ĠĠ', 'Ċ', 'ĠH', 'ello', 'Ċ', '<s>', 'Ċ', 'hi', '<s>', 'there', 'Ċ', 'The', 'Ġfollowing', 'Ġstring', 'Ġshould', 'Ġbe', 'Ġproperly', 'Ġencoded', ':', 'ĠH', 'ello', '.', 'Ċ', 'But', 'Ġ', 'ird', 'Ġand', 'Ġ', 'à¸', 'Ľ', 'à¸', 'µ', 'ĠĠ', 'Ġ', 'ird', 'ĠĠ', 'Ġ', 'à¸', 'Ķ', 'Ċ', 'H', 'ey', 'Ġhow', 'Ġare', 'Ġyou', 'Ġdoing'] # fmt: skip
integration_expected_token_ids = [2113, 343, 281, 1185, 243, 195, 276, 269, 255, 221, 63, 435, 8613, 301, 243, 47, 40, 38, 38, 38, 34, 312, 495, 343, 34500, 2230, 36, 221, 33239, 276, 185, 135, 142, 31778, 186, 273, 276, 187, 131, 272, 185, 269, 130, 221, 33719, 243, 414, 13716, 221, 33719, 304, 414, 13716, 221, 221, 243, 221, 304, 221, 414, 13716, 221, 0, 221, 2197, 0, 10158, 221, 592, 1093, 4935, 1502, 391, 10651, 10033, 48, 414, 13716, 36, 221, 11847, 243, 2326, 312, 243, 12043, 272, 12043, 136, 304, 243, 2326, 304, 243, 12043, 265, 221, 62, 1220, 1905, 417, 2589, 10671] # fmt: skip
expected_tokens_from_ids = ['This', 'Ġis', 'Ġa', 'Ġtest', 'Ġ', 'ð', 'Ł', 'ĺ', 'Ĭ', 'Ċ', 'I', 'Ġwas', 'Ġborn', 'Ġin', 'Ġ', '9', '2', '0', '0', '0', ',', 'Ġand', 'Ġthis', 'Ġis', 'Ġfals', 'é', '.', 'Ċ', 'çĶ', 'Ł', 'æ', '´', '»', 'çļĦ', 'ç', 'ľ', 'Ł', 'è', '°', 'Ľ', 'æ', 'ĺ', '¯', 'Ċ', 'Hi', 'Ġ', 'ĠH', 'ello', 'Ċ', 'Hi', 'ĠĠ', 'ĠH', 'ello', 'Ċ', 'Ċ', 'Ġ', 'Ċ', 'ĠĠ', 'Ċ', 'ĠH', 'ello', 'Ċ', '<s>', 'Ċ', 'hi', '<s>', 'there', 'Ċ', 'The', 'Ġfollowing', 'Ġstring', 'Ġshould', 'Ġbe', 'Ġproperly', 'Ġencoded', ':', 'ĠH', 'ello', '.', 'Ċ', 'But', 'Ġ', 'ird', 'Ġand', 'Ġ', 'à¸', 'Ľ', 'à¸', 'µ', 'ĠĠ', 'Ġ', 'ird', 'ĠĠ', 'Ġ', 'à¸', 'Ķ', 'Ċ', 'H', 'ey', 'Ġhow', 'Ġare', 'Ġyou', 'Ġdoing'] # fmt: skip
integration_expected_decoded_text = "This is a test 😊\nI was born in 92000, and this is falsé.\n生活的真谛是\nHi Hello\nHi Hello\n\n \n \n Hello\n<s>\nhi<s>there\nThe following string should be properly encoded: Hello.\nBut ird and ปี ird ด\nHey how are you doing"
class MarkdownCompatibleTest(unittest.TestCase):
def test_equation_tag(self):
input_text = "(3.2) \\[Equation Text\\]"
excepted_output = "\\[Equation Text \\tag{3.2}\\]"
self.assertEqual(markdown_compatible(input_text), excepted_output)
def test_equation_tag_letters(self):
input_text = "(18a) \\[Equation Text\\]"
excepted_output = "\\[Equation Text \\tag{18a}\\]"
self.assertEqual(markdown_compatible(input_text), excepted_output)
def test_bold_formatting(self):
input_text = r"This is \bm{bold} text."
expected_output = r"This is \mathbf{bold} text."
self.assertEqual(markdown_compatible(input_text), expected_output)
def test_url_conversion(self):
input_text = "Visit my website at https://www.example.com"
expected_output = "Visit my website at [https://www.example.com](https://www.example.com)"
self.assertEqual(markdown_compatible(input_text), expected_output)
def test_algorithm_code_block(self):
input_text = "```python\nprint('Hello, world!')\n```"
expected_output = "```\npython\nprint('Hello, world!')\n```"
self.assertEqual(markdown_compatible(input_text), expected_output)
def test_escape_characters(self):
input_text = r"Escaped characters like \n should not be \\[affected\\]"
expected_output = r"Escaped characters like \n should not be \\[affected\\]"
self.assertEqual(markdown_compatible(input_text), expected_output)
def test_nested_tags(self):
input_text = r"This is a super nested \bm{\bm{\bm{\bm{\bm{bold}}}}} tag."
expected_output = r"This is a super nested \mathbf{\mathbf{\mathbf{\mathbf{\mathbf{bold}}}}} tag."
self.assertEqual(markdown_compatible(input_text), expected_output)
class TestNormalizeListLikeLines(unittest.TestCase):
def test_two_level_lines(self):
input_str = "* Item 1 * Item 2"
expected_output = "* Item 1\n* Item 2\n"
self.assertEqual(normalize_list_like_lines(input_str), expected_output)
def test_three_level_lines(self):
input_str = "- I. Item 1 - II. Item 2 - III. Item 3"
expected_output = "- I. Item 1\n- II. Item 2\n- III. Item 3\n"
self.assertEqual(normalize_list_like_lines(input_str), expected_output)
def test_nested_lines(self):
input_str = "- I. Item 1 - I.1 Sub-item 1 - I.1.1 Sub-sub-item 1 - II. Item 2"
expected_output = "- I. Item 1\n\t- I.1 Sub-item 1\n\t\t- I.1.1 Sub-sub-item 1\n- II. Item 2\n"
self.assertEqual(normalize_list_like_lines(input_str), expected_output)
@require_tokenizers
class NougatPostProcessingTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.tokenizer = NougatTokenizer.from_pretrained("facebook/nougat-base")
def test_correct_tables_basic(self):
input_str = "\\begin{table} \\begin{tabular}{l l} & \\ \\end{tabular} \\end{table}"
expected_output = "\\begin{table}\n\\begin{tabular}{l l} & \\ \\end{tabular}\n\\end{table}"
self.assertEqual(self.tokenizer.correct_tables(input_str), expected_output)
def test_correct_tables_high_count(self):
input_str = "\\begin{tabular}" * 20
expected_output = ""
self.assertEqual(self.tokenizer.correct_tables(input_str), expected_output)
@require_levenshtein
@require_nltk
def test_postprocess_as_nougat_no_markdown(self):
input_str = "# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" # noqa: E231
expected_output = "\n\n# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" # noqa: E231
self.assertEqual(self.tokenizer.post_process_single(input_str, fix_markdown=False), expected_output)