Transformers documentation
Nougat
This model was published in HF papers on 2023-08-25 and contributed to Hugging Face Transformers on 2023-09-26.
Nougat
Overview
The Nougat model was proposed in Nougat: Neural Optical Understanding for Academic Documents by Lukas Blecher, Guillem Cucurull, Thomas Scialom, Robert Stojnic. Nougat uses the same architecture as Donut, meaning an image Transformer encoder and an autoregressive text Transformer decoder to translate scientific PDFs to markdown, enabling easier access to them.
The abstract from the paper is the following:
Scientific 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 (Neural Optical Understanding for Academic 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.
Nougat high-level overview. Taken from the original paper. This model was contributed by nielsr. The original code can be found here.
Usage tips
- The quickest way to get started with Nougat is by checking the tutorial notebooks, which show how to use the model at inference time as well as fine-tuning on custom data.
- Nougat is always used within the VisionEncoderDecoder framework. The model is identical to Donut in terms of architecture.
Inference
Nougat’s VisionEncoderDecoder model accepts images as input and makes use of generate() to autoregressively generate text given the input image.
The NougatImageProcessor class is responsible for preprocessing the input image and NougatTokenizerFast decodes the generated target tokens to the target string. The NougatProcessor wraps NougatImageProcessor and NougatTokenizerFast classes into a single instance to both extract the input features and decode the predicted token ids.
- Step-by-step PDF transcription
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoModelForImageTextToText, NougatProcessor
processor = NougatProcessor.from_pretrained("facebook/nougat-base")
model = AutoModelForImageTextToText.from_pretrained("facebook/nougat-base", device_map="auto")
model.to(model.device) # doctest: +IGNORE_RESULT
# prepare PDF image for the model
filepath = hf_hub_download(repo_id="hf-internal-testing/fixtures_docvqa", filename="nougat_paper.png", repo_type="dataset")
image = Image.open(filepath)
pixel_values = processor(image, return_tensors="pt").to(model.device).pixel_values
# generate transcription (here we only generate 30 tokens)
outputs = model.generate(
pixel_values.to(model.device),
min_length=1,
max_new_tokens=30,
bad_words_ids=[[processor.tokenizer.unk_token_id]],
)
sequence = processor.batch_decode(outputs, skip_special_tokens=True)[0]
sequence = processor.post_process_generation(sequence, fix_markdown=False)
# note: we're using repr here such for the sake of printing the \n characters, feel free to just print the sequence
print(repr(sequence))
'\n\n# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@'See the model hub to look for Nougat checkpoints.
The model is identical to Donut in terms of architecture.
NougatConfig
class transformers.NougatConfig
< source >( transformers_version: str | None = Nonearchitectures: list[str] | None = Noneoutput_hidden_states: bool | None = Falsereturn_dict: bool | None = Truedtype: typing.Union[str, ForwardRef('torch.dtype'), NoneType] = Nonechunk_size_feed_forward: int = 0id2label: dict[int, str] | dict[str, str] | None = Nonelabel2id: dict[str, int] | dict[str, str] | None = Noneproblem_type: typing.Optional[typing.Literal['regression', 'single_label_classification', 'multi_label_classification']] = Noneis_encoder_decoder: bool = Trueencoder: dict | transformers.configuration_utils.PreTrainedConfig | None = Nonedecoder: dict | transformers.configuration_utils.PreTrainedConfig | None = None )
Parameters
This is the configuration class to store the configuration of a NougatModel. It is used to instantiate a Nougat model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the facebook/nougat-base
Configuration objects inherit from PreTrainedConfig and can be used to control the model outputs. Read the documentation from PreTrainedConfig for more information.
Examples:
>>> from transformers import NougatConfig, VisionEncoderDecoderModel
>>> # Initializing a Nougat configuration
>>> config = NougatConfig()
>>> # Initializing a VisionEncoderDecoder model (with random weights) from a Nougat configurations
>>> model = VisionEncoderDecoderModel(config=config)from_encoder_decoder_configs
< source >( encoder_config: PreTrainedConfigdecoder_config: PreTrainedConfig**kwargs ) → VisionEncoderDecoderConfig
Instantiate a VisionEncoderDecoderConfig (or a derived class) from a pre-trained encoder model configuration and decoder model configuration.
NougatImageProcessor
class transformers.NougatImageProcessor
< source >( **kwargs: Unpack )
Parameters
- do_crop_margin (
bool, kwargs, optional, defaults toself.do_crop_margin) — Whether to crop the image margins. - do_thumbnail (
bool, kwargs, optional, defaults toself.do_thumbnail) — Whether to resize the image using thumbnail method. - do_align_long_axis (
bool, kwargs, optional, defaults toself.do_align_long_axis) — Whether to align the long axis of the image with the long axis ofsizeby rotating by 90 degrees. - **kwargs (ImagesKwargs, optional) — Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class for the complete list of supported arguments.
Constructs a NougatImageProcessor image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: Unpack ) → ~image_processing_base.BatchFeature
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False. - do_crop_margin (
bool, kwargs, optional, defaults toself.do_crop_margin) — Whether to crop the image margins. - do_thumbnail (
bool, kwargs, optional, defaults toself.do_thumbnail) — Whether to resize the image using thumbnail method. - do_align_long_axis (
bool, kwargs, optional, defaults toself.do_align_long_axis) — Whether to align the long axis of the image with the long axis ofsizeby rotating by 90 degrees. - return_tensors (
stror TensorType, optional) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - **kwargs (ImagesKwargs, optional) — Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class for the complete list of supported arguments.
Returns
~image_processing_base.BatchFeature
- data (
dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.). - tensor_type (
Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
NougatImageProcessorPil
class transformers.NougatImageProcessorPil
< source >( **kwargs: Unpack )
Parameters
- do_crop_margin (
bool, kwargs, optional, defaults toself.do_crop_margin) — Whether to crop the image margins. - do_thumbnail (
bool, kwargs, optional, defaults toself.do_thumbnail) — Whether to resize the image using thumbnail method. - do_align_long_axis (
bool, kwargs, optional, defaults toself.do_align_long_axis) — Whether to align the long axis of the image with the long axis ofsizeby rotating by 90 degrees. - **kwargs (ImagesKwargs, optional) — Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class for the complete list of supported arguments.
Constructs a NougatImageProcessor image processor.
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]**kwargs: Unpack ) → ~image_processing_base.BatchFeature
Parameters
- images (
Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[PIL.Image.Image], list[numpy.ndarray], list[torch.Tensor]]) — Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False. - do_crop_margin (
bool, kwargs, optional, defaults toself.do_crop_margin) — Whether to crop the image margins. - do_thumbnail (
bool, kwargs, optional, defaults toself.do_thumbnail) — Whether to resize the image using thumbnail method. - do_align_long_axis (
bool, kwargs, optional, defaults toself.do_align_long_axis) — Whether to align the long axis of the image with the long axis ofsizeby rotating by 90 degrees. - return_tensors (
stror TensorType, optional) — Returns stacked tensors if set to'pt', otherwise returns a list of tensors. - **kwargs (ImagesKwargs, optional) — Additional image preprocessing options. Model-specific kwargs are listed above; see the TypedDict class for the complete list of supported arguments.
Returns
~image_processing_base.BatchFeature
- data (
dict) — Dictionary of lists/arrays/tensors returned by the call method (‘pixel_values’, etc.). - tensor_type (
Union[None, str, TensorType], optional) — You can give a tensor_type here to convert the lists of integers in PyTorch/Numpy Tensors at initialization.
NougatTokenizer
class transformers.NougatTokenizer
< source >( errors: str = 'replace'unk_token: str = '<unk>'bos_token: str = '<s>'eos_token: str = '</s>'pad_token: str = '<pad>'vocab: str | dict | list | None = Nonemerges: str | list | None = None**kwargs )
Parameters
- vocab_file (
str, optional) — Path to the vocabulary file. - merges_file (
str, optional) — Path to the merges file. - tokenizer_file (
str, optional) — tokenizers file (generally has a .json extension) that contains everything needed to load the tokenizer. - clean_up_tokenization_spaces (
str, optional, defaults toFalse) — Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces. - unk_token (
str, optional, defaults to"<unk>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. - bos_token (
str, optional, defaults to"<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. - eos_token (
str, optional, defaults to"</s>") — The end of sequence token. - pad_token (
str, optional, defaults to"<pad>") — The token used for padding, for example when batching sequences of different lengths. - vocab (
str,dictorlist, optional) — Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file. - merges (
strorlist, optional) — Custom merges list. If not provided, merges are loaded from merges_file.
Tokenizer for Nougat (backed by HuggingFace tokenizers library).
This tokenizer inherits from TokenizersBackend which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. This class mainly adds Nougat-specific methods for postprocessing the generated text.
correct_tables
< source >( generation: str ) → str
Takes a generated string and fixes tables/tabulars to make them match the markdown format needed.
post_process_generation
< source >( generation: str | list[str]fix_markdown: bool = Truenum_workers: int | None = None ) → Union[str, list[str]]
Parameters
- generation (Union[str, list[str]]) — The generated text or a list of generated texts.
- fix_markdown (
bool, optional, defaults toTrue) — Whether to perform Markdown formatting fixes. - num_workers (
int, optional) — Optional number of workers to pass to leverage multiprocessing (postprocessing several texts in parallel).
Returns
Union[str, list[str]]
The postprocessed text or list of postprocessed texts.
Postprocess a generated text or a list of generated texts.
This function can be used to perform postprocessing on generated text, such as fixing Markdown formatting.
Postprocessing is quite slow so it is recommended to use multiprocessing to speed up the process.
post_process_single
< source >( generation: strfix_markdown: bool = True ) → str
Postprocess a single generated text. Regular expressions used here are taken directly from the Nougat article authors. These expressions are commented for clarity and tested end-to-end in most cases.
remove_hallucinated_references
< source >( text: str ) → str
Remove hallucinated or missing references from the text.
This function identifies and removes references that are marked as missing or hallucinated from the input text.
NougatTokenizerFast
class transformers.NougatTokenizer
< source >( errors: str = 'replace'unk_token: str = '<unk>'bos_token: str = '<s>'eos_token: str = '</s>'pad_token: str = '<pad>'vocab: str | dict | list | None = Nonemerges: str | list | None = None**kwargs )
Parameters
- vocab_file (
str, optional) — Path to the vocabulary file. - merges_file (
str, optional) — Path to the merges file. - tokenizer_file (
str, optional) — tokenizers file (generally has a .json extension) that contains everything needed to load the tokenizer. - clean_up_tokenization_spaces (
str, optional, defaults toFalse) — Whether to cleanup spaces after decoding, cleanup consists in removing potential artifacts like extra spaces. - unk_token (
str, optional, defaults to"<unk>") — The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this token instead. - bos_token (
str, optional, defaults to"<s>") — The beginning of sequence token that was used during pretraining. Can be used a sequence classifier token. - eos_token (
str, optional, defaults to"</s>") — The end of sequence token. - pad_token (
str, optional, defaults to"<pad>") — The token used for padding, for example when batching sequences of different lengths. - vocab (
str,dictorlist, optional) — Custom vocabulary dictionary. If not provided, vocabulary is loaded from vocab_file. - merges (
strorlist, optional) — Custom merges list. If not provided, merges are loaded from merges_file.
Tokenizer for Nougat (backed by HuggingFace tokenizers library).
This tokenizer inherits from TokenizersBackend which contains most of the main methods. Users should refer to this superclass for more information regarding those methods. This class mainly adds Nougat-specific methods for postprocessing the generated text.
correct_tables
< source >( generation: str ) → str
Takes a generated string and fixes tables/tabulars to make them match the markdown format needed.
post_process_generation
< source >( generation: str | list[str]fix_markdown: bool = Truenum_workers: int | None = None ) → Union[str, list[str]]
Parameters
- generation (Union[str, list[str]]) — The generated text or a list of generated texts.
- fix_markdown (
bool, optional, defaults toTrue) — Whether to perform Markdown formatting fixes. - num_workers (
int, optional) — Optional number of workers to pass to leverage multiprocessing (postprocessing several texts in parallel).
Returns
Union[str, list[str]]
The postprocessed text or list of postprocessed texts.
Postprocess a generated text or a list of generated texts.
This function can be used to perform postprocessing on generated text, such as fixing Markdown formatting.
Postprocessing is quite slow so it is recommended to use multiprocessing to speed up the process.
post_process_single
< source >( generation: strfix_markdown: bool = True ) → str
Postprocess a single generated text. Regular expressions used here are taken directly from the Nougat article authors. These expressions are commented for clarity and tested end-to-end in most cases.
remove_hallucinated_references
< source >( text: str ) → str
Remove hallucinated or missing references from the text.
This function identifies and removes references that are marked as missing or hallucinated from the input text.
NougatProcessor
class transformers.NougatProcessor
< source >( image_processortokenizer )
Constructs a NougatProcessor which wraps a image processor and a tokenizer into a single processor.
NougatProcessor offers all the functionalities of NougatImageProcessor and NougatTokenizer. See the ~NougatImageProcessor and ~NougatTokenizer for more information.
__call__
< source >( images = Nonetext = None**kwargs )
Parameters
- images (`
) -- Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If passing in images with pixel values between 0 and 1, setdo_rescale=False`. - text (`
) -- The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings (pretokenized string). If you pass a pretokenized input, setis_split_into_words=True` to avoid ambiguity with batched inputs. - return_tensors (
stror TensorType, optional) — If set, will return tensors of a particular framework. Acceptable values are:'pt': Return PyTorchtorch.Tensorobjects.'np': Return NumPynp.ndarrayobjects.
from_pretrained
< source >( pretrained_model_name_or_path: str | os.PathLikecache_dir: str | os.PathLike | None = Noneforce_download: bool = Falselocal_files_only: bool = Falsetoken: str | bool | None = Nonerevision: str = 'main'**kwargs )
Parameters
- pretrained_model_name_or_path (
stroros.PathLike) — This can be either:- a string, the model id of a pretrained feature_extractor hosted inside a model repo on huggingface.co.
- a path to a directory containing a feature extractor file saved using the
save_pretrained() method, e.g.,
./my_model_directory/. - a path to a saved feature extractor JSON file, e.g.,
./my_model_directory/preprocessor_config.json.
- **kwargs —
Additional keyword arguments passed along to both
from_pretrained() and
~tokenization_utils_base.PreTrainedTokenizer.from_pretrained.
Instantiate a processor associated with a pretrained model.
This class method is simply calling the feature extractor from_pretrained(), image processor ImageProcessingMixin and the tokenizer
~tokenization_utils_base.PreTrainedTokenizer.from_pretrainedmethods. Please refer to the docstrings of the methods above for more information.
save_pretrained
< source >( save_directorypush_to_hub: bool = False**kwargs )
Parameters
- save_directory (
stroros.PathLike) — Directory where the feature extractor JSON file and the tokenizer files will be saved (directory will be created if it does not exist). - push_to_hub (
bool, optional, defaults toFalse) — Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the repository you want to push to withrepo_id(will default to the name ofsave_directoryin your namespace). - kwargs (
dict[str, Any], optional) — Additional key word arguments passed along to the push_to_hub() method.
Saves the attributes of this processor (feature extractor, tokenizer…) in the specified directory so that it can be reloaded using the from_pretrained() method.
This class method is simply calling save_pretrained() and save_pretrained(). Please refer to the docstrings of the methods above for more information.
This method forwards all its arguments to PreTrainedTokenizer’s batch_decode(). Please refer to the docstring of this method for more information.
This method forwards all its arguments to PreTrainedTokenizer’s decode(). Please refer to the docstring of this method for more information.
This method forwards all its arguments to NougatTokenizer’s ~PreTrainedTokenizer.post_process_generation.
Please refer to the docstring of this method for more information.