Transformers 文档

GOT-OCR2

Hugging Face's logo
加入 Hugging Face 社区

并获得增强的文档体验

开始使用

GOT-OCR2

PyTorch

概述

GOT-OCR2 模型由 Haoran Wei、Chenglong Liu、Jinyue Chen、Jia Wang、Lingyu Kong、Yanming Xu、Zheng Ge、Liang Zhao、Jianjian Sun、Yuang Peng、Chunrui Han、Xiangyu Zhang 在 通用 OCR 理论:通过统一端到端模型实现 OCR-2.0 中提出。

论文摘要如下:

传统 OCR 系统 (OCR-1.0) 越来越无法满足人们的需求,因为对人工光学字符智能处理的需求不断增长。本文中,我们将所有人工光学信号 (例如,纯文本、数学/分子式、表格、图表、乐谱,甚至几何形状) 统称为“字符”,并提出了通用 OCR 理论以及一个出色的模型,即 GOT,以促进 OCR-2.0 的到来。GOT 拥有 5.8 亿个参数,是一个统一、优雅的端到端模型,由高压缩编码器和长上下文解码器组成。作为 OCR-2.0 模型,GOT 可以在各种 OCR 任务中处理上述所有“字符”。在输入端,该模型支持切片和整页样式的常用场景和文档图像。在输出端,GOT 可以通过简单的提示生成纯文本或格式化结果 (markdown/tikz/smiles/kern)。此外,该模型还具有交互式 OCR 功能,即由坐标或颜色引导的区域级识别。此外,我们还将动态分辨率和多页 OCR 技术应用于 GOT,以提高实用性。在实验中,我们提供了充足的结果来证明我们模型的优越性。

drawing GOT-OCR2 训练阶段。摘自原论文。

技巧

GOT-OCR2 适用于各种任务,包括纯文档 OCR、场景文本 OCR、格式化文档 OCR,甚至表格、图表、数学公式、几何形状、分子式和乐谱的 OCR。虽然该模型仅输出纯文本,但可以使用 `pdftex`、`mathpix`、`matplotlib`、`tikz`、`verovio` 或 `pyecharts` 等包对输出进行进一步处理,以呈现所需的格式。该模型还可以用于交互式 OCR,用户可以通过提供区域的坐标或边界框的颜色来指定要识别的区域。

该模型由yonigozlan贡献。原始代码可以在这里找到。

使用示例

纯文本推理

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg"
>>> inputs = processor(image, return_tensors="pt", device=device).to(device)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4096,
... )

>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
"R&D QUALITY IMPROVEMENT\nSUGGESTION/SOLUTION FORM\nName/Phone Ext. : (...)"

纯文本批处理推理

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
>>> image2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg"

>>> inputs = processor([image1, image2], return_tensors="pt", device=device).to(device)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4,
... )

>>> processor.batch_decode(generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True)
["Reducing the number", "R&D QUALITY"]

格式化文本推理

GOT-OCR2 还可以生成格式化文本,例如 markdown 或 LaTeX。以下是生成格式化文本的示例

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/latex.png"
>>> inputs = processor(image, return_tensors="pt", format=True, device=device).to(device)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4096,
... )

>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
"\\author{\nHanwen Jiang*{@html "quad\\quad"} Arjun Karpur{@html "daggerquad{ }^{\\dagger} \\quad"} Bingyi Cao{@html "daggerquad{ }^{\\dagger} \\quad"} (...)"

多页推理

尽管在大多数情况下使用“for 循环”进行多页处理是合理的,但某些跨多页的格式化文本数据使得一次性处理所有页面变得必要。GOT 引入了多页 OCR(不使用“for 循环”)功能,模型可以一次性处理多个页面,输出是连续的文本。以下是处理多页的示例

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image1 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/page1.png"
>>> image2 = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/page2.png"
>>> inputs = processor([image1, image2], return_tensors="pt", multi_page=True, format=True, device=device).to(device)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4096,
... )

>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
"\\title{\nGeneral OCR Theory: Towards OCR-2.0 via a Unified End-to-end Model\n}\n\\author{\nHaoran Wei (...)"

裁剪补丁上的推理

GOT 支持 1024×1024 的输入分辨率,这对于大多数 OCR 任务(例如场景 OCR 或处理 A4 大小的 PDF 页面)来说已经足够。然而,某些场景,例如学术论文中常见的水平拼接的两页 PDF 或具有不寻常纵横比的图像,在作为单个图像处理时可能会导致准确性问题。为了解决这个问题,GOT 可以将图像动态裁剪成补丁,一次性处理所有补丁,并合并结果以提高此类输入的准确性。以下是处理裁剪补丁的示例

>>> import torch
>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", torch_dtype=torch.bfloat16, device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/one_column.png"
>>> inputs = processor(image, return_tensors="pt", format=True, crop_to_patches=True, max_patches=3, device=device).to(device)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4096,
... )

