Transformers 文件

Nougat

Hugging Face's logo
加入 Hugging Face 社群

並獲得增強的文件體驗

開始使用

Nougat

PyTorch TensorFlow Flax

概述

Nougat模型由Lukas Blecher、Guillem Cucurull、Thomas Scialom和Robert Stojnic在論文 Nougat:面向學術文件的神經光學理解(Nougat: Neural Optical Understanding for Academic Documents)中提出。Nougat使用了與 Donut 相同的架構,即一個影像Transformer編碼器和一個自迴歸文字Transformer解碼器,將科學PDF文件翻譯為Markdown,使其更易於訪問。

論文摘要如下:

科學知識主要儲存在書籍和科學期刊中,通常以PDF格式存在。然而,PDF格式會導致語義資訊的丟失,尤其是對於數學表示式。我們提出了Nougat(面向學術文件的神經光學理解),這是一個視覺Transformer模型,它執行光學字元識別(OCR)任務,將科學文件處理成標記語言,並在一個新的科學文件資料集上展示了我們模型的有效性。透過彌合人類可讀文件與機器可讀文字之間的差距,該方法為增強數字時代科學知識的可訪問性提供了一個有前景的解決方案。我們釋出了模型和程式碼,以加速未來在科學文字識別方面的工作。

drawing Nougat高層級概述。圖片來自原始論文

該模型由 nielsr 貢獻。原始程式碼可在此處找到。

使用技巧

  • 開始使用Nougat最快的方法是檢視教程筆記本,其中展示瞭如何在推理時使用該模型以及如何在自定義資料上進行微調。
  • Nougat始終在VisionEncoderDecoder框架內使用。該模型的架構與Donut相同。

推理

Nougat的`VisionEncoderDecoder`模型接受影像作為輸入,並利用generate()根據輸入影像自迴歸地生成文字。

NougatImageProcessor類負責預處理輸入影像,而NougatTokenizerFast將生成的目標詞元解碼為目標字串。NougatProcessorNougatImageProcessorNougatTokenizerFast類包裝成一個單一例項,用於提取輸入特徵和解碼預測的詞元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@'

請參閱模型中心以查詢Nougat檢查點。

該模型的架構與Donut相同。

NougatImageProcessor

class transformers.NougatImageProcessor

< >

