Transformers 文档
牛轧糖
并获取增强的文档体验
开始使用
Nougat
概述
Nougat 模型在 Nougat: Neural Optical Understanding for Academic Documents 中被提出,作者是 Lukas Blecher、Guillem Cucurull、Thomas Scialom 和 Robert Stojnic。Nougat 使用与 Donut 相同的架构,意味着使用图像 Transformer 编码器和自回归文本 Transformer 解码器将科学 PDF 转换为 markdown,从而更容易访问它们。
该论文的摘要如下:
科学知识主要存储在书籍和科学期刊中,通常以 PDF 格式存在。然而,PDF 格式会导致语义信息的丢失,特别是对于数学表达式。我们提出了 Nougat (Neural Optical Understanding for Academic Documents),一个视觉 Transformer 模型,它执行光学字符识别 (OCR) 任务,用于将科学文档处理成标记语言,并在一个新的科学文档数据集上证明了我们模型的有效性。所提出的方法为增强数字时代科学知识的可访问性提供了一个有希望的解决方案,弥合了人类可读文档和机器可读文本之间的差距。我们发布了模型和代码,以加速未来在科学文本识别方面的工作。

使用技巧
- 开始使用 Nougat 的最快方法是查看教程笔记本,其中展示了如何在推理时使用该模型以及在自定义数据上进行微调。
- Nougat 始终在 VisionEncoderDecoder 框架内使用。该模型在架构方面与 Donut 完全相同。
推理
Nougat 的 VisionEncoderDecoder
模型接受图像作为输入,并使用 generate() 来自回归地生成文本(给定输入图像)。
NougatImageProcessor 类负责预处理输入图像,NougatTokenizerFast 将生成的target tokens解码为目标字符串。NougatProcessor 将 NougatImageProcessor 和 NougatTokenizerFast 类封装到单个实例中,以提取输入特征并解码预测的 token id。
- 逐步 PDF 转录
>>> from huggingface_hub import hf_hub_download
>>> import re
>>> from PIL import Image
>>> from transformers import NougatProcessor, VisionEncoderDecoderModel
>>> from datasets import load_dataset
>>> import torch
>>> processor = NougatProcessor.from_pretrained("facebook/nougat-base")
>>> model = VisionEncoderDecoderModel.from_pretrained("facebook/nougat-base")
>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model.to(device)
>>> # 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").pixel_values
>>> # generate transcription (here we only generate 30 tokens)
>>> outputs = model.generate(
... pixel_values.to(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@'
查看 模型 Hub 以查找 Nougat checkpoints。
该模型在架构方面与 Donut 完全相同。
NougatImageProcessor
class transformers.NougatImageProcessor
< source >( do_crop_margin: bool = True do_resize: bool = True size: typing.Dict[str, int] = None resample: Resampling = <Resampling.BILINEAR: 2> do_thumbnail: bool = True do_align_long_axis: bool = False do_pad: bool = True do_rescale: bool = True rescale_factor: typing.Union[int, float] = 0.00392156862745098 do_normalize: bool = True image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None **kwargs )
参数
- do_crop_margin (
bool
, 可选, 默认为True
) — 是否裁剪图像边距。 - do_resize (
bool
, 可选, 默认为True
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
重写。 - size (
Dict[str, int]
可选, 默认为{"height" -- 896, "width": 672}
): 调整大小后图像的尺寸。可以被preprocess
方法中的size
重写。 - resample (
PILImageResampling
, 可选, 默认为Resampling.BILINEAR
) — 如果调整图像大小,则使用的重采样滤波器。可以被preprocess
方法中的resample
重写。 - do_thumbnail (
bool
, 可选, 默认为True
) — 是否使用缩略图方法调整图像大小。 - do_align_long_axis (
bool
, 可选, 默认为False
) — 是否通过旋转 90 度将图像的长轴与size
的长轴对齐。 - do_pad (
bool
, 可选, 默认为True
) — 是否将图像填充到批次中最大的图像尺寸。 - do_rescale (
bool
, 可选, 默认为True
) — 是否按指定的比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
或float
, 可选, 默认为1/255
) — 如果缩放图像,则使用的缩放因子。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可以被preprocess
方法中的do_normalize
覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为IMAGENET_DEFAULT_MEAN
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中通道的数量。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为IMAGENET_DEFAULT_STD
) — 图像标准差。
构建 Nougat 图像处理器。
preprocess
< source >( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_crop_margin: bool = None do_resize: bool = None size: typing.Dict[str, int] = None resample: Resampling = None do_thumbnail: bool = None do_align_long_axis: bool = None do_pad: bool = None do_rescale: bool = None rescale_factor: typing.Union[int, float] = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None data_format: typing.Optional[transformers.image_utils.ChannelDimension] = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )
参数
- images (
ImageInput
) — 要预处理的图像。接受单个或一批像素值范围从 0 到 255 的图像。 - do_crop_margin (
bool
, 可选, 默认为self.do_crop_margin
) — 是否裁剪图像边距。 - do_resize (
bool
, 可选, 默认为self.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, 可选, 默认为self.size
) — 调整大小后图像的尺寸。图像的最短边将被调整为 min(size[“height”], size[“width”]),最长边将被调整以保持输入宽高比。 - resample (
int
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举PILImageResampling
之一。仅当do_resize
设置为True
时才有效。 - do_thumbnail (
bool
, 可选, 默认为self.do_thumbnail
) — 是否使用缩略图方法调整图像大小。 - do_align_long_axis (
bool
, 可选, 默认为self.do_align_long_axis
) — 是否通过旋转 90 度来对齐图像的长轴与size
的长轴。 - do_pad (
bool
, 可选, 默认为self.do_pad
) — 是否将图像填充到批次中最大的图像尺寸。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否按指定的比例rescale_factor
缩放图像。 - rescale_factor (
int
或float
, 可选, 默认为self.rescale_factor
) — 如果缩放图像,则使用的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。 - return_tensors (
str
或TensorType
, 可选) — 返回的张量类型。可以是以下之一:- Unset: 返回
np.ndarray
列表。 TensorType.TENSORFLOW
或'tf'
: 返回tf.Tensor
类型的批次。TensorType.PYTORCH
或'pt'
: 返回torch.Tensor
类型的批次。TensorType.NUMPY
或'np'
: 返回np.ndarray
类型的批次。TensorType.JAX
或'jax'
: 返回jax.numpy.ndarray
类型的批次。
- Unset: 返回
- data_format (
ChannelDimension
或str
, 可选, 默认为ChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 默认为输入图像的通道维度格式。
- input_data_format (
ChannelDimension
或str
, 可选) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理一个图像或一批图像。
NougatTokenizerFast
class transformers.NougatTokenizerFast
< source >( vocab_file = None tokenizer_file = None clean_up_tokenization_spaces = False unk_token = '<unk>' bos_token = '<s>' eos_token = '</s>' pad_token = '<pad>' **kwargs )
参数
- vocab_file (
str
, 可选) — SentencePiece 文件(通常带有 .model 扩展名),其中包含实例化分词器所需的词汇表。 - tokenizer_file (
str
, 可选) — tokenizers 文件(通常带有 .json 扩展名),其中包含加载分词器所需的一切。 - clean_up_tokenization_spaces (
str
, 可选, 默认为False
) — 是否在解码后清理空格,清理包括删除潜在的伪像,如额外的空格。 - unk_token (
str
, 可选, 默认为"<unk>"
) — 未知 token。词汇表中没有的 token 无法转换为 ID,而是设置为此 token。 - bos_token (
str
, 可选, 默认为"<s>"
) — 序列开始 token,在预训练期间使用。可以用作序列分类器 token。 - eos_token (
str
, 可选, 默认为"</s>"
) — 序列结束 token。 - pad_token (
str
, 可选, 默认为"<pad>"
) — 用于填充的 token,例如在批量处理不同长度的序列时。 - model_max_length (
int
, 可选) — Transformer 模型输入的最大长度(以 token 数量计)。当分词器通过 from_pretrained() 加载时,这将设置为max_model_input_sizes
中关联模型存储的值(见上文)。如果未提供值,则默认为 VERY_LARGE_INTEGER (int(1e30)
)。 - padding_side (
str
, 可选) — 模型应在其上应用填充的一侧。应在 [‘right’, ‘left’] 之间选择。默认值从同名类属性中选取。 - truncation_side (
str
, 可选) — 模型应在其上应用截断的一侧。应在 [‘right’, ‘left’] 之间选择。默认值从同名类属性中选取。 - chat_template (
str
, 可选) — 一个 Jinja 模板字符串,将用于格式化聊天消息列表。有关完整描述,请参阅 https://huggingface.co/docs/transformers/chat_templating。 - model_input_names (
List[string]
, 可选) — 模型前向传播接受的输入列表(如"token_type_ids"
或"attention_mask"
)。默认值从同名类属性中选取。 - bos_token (
str
或tokenizers.AddedToken
, 可选) — 表示句子开头的特殊 token。将与self.bos_token
和self.bos_token_id
关联。 - eos_token (
str
或tokenizers.AddedToken
, 可选) — 表示句子结尾的特殊 token。将与self.eos_token
和self.eos_token_id
关联。 - unk_token (
str
或tokenizers.AddedToken
, 可选) — 表示词汇表外 token 的特殊 token。将与self.unk_token
和self.unk_token_id
关联。 - sep_token (
str
或tokenizers.AddedToken
, 可选) — 分隔同一输入中两个不同句子的特殊 token(例如 BERT 使用的 token)。将与self.sep_token
和self.sep_token_id
关联。 - pad_token (
str
或tokenizers.AddedToken
, 可选) — 一种特殊的 token,用于使 token 数组在批处理时大小相同。然后将被注意力机制或损失计算忽略。将与self.pad_token
和self.pad_token_id
关联。 - cls_token (
str
或tokenizers.AddedToken
, 可选) — 表示输入类别的特殊 token(例如 BERT 使用的 token)。将与self.cls_token
和self.cls_token_id
关联。 - mask_token (
str
或tokenizers.AddedToken
, 可选) — 表示掩码 token 的特殊 token(由掩码语言建模预训练目标使用,如 BERT)。将与self.mask_token
和self.mask_token_id
关联。 - additional_special_tokens (tuple 或 list of
str
或tokenizers.AddedToken
, 可选) — 附加特殊 token 的 tuple 或 list。在此处添加它们以确保在将skip_special_tokens
设置为 True 时跳过它们。如果它们不是词汇表的一部分,则将它们添加到词汇表的末尾。 - clean_up_tokenization_spaces (
bool
, 可选, 默认为True
) — 模型是否应清理在 token 化过程中拆分输入文本时添加的空格。 - split_special_tokens (
bool
, 可选, 默认为False
) — 特殊 token 是否应在 token 化过程中拆分。传递将影响分词器的内部状态。默认行为是不拆分特殊 token。这意味着如果<s>
是bos_token
,则tokenizer.tokenize("<s>") = ['<s>
]。否则,如果split_special_tokens=True
,则tokenizer.tokenize("<s>")
将给出['<','s', '>']
。 - tokenizer_object (
tokenizers.Tokenizer
) — 来自 🤗 tokenizers 的tokenizers.Tokenizer
对象,用于从中实例化。有关更多信息,请参阅 使用来自 🤗 tokenizers 的分词器。 - tokenizer_file (
str
) — 本地 JSON 文件的路径,表示先前序列化的来自 🤗 tokenizers 的tokenizers.Tokenizer
对象。
Nougat 的快速分词器(由 HuggingFace tokenizers 库支持)。
此分词器继承自 PreTrainedTokenizerFast,其中包含大多数主要方法。用户应参考此超类以获取有关这些方法的更多信息。此类主要添加了 Nougat 特有的方法,用于后处理生成的文本。
类属性(被派生类覆盖)
- vocab_files_names (
Dict[str, str]
) — 一个字典,键是模型所需的每个词汇表文件的__init__
关键字名称,关联的值是用于保存关联文件的文件名(字符串)。 - pretrained_vocab_files_map (
Dict[str, Dict[str, str]]
) — 一个字典的字典,高级键是模型所需的每个词汇表文件的__init__
关键字名称,低级键是预训练模型的short-cut-names
,关联的值是关联的预训练词汇表文件的url
。 - model_input_names (
List[str]
) — 模型前向传播中预期输入的列表。 - padding_side (
str
) — 模型应在其上应用填充的侧面的默认值。应为'right'
或'left'
。 - truncation_side (
str
) — 模型应应用截断的侧面的默认值。应为'right'
或'left'
。
correct_tables
< source >( generation: str ) → str
获取生成的字符串并修复表格/制表符,使其与所需的 markdown 格式匹配。
post_process_generation
< source >( generation: typing.Union[str, typing.List[str]] fix_markdown: bool = True num_workers: int = None ) → Union[str, List[str]]
后处理生成的文本或生成的文本列表。
此函数可用于对生成的文本执行后处理,例如修复 Markdown 格式。
后处理速度相当慢,因此建议使用多进程来加快处理速度。
post_process_single
< source >( generation: str fix_markdown: bool = True ) → str
后处理单个生成的文本。此处使用的正则表达式直接取自 Nougat 文章的作者。这些表达式已添加注释以提高清晰度,并在大多数情况下进行了端到端测试。
remove_hallucinated_references
< source >( text: str ) → str
从文本中移除幻觉或缺失的引用。
此函数识别并移除输入文本中标记为缺失或幻觉的引用。
NougatProcessor
class transformers.NougatProcessor
< source >( image_processor tokenizer )
参数
- image_processor (NougatImageProcessor) — NougatImageProcessor 的实例。图像处理器是必需的输入。
- tokenizer (NougatTokenizerFast) — NougatTokenizerFast 的实例。分词器是必需的输入。
构建一个 Nougat 处理器,该处理器将 Nougat 图像处理器和 Nougat 分词器封装到单个处理器中。
NougatProcessor 提供 NougatImageProcessor 和 NougatTokenizerFast 的所有功能。有关更多信息,请参阅 call() 和 decode()。
__call__
< source >( images = None text = None do_crop_margin: bool = None do_resize: bool = None size: typing.Dict[str, int] = None resample: PILImageResampling = None do_thumbnail: bool = None do_align_long_axis: bool = None do_pad: bool = None do_rescale: bool = None rescale_factor: typing.Union[int, float] = None do_normalize: bool = None image_mean: typing.Union[float, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.List[float], NoneType] = None data_format: typing.Optional[ForwardRef('ChannelDimension')] = 'channels_first' input_data_format: typing.Union[str, ForwardRef('ChannelDimension'), NoneType] = None text_pair: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None text_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]]] = None text_pair_target: typing.Union[str, typing.List[str], typing.List[typing.List[str]], NoneType] = None add_special_tokens: bool = True padding: typing.Union[bool, str, transformers.utils.generic.PaddingStrategy] = False truncation: typing.Union[bool, str, transformers.tokenization_utils_base.TruncationStrategy] = None max_length: typing.Optional[int] = None stride: int = 0 is_split_into_words: bool = False pad_to_multiple_of: typing.Optional[int] = None return_tensors: typing.Union[str, transformers.utils.generic.TensorType, NoneType] = None return_token_type_ids: typing.Optional[bool] = None return_attention_mask: typing.Optional[bool] = None return_overflowing_tokens: bool = False return_special_tokens_mask: bool = False return_offsets_mapping: bool = False return_length: bool = False verbose: bool = True )
from_pretrained
< source >( pretrained_model_name_or_path: typing.Union[str, os.PathLike] cache_dir: typing.Union[str, os.PathLike, NoneType] = None force_download: bool = False local_files_only: bool = False token: typing.Union[str, bool, NoneType] = None revision: str = 'main' **kwargs )
参数
- pretrained_model_name_or_path (
str
或os.PathLike
) — 可以是以下之一:- 一个字符串,即托管在 huggingface.co 上的模型仓库内的预训练 feature_extractor 的模型 ID。
- 一个目录的路径,其中包含使用 save_pretrained() 方法保存的特征提取器文件,例如
./my_model_directory/
。 - 保存的特征提取器 JSON 文件的路径或 URL,例如
./my_model_directory/preprocessor_config.json
。
- **kwargs — 传递给 from_pretrained() 和
~tokenization_utils_base.PreTrainedTokenizer.from_pretrained
的其他关键字参数。
实例化与预训练模型关联的处理器。
此类方法只是调用特征提取器 from_pretrained()、图像处理器 ImageProcessingMixin 和分词器 ~tokenization_utils_base.PreTrainedTokenizer.from_pretrained
方法。有关更多信息,请参阅上述方法的文档字符串。
save_pretrained
< source >( save_directory push_to_hub: bool = False **kwargs )
参数
- save_directory (
str
或os.PathLike
) — 将在其中保存特征提取器 JSON 文件和分词器文件的目录(如果目录不存在,则会创建目录)。 - push_to_hub (
bool
, 可选, 默认为False
) — 是否在保存模型后将其推送到 Hugging Face 模型中心。 您可以使用repo_id
指定要推送到的仓库(默认为您命名空间中save_directory
的名称)。 - kwargs (
Dict[str, Any]
, 可选) — 传递给 push_to_hub() 方法的附加关键字参数。
将此处理器(特征提取器、分词器...)的属性保存在指定目录中,以便可以使用 from_pretrained() 方法重新加载。
此class方法只是简单地调用 save_pretrained() 和 save_pretrained()。 有关更多信息,请参阅上述方法的文档字符串。
此方法将其所有参数转发到 NougatTokenizer 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发到 NougatTokenizer 的 decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发到 NougatTokenizer 的 ~PreTrainedTokenizer.post_process_generation
。 有关更多信息,请参阅此方法的文档字符串。