>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
"on developing architectural improvements to make learnable matching methods generalize.\nMotivated by the above observations, (...)"

特定区域的推理

GOT 支持交互式 OCR,用户可以通过提供区域的坐标或边界框的颜色来指定要识别的区域。以下是处理特定区域的示例

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
>>> inputs = processor(image, return_tensors="pt", color="green", device=device).to(device) # or box=[x1, y1, x2, y2] for coordinates (image pixels)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4096,
... )

>>> processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
"You should keep in mind what features from the module should be used, especially \nwhen you’re planning to sell a template."

通用 OCR 数据推理示例:乐谱

虽然该模型仅输出纯文本,但可以使用 `pdftex`、`mathpix`、`matplotlib`、`tikz`、`verovio` 或 `pyecharts` 等包对输出进行进一步处理,以呈现所需的格式。以下是处理乐谱的示例

>>> from transformers import AutoProcessor, AutoModelForImageTextToText
>>> import torch
>>> import verovio

>>> device = "cuda" if torch.cuda.is_available() else "cpu"
>>> model = AutoModelForImageTextToText.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", device_map=device)
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf", use_fast=True)

>>> image = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/sheet_music.png"
>>> inputs = processor(image, return_tensors="pt", format=True, device=device).to(device)

>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer=processor.tokenizer,
...     stop_strings="<|im_end|>",
...     max_new_tokens=4096,
... )

>>> outputs = processor.decode(generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True)
>>> tk = verovio.toolkit()
>>> tk.loadData(outputs)
>>> tk.setOptions(
...     {
...         "pageWidth": 2100,
...         "pageHeight": 800,
...         "footer": "none",
...         "barLineWidth": 0.5,
...         "beamMaxSlope": 15,
...         "staffLineWidth": 0.2,
...         "spacingStaff": 6,
...     }
... )
>>> tk.getPageCount()
>>> svg = tk.renderToSVG()
>>> svg = svg.replace('overflow="inherit"', 'overflow="visible"')
>>> with open("output.svg", "w") as f:
>>>     f.write(svg)
drawing

GotOcr2Config

class transformers.GotOcr2Config

< >

( vision_config = None text_config = None image_token_index = 151859 image_seq_length = 576 pad_token_id = -1 **kwargs )

参数

  • vision_config (Union[AutoConfig, dict], 可选, 默认为 CLIPVisionConfig) — 视觉骨干的配置对象或字典。
  • text_config (Union[AutoConfig, dict], 可选, 默认为 LlamaConfig) — 文本骨干的配置对象或字典。
  • image_token_index (int, 可选, 默认为 151859) — 用于编码图像提示的图像 token 索引。
  • image_seq_length (int, 可选, 默认为 576) — 单个图像嵌入的序列长度。
  • pad_token_id (int, 可选, 默认为 -1) — 填充 token ID。

这是一个用于存储 GotOcr2ForConditionalGeneration 配置的配置类。它用于根据指定参数实例化 GotOcr2 模型,定义模型架构。使用默认值实例化配置将产生类似于 GOT-OCR-2.0 的配置。

例如 stepfun-ai/GOT-OCR-2.0-hf

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。

>>> from transformers import GotOcr2ForConditionalGeneration, GotOcr2Config

>>> # Initializing a GotOcr2 style configuration
>>> configuration = GotOcr2Config()

>>> # Initializing a model from the Qwen2-VL-7B style configuration
>>> model = GotOcr2ForConditionalGeneration(configuration)

>>> # Accessing the model configuration
>>> configuration = model.config

GotOcr2VisionConfig

class transformers.GotOcr2VisionConfig

< >

( hidden_size = 768 output_channels = 256 num_hidden_layers = 12 num_attention_heads = 12 num_channels = 3 image_size = 1024 patch_size = 16 hidden_act = 'gelu' layer_norm_eps = 1e-06 attention_dropout = 0.0 initializer_range = 1e-10 qkv_bias = True use_abs_pos = True use_rel_pos = True window_size = 14 global_attn_indexes = [2, 5, 8, 11] mlp_dim = 3072 **kwargs )