( do_crop_margin: bool = True do_resize: bool = True size: typing.Optional[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, list[float], NoneType] = None image_std: typing.Union[float, 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 (intfloat, 可選, 預設為 `1/255`) — 縮放影像時使用的比例因子。可在 `preprocess` 方法中透過 `rescale_factor` 引數覆蓋。
  • do_normalize (bool, 可選, 預設為 `True`) — 是否對影像進行歸一化。可在 `preprocess` 方法中透過 `do_normalize` 引數覆蓋。
  • image_mean (floatlist[float], 可選, 預設為 `IMAGENET_DEFAULT_MEAN`) — 歸一化影像時使用的均值。這是一個浮點數或浮點數列表,長度與影像通道數相同。可在 `preprocess` 方法中透過 `image_mean` 引數覆蓋。
  • image_std (floatlist[float], 可選, 預設為 `IMAGENET_DEFAULT_STD`) — 影像標準差。

構建一個Nougat影像處理器。

預處理

< >

( 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: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: Resampling = None do_thumbnail: typing.Optional[bool] = None do_align_long_axis: typing.Optional[bool] = None do_pad: typing.Optional[bool] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Union[int, float, NoneType] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, 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 (intfloat, 可選, 預設為 `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`, 可選) — 返回張量的型別。可以是以下之一:
    • 未設定:返回 `np.ndarray` 列表。
    • `TensorType.TENSORFLOW` 或 `'tf'`:返回 `tf.Tensor` 批次。
    • `TensorType.PYTORCH` 或 `'pt'`:返回 `torch.Tensor` 批次。
    • `TensorType.NUMPY` 或 `'np'`:返回 `np.ndarray` 批次。
    • `TensorType.JAX` 或 `'jax'`:返回 `jax.numpy.ndarray` 批次。
  • data_format (`ChannelDimension` 或 `str`, 可選, 預設為 `ChannelDimension.FIRST`) — 輸出影像的通道維度格式。可以是以下之一:
    • `ChannelDimension.FIRST`:影像格式為 (num_channels, height, width)。
    • `ChannelDimension.LAST`:影像格式為 (height, width, num_channels)。
    • 未設定:預設為輸入影像的通道維度格式。
  • 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

< >

( 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`, 可選, 預設為 `""`) — 未知詞元。不在詞彙表中的詞元無法轉換為ID,將被設定為此詞元。
  • bos_token (str, 可選, 預設為 "<s>") — 預訓練期間使用的序列開始標記。可用作序列分類器標記。
  • eos_token (str, 可選, 預設為 "</s>") — 序列結束標記。
  • pad_token (str, 可選, 預設為 "<pad>") — 用於填充的標記,例如在批處理不同長度的序列時。
  • model_max_length (int, 可選) — Transformer 模型輸入的最大長度(以標記數量計)。當使用 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 or tokenizers.AddedToken, 可選) — 表示句子開頭的特殊標記。將與 `self.bos_token` 和 `self.bos_token_id` 關聯。
  • eos_token (str or tokenizers.AddedToken, 可選) — 表示句子結尾的特殊標記。將與 `self.eos_token` 和 `self.eos_token_id` 關聯。
  • unk_token (str or tokenizers.AddedToken, 可選) — 表示詞彙表外標記的特殊標記。將與 `self.unk_token` 和 `self.unk_token_id` 關聯。
  • sep_token (str or tokenizers.AddedToken, 可選) — 用於在同一輸入中分隔兩個不同句子的特殊標記(例如 BERT 使用)。將與 `self.sep_token` 和 `self.sep_token_id` 關聯。
  • pad_token (str or tokenizers.AddedToken, 可選) — 一種特殊標記,用於使標記陣列具有相同的大小以便於批處理。之後將被注意力機制或損失計算忽略。將與 `self.pad_token` 和 `self.pad_token_id` 關聯。
  • cls_token (str or tokenizers.AddedToken, 可選) — 表示輸入類別的特殊標記(例如 BERT 使用)。將與 `self.cls_token` 和 `self.cls_token_id` 關聯。
  • mask_token (str or tokenizers.AddedToken, 可選) — 表示掩碼標記的特殊標記(用於掩碼語言建模預訓練目標,如 BERT)。將與 `self.mask_token` 和 `self.mask_token_id` 關聯。
  • additional_special_tokens (tuple or list of str or tokenizers.AddedToken, 可選) — 一個元組或列表,包含額外的特殊標記。在此處新增它們以確保在使用 `skip_special_tokens` 設定為 True 進行解碼時跳過它們。如果它們不屬於詞彙表,將被新增到詞彙表的末尾。
  • clean_up_tokenization_spaces (bool, 可選, 預設為 True) — 模型是否應清理在分詞過程中分割輸入文字時新增的空格。
  • split_special_tokens (bool, 可選, 預設為 False) — 特殊標記在分詞過程中是否應被分割。傳遞此引數將影響分詞器的內部狀態。預設行為是不分割特殊標記。這意味著如果 `<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

< >

( generation: str ) str

引數

  • generation (str) — 需要後處理的生成文字。

返回

字串

後處理後的文字。

接收一個生成的字串,並修復其中的表格/製表環境,使其符合所需的 markdown 格式。

示例

correct_tables("\begin{table} \begin{tabular}{l l} & \ \end{tabular} \end{table}")
"\begin{table}
abular}{l l} & \ \end{tabular}
le}"

post_process_generation

< >

( generation: typing.Union[str, list[str]] fix_markdown: bool = True num_workers: typing.Optional[int] = None ) Union[str, list[str]]

引數

  • generation (Union[str, list[str]]) — 生成的文字或生成的文字列表。
  • fix_markdown (bool, 可選, 預設為 True) — 是否執行 Markdown 格式修復。
  • num_workers (int, 可選) — 可選的工作程序數,用於利用多程序(並行後處理多個文字)。

返回

Union[str, list[str]]

後處理後的文字或後處理後的文字列表。

對一個生成的文字或一系列生成的文字進行後處理。

此函式可用於對生成的文字進行後處理,例如修復 Markdown 格式。

後處理相當慢,因此建議使用多程序來加速該過程。

post_process_single

< >

( generation: str fix_markdown: bool = True ) str

引數

  • generation (str) — 需要後處理的生成文字。
  • fix_markdown (bool, 可選) — 是否執行 Markdown 格式修復。預設為 True。

返回

字串

後處理後的文字。

對單個生成的文字進行後處理。這裡使用的正則表示式直接取自 Nougat 文章的作者。為清晰起見,這些表示式都有註釋,並在大多數情況下進行了端到端測試。

remove_hallucinated_references

< >

( text: str ) str

引數

  • text (str) — 包含引用的輸入文字。

返回

字串

移除了幻覺引用的文字。

從文字中移除幻覺或缺失的引用。

此函式識別並從輸入文字中移除被標記為缺失或幻覺的引用。

NougatProcessor

class transformers.NougatProcessor

< >

( image_processor tokenizer )

引數

構建一個 Nougat 處理器,它將一個 Nougat 影像處理器和一個 Nougat 分詞器包裝成一個單一的處理器。

NougatProcessor 提供了 NougatImageProcessorNougatTokenizerFast 的所有功能。有關更多資訊,請參閱 __call__()decode()

__call__

< >

( images = None text = None do_crop_margin: typing.Optional[bool] = None do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None resample: PILImageResampling = None do_thumbnail: typing.Optional[bool] = None do_align_long_axis: typing.Optional[bool] = None do_pad: typing.Optional[bool] = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Union[int, float, NoneType] = None do_normalize: typing.Optional[bool] = None image_mean: typing.Union[float, list[float], NoneType] = None image_std: typing.Union[float, 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, list[str], list[list[str]], NoneType] = None text_target: typing.Union[str, list[str], list[list[str]]] = None text_pair_target: typing.Union[str, list[str], list[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

< >

( 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 or os.PathLike) — 這可以是以下之一:

    • 一個字串,即託管在 huggingface.co 的模型倉庫中的預訓練特徵提取器的 模型 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

< >

( save_directory push_to_hub: bool = False **kwargs )

引數

  • save_directory (str or os.PathLike) — 將儲存特徵提取器 JSON 檔案和分詞器檔案的目錄(如果目錄不存在,則會建立)。
  • push_to_hub (bool, 可選, 預設為 False) — 是否在儲存模型後將其推送到 Hugging Face 模型中心。您可以使用 `repo_id` 指定要推送到的倉庫(預設為您名稱空間中 `save_directory` 的名稱)。
  • kwargs (dict[str, Any], 可選) — 傳遞給 push_to_hub() 方法的附加關鍵字引數。

將此處理器的屬性(特徵提取器、分詞器等)儲存在指定目錄中,以便可以使用 from_pretrained() 方法重新載入。

此方法只是呼叫 save_pretrained()save_pretrained()。有關更多資訊,請參閱上述方法的文件字串。

batch_decode

< >

( *args **kwargs )

此方法將其所有引數轉發給 NougatTokenizer 的 batch_decode()。有關更多資訊,請參閱該方法的文件字串。

解碼

< >

( *args **kwargs )

此方法將其所有引數轉發給 NougatTokenizer 的 decode()。請參閱該方法的文件字串以獲取更多資訊。

post_process_generation

< >

( *args **kwargs )

此方法將其所有引數轉發給 NougatTokenizer 的 ~PreTrainedTokenizer.post_process_generation。請參閱該方法的文件字串以獲取更多資訊。

< > 在 GitHub 上更新

© . This site is unofficial and not affiliated with Hugging Face, Inc.