参数

  • hidden_size (int, 可选, 默认为 768) — 编码器层和池化层的维度。
  • output_channels (int, 可选, 默认为 256) — 补丁编码器中输出通道的维度。
  • num_hidden_layers (int, 可选, 默认为 12) — Transformer 编码器中的隐藏层数量。
  • num_attention_heads (int, 可选, 默认为 12) — Transformer 编码器中每个注意力层的注意力头数量。
  • num_channels (int, 可选, 默认为 3) — 输入图像中的通道数量。
  • image_size (int, 可选, 默认为 1024) — 预期分辨率。调整大小后的输入图像的目标大小。
  • patch_size (int, 可选, 默认为 16) — 从输入图像中提取的补丁大小。
  • hidden_act (str, 可选, 默认为 "gelu") — 非线性激活函数(函数或字符串)。
  • layer_norm_eps (float, 可选, 默认为 1e-06) — 层归一化层使用的 epsilon。
  • attention_dropout (float, 可选, 默认为 0.0) — 注意力概率的 dropout 比率。
  • initializer_range (float, 可选, 默认为 1e-10) — 用于初始化所有权重矩阵的截断正态初始化器的标准差。
  • qkv_bias (bool, 可选, 默认为 True) — 是否在查询、键、值投影中添加偏置。
  • use_abs_pos (bool, 可选, 默认为 True) — 是否使用绝对位置嵌入。
  • use_rel_pos (bool, 可选, 默认为 True) — 是否使用相对位置嵌入。
  • window_size (int, 可选, 默认为 14) — 相对位置的窗口大小。
  • global_attn_indexes (list[int], 可选, 默认为 [2, 5, 8, 11]) — 全局注意力层的索引。
  • mlp_dim (int, 可选, 默认为 3072) — Transformer 编码器中 MLP 层的维度。

这是用于存储 GotOcr2VisionModel 配置的配置类。它用于根据指定参数实例化 GOT_OCR2 视觉编码器,定义模型架构。实例化默认配置将生成与 SAM ViT-h facebook/sam-vit-huge 架构类似的配置。

配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请参阅 PretrainedConfig 的文档。

GotOcr2ImageProcessor

class transformers.GotOcr2ImageProcessor

< >

( do_resize: bool = True size: typing.Optional[dict[str, int]] = None crop_to_patches: bool = False min_patches: int = 1 max_patches: int = 12 resample: Resampling = <Resampling.BICUBIC: 3> 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 do_convert_rgb: bool = True **kwargs )

参数

  • do_resize (bool, 可选, 默认为 True) — 是否将图像的 (高,宽) 维度调整为指定的 size。可以通过 preprocess 方法中的 do_resize 参数覆盖。
  • size (dict, 可选, 默认为 {"height" -- 384, "width": 384}):调整大小后输出图像的尺寸。可以通过 preprocess 方法中的 size 参数覆盖。
  • crop_to_patches (bool, 可选, 默认为 False) — 是否将图像裁剪成补丁。可以通过 preprocess 方法中的 crop_to_patches 参数覆盖。
  • min_patches (int, 可选, 默认为 1) — 从图像中提取的最小补丁数。仅当 crop_to_patches 设置为 True 时有效。可以通过 preprocess 方法中的 min_patches 参数覆盖。
  • max_patches (int, 可选, 默认为 12) — 从图像中提取的最大补丁数。仅当 crop_to_patches 设置为 True 时有效。可以通过 preprocess 方法中的 max_patches 参数覆盖。
  • resample (PILImageResampling, 可选, 默认为 Resampling.BICUBIC) — 调整图像大小时使用的重采样滤波器。仅当 do_resize 设置为 True 时有效。可以通过 preprocess 方法中的 resample 参数覆盖。
  • do_rescale (bool, 可选, 默认为 True) — 是否按指定比例 rescale_factor 重新缩放图像。可以通过 preprocess 方法中的 do_rescale 参数覆盖。
  • rescale_factor (intfloat, 可选, 默认为 1/255) — 如果重新缩放图像,则使用的缩放因子。仅当 do_rescale 设置为 True 时有效。可以通过 preprocess 方法中的 rescale_factor 参数覆盖。
  • do_normalize (bool, 可选, 默认为 True) — 是否标准化图像。可以通过 preprocess 方法中的 do_normalize 参数覆盖。
  • image_mean (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_MEAN) — 如果标准化图像,则使用的均值。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_mean 参数覆盖。
  • image_std (floatlist[float], 可选, 默认为 IMAGENET_STANDARD_STD) — 如果标准化图像,则使用的标准差。这是一个浮点数或浮点数列表,其长度与图像中的通道数相同。可以通过 preprocess 方法中的 image_std 参数覆盖。
  • do_convert_rgb (bool, 可选, 默认为 True) — 是否将图像转换为 RGB 格式。

构造一个 GOT_OCR2 图像处理器。

crop_image_to_patches

< >

( images: ndarray min_patches: int max_patches: int use_thumbnail: bool = True patch_size: typing.Union[tuple, int, dict, NoneType] = None data_format: ChannelDimension = None ) listPIL.Image.Image 或 list[np.ndarray]

参数

  • images (np.ndarray) — 要裁剪的图像。
  • min_patches (int) — 从图像中提取的最小补丁数。
  • max_patches (int) — 从图像中提取的最大补丁数。
  • use_thumbnail (bool, 可选, 默认为 True) — 是否将缩略图添加到裁剪后的补丁列表中。
  • patch_size (int, tuple[int, int], dict, 可选) — 输出补丁的尺寸。
  • data_format (ChannelDimension, 可选) — 图像数据的格式。如果为 None,则从输入图像推断格式。

返回

listPIL.Image.Image 或 list[np.ndarray]

裁剪后的图像列表。

将图像裁剪为补丁并返回裁剪后的图像列表。补丁的数量和网格排列由原始图像尺寸、目标补丁尺寸以及最小和最大补丁数量决定。补丁网格的纵横比选择为最接近原始图像纵横比的。

get_number_of_image_patches

< >

( height: int width: int images_kwargs = None ) int

参数

  • height (int) — 输入图像的高度。
  • width (int) — 输入图像的宽度。
  • images_kwargs (dict, 可选) — 覆盖图像处理器默认值的任何关键字参数。

返回

int

每张图像的补丁数量。

一个根据给定图像尺寸返回补丁数量的工具函数。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] do_resize: typing.Optional[bool] = None size: typing.Optional[dict[str, int]] = None crop_to_patches: typing.Optional[bool] = None min_patches: typing.Optional[int] = None max_patches: typing.Optional[int] = None resample: Resampling = None do_rescale: typing.Optional[bool] = None rescale_factor: typing.Optional[float] = 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 do_convert_rgb: typing.Optional[bool] = None data_format: ChannelDimension = <ChannelDimension.FIRST: 'channels_first'> input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None )

参数

  • images (ImageInput) — 要预处理的图像。期望单个或批量图像的像素值范围为 0 到 255。如果传入的图像像素值在 0 到 1 之间,请设置 do_rescale=False
  • do_resize (bool, 可选, 默认为 self.do_resize) — 是否调整图像大小。
  • size (dict[str, int], 可选, 默认为 self.size) — 控制 resize 后图像的大小。图像的最短边将调整为 size["shortest_edge"],同时保持纵横比。如果此调整大小后的图像最长边 > int(size["shortest_edge"] * (1333 / 800)),则图像将再次调整大小,使最长边等于 int(size["shortest_edge"] * (1333 / 800))
  • crop_to_patches (bool, 可选, 默认为 self.crop_to_patches) — 是否将图像裁剪成补丁。
  • min_patches (int, 可选, 默认为 self.min_patches) — 从图像中提取的最小补丁数。仅当 crop_to_patches 设置为 True 时有效。
  • max_patches (int, 可选, 默认为 self.max_patches) — 从图像中提取的最大补丁数。仅当 crop_to_patches 设置为 True 时有效。
  • resample (PILImageResampling, 可选, 默认为 self.resample) — 调整图像大小时使用的重采样滤波器。仅当 do_resize 设置为 True 时有效。
  • do_rescale (bool, 可选, 默认为 self.do_rescale) — 是否将图像值重新缩放至 [0 - 1] 之间。
  • rescale_factor (float, 可选, 默认为 self.rescale_factor) — 如果 do_rescale 设置为 True,则用于重新缩放图像的缩放因子。
  • do_normalize (bool, 可选, 默认为 self.do_normalize) — 是否标准化图像。
  • image_mean (floatlist[float], 可选, 默认为 self.image_mean) — 如果 do_normalize 设置为 True,则用于标准化图像的均值。
  • image_std (floatlist[float], 可选, 默认为 self.image_std) — 如果 do_normalize 设置为 True,则用于标准化图像的标准差。
  • do_convert_rgb (bool, 可选, 默认为 self.do_convert_rgb) — 是否将图像转换为 RGB 格式。
  • return_tensors (strTensorType, 可选) — 要返回的张量类型。可以是以下之一:
    • 未设置:返回 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 (ChannelDimensionstr, 可选, 默认为 ChannelDimension.FIRST) — 输出图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • 未设置:使用输入图像的通道维度格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • "none"ChannelDimension.NONE:图像为 (height, width) 格式。

预处理一张或一批图像。

resize

< >

( image: ndarray size: dict resample: Resampling = <Resampling.BICUBIC: 3> data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None input_data_format: typing.Union[str, transformers.image_utils.ChannelDimension, NoneType] = None **kwargs ) np.ndarray

参数

  • image (np.ndarray) — 要调整大小的图像。
  • size (dict[str, int]) — 字典,格式为 {"height": int, "width": int},指定输出图像的尺寸。
  • resample (PILImageResampling, 可选, 默认为 PILImageResampling.BICUBIC) — 调整图像大小时使用的 PILImageResampling 滤波器,例如 PILImageResampling.BICUBIC
  • data_format (ChannelDimensionstr, 可选) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • "none"ChannelDimension.NONE:图像为 (height, width) 格式。
  • input_data_format (ChannelDimensionstr, 可选) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • "none"ChannelDimension.NONE:图像为 (height, width) 格式。

返回

np.ndarray

调整大小后的图像。

将图像调整为 (size["height"], size["width"])

GotOcr2ImageProcessorFast

class transformers.GotOcr2ImageProcessorFast

< >

( **kwargs: typing_extensions.Unpack[transformers.models.got_ocr2.image_processing_got_ocr2_fast.GotOcr2ImageProcessorKwargs] )

构建一个快速 Got Ocr2 图像处理器。

crop_image_to_patches

< >

( images: torch.Tensor min_patches: int max_patches: int use_thumbnail: bool = True patch_size: typing.Union[tuple, int, dict, NoneType] = None interpolation: typing.Optional[ForwardRef('F.InterpolationMode')] = None ) listPIL.Image.Image or list[np.ndarray]

参数

  • images (torch.Tensor) — 要裁剪的图像。
  • min_patches (int) — 从图像中提取的最小补丁数量。
  • max_patches (int) — 从图像中提取的最大补丁数量。
  • use_thumbnail (bool, 可选, 默认为 True) — 是否将缩略图添加到裁剪后的补丁列表中。
  • patch_size (int, tuple[int, int], dict, 可选) — 输出补丁的大小。图像数据的格式。如果为 None,则从输入图像推断格式。

返回

listPIL.Image.Image 或 list[np.ndarray]

裁剪后的图像列表。

将图像裁剪成补丁并返回裁剪后的图像列表。补丁的数量和网格排列由原始图像大小、目标补丁大小以及最小和最大补丁数量决定。补丁网格的宽高比选择最接近原始图像宽高比的值。

get_number_of_image_tokens

< >

( height: int width: int images_kwargs = None ) int

参数

  • height (int) — 输入图像的高度。
  • width (int) — 输入图像的宽度。
  • images_kwargs (dict, 可选) — 任何用于覆盖图像处理器默认值的关键字参数。

返回

int

每张图像的补丁数量。

一个根据给定图像尺寸返回补丁数量的工具函数。

preprocess

< >

( images: typing.Union[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']] **kwargs: typing_extensions.Unpack[transformers.models.got_ocr2.image_processing_got_ocr2_fast.GotOcr2ImageProcessorKwargs] ) <class 'transformers.image_processing_base.BatchFeature'>

参数

  • images (Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]) — 要预处理的图像。期望像素值在 0 到 255 之间的单个图像或批量图像。如果传入像素值在 0 到 1 之间的图像,请设置 do_rescale=False
  • do_resize (bool, 可选) — 是否调整图像大小。
  • size (dict[str, int], 可选) — 描述模型的最大输入尺寸。
  • default_to_square (bool, 可选) — 如果 size 为 int 类型,调整图像大小时是否默认为正方形图像。
  • resample (Union[PILImageResampling, F.InterpolationMode, NoneType]) — 如果调整图像大小,则使用的重采样滤波器。可以是枚举 PILImageResampling 之一。仅当 do_resize 设置为 True 时有效。
  • do_center_crop (bool, 可选) — 是否中心裁剪图像。
  • crop_size (dict[str, int], 可选) — 应用 center_crop 后输出图像的大小。
  • do_rescale (bool, 可选) — 是否重新缩放图像。
  • rescale_factor (Union[int, float, NoneType]) — 如果 do_rescale 设置为 True,则按此重新缩放图像。
  • do_normalize (bool, 可选) — 是否归一化图像。
  • image_mean (Union[float, list[float], NoneType]) — 用于归一化的图像平均值。仅当 do_normalize 设置为 True 时有效。
  • image_std (Union[float, list[float], NoneType]) — 用于归一化的图像标准差。仅当 do_normalize 设置为 True 时有效。
  • do_convert_rgb (bool, 可选) — 是否将图像转换为 RGB。
  • return_tensors (Union[str, ~utils.generic.TensorType, NoneType]) — 如果设置为 `pt`,则返回堆叠张量,否则返回张量列表。
  • data_format (~image_utils.ChannelDimension, 可选) — 仅支持 ChannelDimension.FIRST。为与慢速处理器兼容而添加。
  • input_data_format (Union[str, ~image_utils.ChannelDimension, NoneType]) — 输入图像的通道维度格式。如果未设置,则从输入图像推断通道维度格式。可以是以下之一:
    • "channels_first"ChannelDimension.FIRST:图像为 (num_channels, height, width) 格式。
    • "channels_last"ChannelDimension.LAST:图像为 (height, width, num_channels) 格式。
    • "none"ChannelDimension.NONE:图像为 (height, width) 格式。
  • device (torch.device, 可选) — 处理图像的设备。如果未设置,则从输入图像推断设备。
  • disable_grouping (bool, 可选) — 是否禁用按大小对图像进行分组以单独处理而不是批量处理。如果为 None,则如果图像在 CPU 上,则将其设置为 True,否则设置为 False。此选择基于经验观察,详情请参阅此处:https://github.com/huggingface/transformers/pull/38157
  • crop_to_patches (bool, 可选, 默认为 False) — 是否将图像裁剪成补丁。可以通过 preprocess 方法中的 crop_to_patches 参数覆盖。
  • min_patches (int, 可选, 默认为 1) — 从图像中提取的最小补丁数量。仅当 crop_to_patches 设置为 True 时有效。可以通过 preprocess 方法中的 min_patches 参数覆盖。
  • max_patches (int, 可选, 默认为 12) — 从图像中提取的最大补丁数量。仅当 crop_to_patches 设置为 True 时有效。可以通过 preprocess 方法中的 max_patches 参数覆盖。

返回

<class 'transformers.image_processing_base.BatchFeature'>

  • data (dict) — 由 call 方法返回的列表/数组/张量字典(“pixel_values”等)。
  • tensor_type (Union[None, str, TensorType], 可选) — 您可以在此处提供一个`tensor_type`,以便在初始化时将整数列表转换为PyTorch/TensorFlow/Numpy张量。

GotOcr2Processor

class transformers.GotOcr2Processor

< >

( image_processor = None tokenizer = None chat_template = None **kwargs )

参数

  • image_processor (GotOcr2ImageProcessor, 可选) — 图像处理器是必需的输入。
  • tokenizer ([PreTrainedTokenizer, PreTrainedTokenizerFast], 可选) — 分词器是必需的输入。
  • chat_template (str, 可选) — 一个 Jinja 模板,用于将聊天中的消息列表转换为可标记化的字符串。

构建一个 GotOcr2 处理器,它将 GotOcr2ImageProcessorPretrainedTokenizerFast 分词器包装成一个继承图像处理器和分词器功能的单一处理器。有关更多信息,请参阅 __call__()decode() 的文档字符串。

batch_decode

< >

( *args **kwargs )

此方法将其所有参数转发到 PreTrainedTokenizerFast 的 batch_decode()。有关更多信息,请参阅此方法的文档字符串。

decode

< >

( *args **kwargs )

此方法将其所有参数转发到 PreTrainedTokenizerFast 的 decode()。有关更多信息,请参阅此方法的文档字符串。

GotOcr2Model

class transformers.GotOcr2Model

< >

( config: GotOcr2Config )

参数

  • config (GotOcr2Config) — 包含模型所有参数的模型配置类。使用配置文件初始化不加载与模型关联的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。

GotOcr2 模型由视觉骨干和语言模型组成,不带语言建模头。

此模型继承自 PreTrainedModel。请查看超类文档以获取库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None **kwargs: typing_extensions.Unpack[transformers.modeling_flash_attention_utils.FlashAttentionKwargs] ) transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2ModelOutputWithPast or tuple(torch.FloatTensor)

参数

  • input_ids (torch.LongTensor,形状为 (batch_size, sequence_length)) — 词汇表中输入序列标记的索引。默认情况下将忽略填充。

    可以使用 AutoTokenizer 获取索引。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • pixel_values (torch.FloatTensor,形状为 (batch_size, num_channels, image_size, image_size)) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 处理图像)。
  • attention_mask (torch.Tensor,形状为 (batch_size, sequence_length)可选) — 掩码,以避免在填充标记索引上执行注意力。掩码值选择在 [0, 1] 之间:

    • 1 表示未被掩盖的标记,
    • 0 表示被掩盖的标记。

    什么是注意力掩码?

  • position_ids (torch.LongTensor,形状为 (batch_size, sequence_length)可选) — 每个输入序列标记在位置嵌入中的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

  • past_key_values (list[torch.FloatTensor], 可选) — 预计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括模型在解码前一阶段返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    允许两种格式:

    • 一个 Cache 实例,请参阅我们的 kv cache 指南
    • config.n_layers 长度的 tuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)。这也被称为旧版缓存格式。

    模型将输出与作为输入提供的缓存格式相同的缓存格式。如果未传递 past_key_values,则将返回旧版缓存格式。

    如果使用 past_key_values,用户可以选择仅输入形状为 (batch_size, 1) 的最新 input_ids(那些未将其过去的键值状态提供给此模型的),而不是形状为 (batch_size, sequence_length) 的所有 input_ids

  • inputs_embeds (torch.FloatTensor,形状为 (batch_size, sequence_length, hidden_size)可选) — 可选地,您可以直接传递嵌入表示,而不是传递 input_ids。如果您希望对 input_ids 索引转换为关联向量的方式有更多控制,而不是模型内部的嵌入查找矩阵,这会很有用。
  • use_cache (bool, 可选) — 如果设置为 True,则返回 past_key_values 键值状态,可用于加速解码(参见 past_key_values)。
  • output_attentions (bool, 可选) — 是否返回所有注意力层的注意力张量。有关更多详细信息,请参阅返回张量中的 attentions
  • output_hidden_states (bool, optional) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 `hidden_states`。
  • return_dict (bool, optional) — 是否返回 ModelOutput 而不是普通的元组。
  • cache_position (形状为 (sequence_length)torch.LongTensor可选) — 表示输入序列中令牌位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。

返回

transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2ModelOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2ModelOutputWithPast 或一个 torch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),其中包含根据配置 (GotOcr2Config) 和输入的不同元素。

  • last_hidden_state (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor, 可选) — 模型最后一层输出的隐藏状态序列。

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple[torch.FloatTensor, ...]可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(如果模型具有嵌入层,则一个用于嵌入输出,加上每个层的一个输出)。

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor, ...]可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元组(每层一个)。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • image_hidden_states (torch.FloatTensor可选) — 形状为 (batch_size, num_images, sequence_length, hidden_size)torch.FloatTensor。由视觉编码器生成并投影最后一个隐藏状态后的模型的图像隐藏状态。

GotOcr2Model 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然前向传递的实现需要在该函数中定义,但此后应调用 `Module` 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则静默忽略它们。

get_image_features

< >

( pixel_values: FloatTensor ) image_features (torch.Tensor)

参数

  • pixel_values (形状为 (batch_size, channels, height, width)torch.FloatTensor]) —

返回

image_features (torch.Tensor)

形状为 (num_images, image_length, embed_dim) 的图像特征张量。

从视觉塔获取图像最后隐藏状态并应用多模态投影。

GotOcr2ForConditionalGeneration

class transformers.GotOcr2ForConditionalGeneration

< >

( config: GotOcr2Config )

参数

  • config (GotOcr2Config) — 模型配置类,包含模型的所有参数。使用配置文件初始化不会加载与模型相关的权重,只加载配置。请查看 from_pretrained() 方法加载模型权重。

GOT_OCR2 模型由视觉骨干和语言模型组成。

此模型继承自 PreTrainedModel。请查看超类文档以获取库为其所有模型实现的一般方法(例如下载或保存、调整输入嵌入大小、修剪头部等)。

此模型也是 PyTorch torch.nn.Module 子类。将其作为常规 PyTorch 模块使用,并参考 PyTorch 文档中所有与一般用法和行为相关的事项。

forward

< >

( input_ids: LongTensor = None pixel_values: FloatTensor = None attention_mask: typing.Optional[torch.Tensor] = None position_ids: typing.Optional[torch.LongTensor] = None past_key_values: typing.Optional[list[torch.FloatTensor]] = None inputs_embeds: typing.Optional[torch.FloatTensor] = None labels: typing.Optional[torch.LongTensor] = None use_cache: typing.Optional[bool] = None output_attentions: typing.Optional[bool] = None output_hidden_states: typing.Optional[bool] = None return_dict: typing.Optional[bool] = None cache_position: typing.Optional[torch.LongTensor] = None logits_to_keep: typing.Union[int, torch.Tensor] = 0 **kwargs: typing_extensions.Unpack[transformers.models.got_ocr2.modeling_got_ocr2.KwargsForCausalLM] ) transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2CausalLMOutputWithPasttuple(torch.FloatTensor)

参数

  • input_ids (形状为 (batch_size, sequence_length)torch.LongTensor) — 词汇表中输入序列令牌的索引。默认情况下将忽略填充。

    索引可以使用 AutoTokenizer 获取。有关详细信息,请参阅 PreTrainedTokenizer.encode()PreTrainedTokenizer.call()

    什么是输入 ID?

  • pixel_values (形状为 (batch_size, num_channels, image_size, image_size)torch.FloatTensor) — 对应于输入图像的张量。像素值可以使用 {image_processor_class} 获取。有关详细信息,请参阅 {image_processor_class}.__call__{processor_class} 使用 {image_processor_class} 进行图像处理)。
  • attention_mask (形状为 (batch_size, sequence_length)torch.Tensor可选) — 掩码,用于避免对填充令牌索引执行注意力。掩码值选择在 [0, 1] 之间:

    • 1 表示**未被掩码**的令牌,
    • 0 表示**被掩码**的令牌。

    什么是注意力掩码?

  • position_ids (形状为 (batch_size, sequence_length)torch.LongTensor可选) — 每个输入序列令牌在位置嵌入中的位置索引。选择范围为 [0, config.n_positions - 1]

    什么是位置 ID?

  • past_key_values (list[torch.FloatTensor]可选) — 预先计算的隐藏状态(自注意力块和交叉注意力块中的键和值),可用于加速顺序解码。这通常包括模型在解码上一阶段返回的 past_key_values,当 use_cache=Trueconfig.use_cache=True 时。

    允许两种格式:

    • 一个 Cache 实例,请参阅我们的 kv 缓存指南
    • 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量)。这也被称为旧版缓存格式。

    模型将输出与输入相同的缓存格式。如果没有传入 past_key_values,将返回旧版缓存格式。

    如果使用 past_key_values,用户可以选择只输入最后一个 input_ids(那些没有将其过去的键值状态提供给此模型的)形状为 (batch_size, 1),而不是所有 input_ids 形状为 (batch_size, sequence_length)

  • inputs_embeds (形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor可选) — 可选地,您可以选择直接传入嵌入表示,而不是传入 input_ids。如果您希望对 input_ids 索引如何转换为关联向量有比模型内部嵌入查找矩阵更多的控制,这将非常有用。
  • labels (形状为 (batch_size, sequence_length)torch.LongTensor可选) — 用于计算掩码语言建模损失的标签。索引应在 [0, ..., config.vocab_size] 或 -100 之间(参见 input_ids 文档字符串)。索引设置为 -100 的令牌将被忽略(掩码),损失仅针对标签在 [0, ..., config.vocab_size] 中的令牌计算。
  • use_cache (bool可选) — 如果设置为 True,将返回 past_key_values 键值状态,并可用于加速解码(参见 past_key_values)。
  • output_attentions (bool可选) — 是否返回所有注意力层的注意力张量。有关详细信息,请参阅返回张量下的 `attentions`。
  • output_hidden_states (bool可选) — 是否返回所有层的隐藏状态。有关详细信息,请参阅返回张量下的 `hidden_states`。
  • return_dict (bool可选) — 是否返回 ModelOutput 而不是普通的元组。
  • cache_position (形状为 (sequence_length)torch.LongTensor可选) — 表示输入序列中令牌位置的索引。与 position_ids 不同,此张量不受填充影响。它用于在正确位置更新缓存并推断完整的序列长度。
  • logits_to_keep (Union[int, torch.Tensor],默认为 0) — 如果是 int,则计算最后 logits_to_keep 个令牌的对数。如果是 0,则计算所有 input_ids 的对数(特殊情况)。生成时只需要最后一个令牌的对数,并且仅计算该令牌的对数可以节省内存,这对于长序列或大词汇量来说非常显著。如果是 torch.Tensor,则必须是 1D,对应于序列长度维度中要保留的索引。这在使用打包张量格式(批量和序列长度的单维度)时很有用。

返回

transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2CausalLMOutputWithPasttuple(torch.FloatTensor)

一个 transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2CausalLMOutputWithPast 或一个 torch.FloatTensor 元组(如果传递 return_dict=False 或当 config.return_dict=False 时),其中包含根据配置 (GotOcr2Config) 和输入的不同元素。

  • loss (torch.FloatTensor 形状为 (1,)可选,当提供 labels 时返回) — 语言建模损失(用于下一个 token 预测)。

  • logits (形状为 (batch_size, sequence_length, config.vocab_size)torch.FloatTensor) — 语言建模头部的预测分数(SoftMax 之前的每个词汇标记的分数)。

  • past_key_values (tuple(tuple(torch.FloatTensor))可选,当传递 use_cache=True 或当 config.use_cache=True 时返回) — 长度为 config.n_layerstuple(torch.FloatTensor) 元组,每个元组包含 2 个形状为 (batch_size, num_heads, sequence_length, embed_size_per_head) 的张量。

    包含预计算的隐藏状态(自注意力块中的键和值),可用于(参见 past_key_values 输入)加速顺序解码。

  • hidden_states (tuple[torch.FloatTensor]可选,当传递 output_hidden_states=True 或当 config.output_hidden_states=True 时返回) — 形状为 (batch_size, sequence_length, hidden_size)torch.FloatTensor 元组(如果模型具有嵌入层,则一个用于嵌入输出,加上每个层的一个输出)。

    模型在每个层输出的隐藏状态以及可选的初始嵌入输出。

  • attentions (tuple[torch.FloatTensor]可选,当传递 output_attentions=True 或当 config.output_attentions=True 时返回) — 形状为 (batch_size, num_heads, sequence_length, sequence_length)torch.FloatTensor 元组(每层一个)。

    注意力 softmax 后的注意力权重,用于计算自注意力头中的加权平均值。

  • image_hidden_states (torch.FloatTensor可选) — 形状为 (batch_size, num_images, sequence_length, hidden_size)torch.FloatTensor。由视觉编码器生成并投影最后一个隐藏状态后的模型的图像隐藏状态。

GotOcr2ForConditionalGeneration 的 forward 方法,覆盖了 __call__ 特殊方法。

虽然前向传递的实现需要在该函数中定义,但此后应调用 `Module` 实例而不是此函数,因为前者负责运行预处理和后处理步骤,而后者则静默忽略它们。

示例

>>> from PIL import Image
>>> import requests
>>> from transformers import AutoProcessor, GotOcr2ForConditionalGeneration, TextStreamer

>>> model = GotOcr2ForConditionalGeneration.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf").to("cuda")
>>> processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")

>>> url = "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
>>> image = Image.open(requests.get(url, stream=True).raw)

>>> inputs = processor(image, return_tensors="pt", color="green").to("cuda")

>>> # Generate
>>> streamer = TextStreamer(processor.tokenizer, skip_prompt=True, skip_special_tokens=True)
>>> generate_ids = model.generate(
...     **inputs,
...     do_sample=False,
...     tokenizer = processor.tokenizer,
...     stop_strings='<|im_end|>',
...     streamer=streamer,
...     max_new_tokens=4096,
... )
"You should keep in mind what features from the module should be used, especially
when you're planning to sell a template."
< > 在 GitHub 上更新