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

提示
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 ""} Arjun Karpur{@html ""} Bingyi Cao{@html ""} (...)"
多页推理
虽然在大多数情况下使用“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)
GotOcr2Config
class transformers.GotOcr2Config
< source >( vision_config = None text_config = None image_token_index = 151859 image_seq_length = 576 pad_token_id = -1 **kwargs )
参数
- vision_config (
Union[AutoConfig, dict]
, optional, defaults toCLIPVisionConfig
) — 视觉骨干网络的配置对象或字典(config object or dictionary
)。 - text_config (
Union[AutoConfig, dict]
, optional, defaults toLlamaConfig
) — 文本骨干网络的配置对象或字典(config object or dictionary
)。 - image_token_index (
int
, optional, defaults to 151859) — 用于编码图像提示的图像令牌索引(image token index
)。 - image_seq_length (
int
, optional, defaults to 576) — 一个图像嵌入的序列长度(sequence length
)。 - pad_token_id (
int
, optional, defaults to -1) — 填充令牌 ID(padding token id
)。
这是用于存储 GotOcr2ForConditionalGeneration 配置的配置类。它用于根据指定的参数实例化 GotOcr2 模型,从而定义模型架构。使用默认值实例化配置将产生与 GOT-OCR-2.0 类似的配置。
配置对象继承自 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
, optional, defaults to 768) — 编码器层和池化器层的维度(dimensionality
)。 - output_channels (
int
, optional, defaults to 256) — Patch Encoder 中输出通道的维度(dimensionality
)。 - num_hidden_layers (
int
, optional, defaults to 12) — Transformer 编码器中隐藏层的数量。 - num_attention_heads (
int
, optional, defaults to 12) — Transformer 编码器中每个注意力层的注意力头数。 - num_channels (
int
, optional, defaults to 3) — 输入图像中的通道数。 - image_size (
int
, optional, defaults to 1024) — 预期分辨率。调整大小后的输入图像的目标大小。 - patch_size (
int
, optional, defaults to 16) — 从输入图像中提取的 patch 的大小。 - hidden_act (
str
, optional, defaults to"gelu"
) — 非线性激活函数(函数或字符串)。 - layer_norm_eps (
float
, optional, defaults to 1e-06) — 层归一化层使用的 epsilon 值。 - attention_dropout (
float
, optional, defaults to 0.0) — 注意力概率的 dropout 比率。 - initializer_range (
float
, optional, defaults to 1e-10) — 用于初始化所有权重矩阵的 truncated_normal_initializer 的标准差。 - qkv_bias (
bool
, optional, defaults toTrue
) — 是否向 query、key、value 投影添加偏置。 - use_abs_pos (
bool
, optional, defaults toTrue
) — 是否使用绝对位置嵌入。 - use_rel_pos (
bool
, optional, defaults toTrue
) — 是否使用相对位置嵌入。 - window_size (
int
, optional, defaults to 14) — 相对位置的窗口大小。 - global_attn_indexes (
List[int]
, optional, defaults to[2, 5, 8, 11]
) — 全局注意力层的索引。 - mlp_dim (
int
, optional, defaults to 3072) — Transformer 编码器中 MLP 层的维度(dimensionality
)。
这是用于存储 GotOcr2VisionModel
配置的配置类。它用于根据指定的参数实例化 GOT_OCR2 视觉编码器,从而定义模型架构。实例化默认配置将产生与 SAM ViT-h facebook/sam-vit-huge 架构类似的配置。
配置对象继承自 PretrainedConfig,可用于控制模型输出。有关更多信息,请阅读 PretrainedConfig 的文档。
GotOcr2ImageProcessor
class transformers.GotOcr2ImageProcessor
< source >( do_resize: bool = True size: typing.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, typing.List[float], NoneType] = None image_std: typing.Union[float, typing.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 (
int
或float
, 可选, 默认为1/255
) — 如果缩放图像,则使用的比例因子。仅当do_rescale
设置为True
时有效。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, 可选, 默认为True
) — 是否对图像进行归一化。可以被preprocess
方法中的do_normalize
参数覆盖。 可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
或List[float]
, 可选, 默认为IMAGENET_STANDARD_MEAN
) — 如果对图像进行归一化,则使用的均值。这是一个浮点数或浮点数列表,其长度为图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。 可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
或List[float]
, 可选, 默认为IMAGENET_STANDARD_STD
) — 如果对图像进行归一化,则使用的标准差。这是一个浮点数或浮点数列表,其长度为图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。 可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, 可选, 默认为True
) — 是否将图像转换为 RGB 格式。
构建 GOT_OCR2 图像处理器。
crop_image_to_patches
< source >( images: ndarray min_patches: int max_patches: int use_thumbnail: bool = True patch_size: typing.Union[typing.Tuple, int, dict] = None data_format: ChannelDimension = None ) → ListPIL.Image.Image
or 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
or List[np.ndarray]
裁剪后的图像列表。
将图像裁剪为图像块,并返回裁剪后的图像列表。图像块的数量及其网格排列由原始图像大小、目标图像块大小以及最小和最大图像块数量决定。图像块网格的纵横比选择为最接近原始图像纵横比。
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_resize: typing.Optional[bool] = None size: typing.Optional[typing.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, 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 do_convert_rgb: 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
, optional, defaults toself.min_patches
) — 从图像中提取的最小图块数。仅当crop_to_patches
设置为True
时有效。 - max_patches (
int
, optional, defaults toself.max_patches
) — 从图像中提取的最大图块数。仅当crop_to_patches
设置为True
时有效。 - resample (
PILImageResampling
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样过滤器。仅当do_resize
设置为True
时有效。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否将图像值重新缩放到 [0 - 1] 之间。 - rescale_factor (
float
, optional, defaults toself.rescale_factor
) — 如果do_rescale
设置为True
,则通过此比例因子重新缩放图像。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
orList[float]
, optional, defaults toself.image_mean
) — 如果do_normalize
设置为True
,则用于归一化图像的图像均值。 - image_std (
float
orList[float]
, optional, defaults toself.image_std
) — 如果do_normalize
设置为True
,则用于归一化图像的图像标准差。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
orTensorType
, optional) — 返回张量的类型。可以是以下之一:- 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
orstr
, optional, defaults toChannelDimension.FIRST
) — 输出图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。- Unset: 使用输入图像的通道维度格式。
- input_data_format (
ChannelDimension
orstr
, optional) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
预处理图像或一批图像。
调整大小
< source >( image: ndarray size: typing.Dict[str, int] 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
, optional, defaults toPILImageResampling.BICUBIC
) — 调整图像大小时使用的PILImageResampling
过滤器,例如PILImageResampling.BICUBIC
。 - data_format (
ChannelDimension
orstr
, optional) — 输出图像的通道维度格式。如果未设置,则使用输入图像的通道维度格式。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
: 图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
: 图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
: 图像格式为 (height, width)。
- input_data_format (
ChannelDimension
orstr
, optional) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"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
< source >( **kwargs: typing_extensions.Unpack[transformers.models.got_ocr2.image_processing_got_ocr2_fast.GotOcr2ImageProcessorKwargs] )
参数
- do_resize (
bool
, optional, defaults toself.do_resize
) — 是否将图像的(高度,宽度)尺寸调整为指定的size
。可以被preprocess
方法中的do_resize
参数覆盖。 - size (
dict
, optional, defaults toself.size
) — 调整大小后输出图像的大小。可以被preprocess
方法中的size
参数覆盖。 - default_to_square (
bool
, optional, defaults toself.default_to_square
) — 如果 size 是整数,是否默认调整为方形图像。 - resample (
PILImageResampling
, optional, defaults toself.resample
) — 如果调整图像大小,则使用的重采样过滤器。仅当do_resize
设置为True
时有效。可以被preprocess
方法中的resample
参数覆盖。 - do_center_crop (
bool
, optional, defaults toself.do_center_crop
) — 是否将图像中心裁剪到指定的crop_size
大小。可以被preprocess
方法中的do_center_crop
参数覆盖。 - crop_size (
Dict[str, int]
optional, defaults toself.crop_size
) — 应用center_crop
后输出图像的大小。可以被preprocess
方法中的crop_size
参数覆盖。 - do_rescale (
bool
, optional, defaults toself.do_rescale
) — 是否根据指定的缩放比例rescale_factor
缩放图像。可以被preprocess
方法中的do_rescale
参数覆盖。 - rescale_factor (
int
orfloat
, optional, defaults toself.rescale_factor
) — 如果缩放图像,则使用的缩放因子。仅当do_rescale
设置为True
时才有效。可以被preprocess
方法中的rescale_factor
参数覆盖。 - do_normalize (
bool
, optional, defaults toself.do_normalize
) — 是否对图像进行标准化。可以被preprocess
方法中的do_normalize
参数覆盖。可以被preprocess
方法中的do_normalize
参数覆盖。 - image_mean (
float
orList[float]
, optional, defaults toself.image_mean
) — 标准化图像时使用的均值。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_mean
参数覆盖。可以被preprocess
方法中的image_mean
参数覆盖。 - image_std (
float
orList[float]
, optional, defaults toself.image_std
) — 标准化图像时使用的标准差。这是一个浮点数或浮点数列表,其长度等于图像中的通道数。可以被preprocess
方法中的image_std
参数覆盖。可以被preprocess
方法中的image_std
参数覆盖。 - do_convert_rgb (
bool
, optional, defaults toself.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
orTensorType
, optional, defaults toself.return_tensors
) — 如果设置为 `pt`,则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
orstr
, optional, defaults toself.data_format
) — 仅支持ChannelDimension.FIRST
。为与慢速处理器兼容而添加。 - input_data_format (
ChannelDimension
orstr
, optional, defaults toself.input_data_format
) — 输入图像的通道维度格式。如果未设置,则通道维度格式从输入图像推断。可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, optional, defaults toself.device
) — 处理图像的设备。如果未设置,则设备从输入图像推断。 - crop_to_patches (
bool
, optional, defaults toFalse
) — 是否将图像裁剪为 patches。可以被preprocess
方法中的crop_to_patches
参数覆盖。 - min_patches (
int
, optional, defaults to 1) — 从图像中提取的最小 patches 数量。仅当crop_to_patches
设置为True
时才有效。可以被preprocess
方法中的min_patches
参数覆盖。 - max_patches (
int
, optional, defaults to 12) — 从图像中提取的最大 patches 数量。仅当crop_to_patches
设置为True
时才有效。可以被preprocess
方法中的max_patches
参数覆盖。
构建一个快速的 GotOcr2 图像处理器。
crop_image_to_patches
< source >( images: torch.Tensor min_patches: int max_patches: int use_thumbnail: bool = True patch_size: typing.Union[typing.Tuple, int, dict] = None interpolation: typing.Optional[ForwardRef('F.InterpolationMode')] = None ) → ListPIL.Image.Image
or List[np.ndarray]
参数
- images (
torch.Tensor
) — 要裁剪的图像。 - min_patches (
int
) — 从图像中提取的最小 patches 数量。 - max_patches (
int
) — 从图像中提取的最大 patches 数量。 - use_thumbnail (
bool
, optional, defaults toTrue
) — 是否向裁剪的 patches 列表添加缩略图图像。 - patch_size (
int
,Tuple[int, int]
,dict
, optional) — 输出 patches 的大小。图像数据的格式。如果为None
,则格式从输入图像推断。
返回值
ListPIL.Image.Image
or List[np.ndarray]
裁剪后的图像列表。
将图像裁剪为 patches 并返回裁剪图像的列表。patches 的数量及其网格排列方式由原始图像大小、目标 patch 大小以及最小和最大 patches 数量决定。patches 网格的纵横比被选择为最接近原始图像纵横比。
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: typing_extensions.Unpack[transformers.models.got_ocr2.image_processing_got_ocr2_fast.GotOcr2ImageProcessorKwargs] )
参数
- images (
ImageInput
) — 要预处理的图像。 期望输入像素值范围在 0 到 255 之间的单张或批量图像。如果传入的图像像素值在 0 到 1 之间,请设置do_rescale=False
。 - do_resize (
bool
, optional, defaults toself.do_resize
) — 是否调整图像大小。 - size (
Dict[str, int]
, optional, defaults toself.size
) — 描述模型的最大输入尺寸。 - resample (
PILImageResampling
或InterpolationMode
, 可选, 默认为self.resample
) — 如果调整图像大小,则使用的重采样滤波器。 可以是枚举类型PILImageResampling
之一。 仅当do_resize
设置为True
时才有效。 - do_center_crop (
bool
, 可选, 默认为self.do_center_crop
) — 是否对图像进行中心裁剪。 - crop_size (
Dict[str, int]
, 可选, 默认为self.crop_size
) — 应用center_crop
后输出图像的尺寸。 - do_rescale (
bool
, 可选, 默认为self.do_rescale
) — 是否对图像进行重新缩放。 - rescale_factor (
float
, 可选, 默认为self.rescale_factor
) — 如果do_rescale
设置为True
,则用于重新缩放图像的缩放因子。 - do_normalize (
bool
, 可选, 默认为self.do_normalize
) — 是否对图像进行归一化。 - image_mean (
float
或List[float]
, 可选, 默认为self.image_mean
) — 用于归一化的图像均值。 仅当do_normalize
设置为True
时才有效。 - image_std (
float
或List[float]
, 可选, 默认为self.image_std
) — 用于归一化的图像标准差。 仅当do_normalize
设置为True
时才有效。 - do_convert_rgb (
bool
, 可选, 默认为self.do_convert_rgb
) — 是否将图像转换为 RGB 格式。 - return_tensors (
str
或TensorType
, 可选, 默认为self.return_tensors
) — 如果设置为 'pt',则返回堆叠的张量,否则返回张量列表。 - data_format (
ChannelDimension
或str
, 可选, 默认为self.data_format
) — 仅支持ChannelDimension.FIRST
。 添加此项是为了与慢速处理器兼容。 - input_data_format (
ChannelDimension
或str
, 可选, 默认为self.input_data_format
) — 输入图像的通道维度格式。 如果未设置,则通道维度格式从输入图像推断。 可以是以下之一:"channels_first"
或ChannelDimension.FIRST
:图像格式为 (num_channels, height, width)。"channels_last"
或ChannelDimension.LAST
:图像格式为 (height, width, num_channels)。"none"
或ChannelDimension.NONE
:图像格式为 (height, width)。
- device (
torch.device
, 可选, 默认为self.device
) — 用于处理图像的设备。 如果未设置,则设备从输入图像推断。 crop_to_patches (bool
, 可选, 默认为False
): 是否将图像裁剪为 patches。 可以被preprocess
方法中的crop_to_patches
参数覆盖。 min_patches (int
, 可选, 默认为 1): 从图像中提取的最小 patch 数量。 仅当crop_to_patches
设置为True
时才有效。 可以被preprocess
方法中的min_patches
参数覆盖。 max_patches (int
, 可选, 默认为 12): 从图像中提取的最大 patch 数量。 仅当crop_to_patches
设置为True
时才有效。 可以被preprocess
方法中的max_patches
参数覆盖。
预处理图像或一批图像。
GotOcr2Processor
class transformers.GotOcr2Processor
< source >( image_processor = None tokenizer = None chat_template = None **kwargs )
参数
- image_processor (GotOcr2ImageProcessor, 可选) — 图像处理器是必需的输入。
- tokenizer ([
PreTrainedTokenizer
,PreTrainedTokenizerFast
], 可选) — tokenizer 是必需的输入。 - chat_template (
str
, 可选) — Jinja 模板,用于将聊天中的消息列表转换为可标记化的字符串。
构造一个 GotOcr2 processor,它将 GotOcr2ImageProcessor 和 PretrainedTokenizerFast
tokenizer 封装到一个单独的 processor 中,该 processor 继承了图像处理器和 tokenizer 的功能。 有关更多信息,请参见 __call__()
和 decode() 。
此方法将其所有参数转发到 PreTrainedTokenizerFast 的 batch_decode()。 有关更多信息,请参阅此方法的文档字符串。
此方法将其所有参数转发到 PreTrainedTokenizerFast 的 decode()。 有关更多信息,请参阅此方法的文档字符串。
GotOcr2ForConditionalGeneration
class transformers.GotOcr2ForConditionalGeneration
< source >( config: GotOcr2Config )
参数
- config (GotOcr2Config 或 GotOcr2VisionConfig) — 带有模型所有参数的模型配置类。 使用配置文件初始化不会加载与模型关联的权重,仅加载配置。 查看 from_pretrained() 方法以加载模型权重。
GOT_OCR2 模型由视觉骨干网络和语言模型组成。 此模型继承自 PreTrainedModel。 查看超类文档,了解库为其所有模型实现的通用方法(例如,下载或保存、调整输入嵌入大小、剪枝头等)。
此模型也是 PyTorch torch.nn.Module 子类。 将其用作常规 PyTorch Module,并参阅 PyTorch 文档,了解与常规用法和行为相关的所有事项。
forward
< source >( 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[typing.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 ) → transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2CausalLMOutputWithPast
或 tuple(torch.FloatTensor)
参数
- input_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
) — 词汇表中输入序列 tokens 的索引。 默认情况下,如果您提供 padding,则 padding 将被忽略。索引可以使用 AutoTokenizer 获得。 有关详细信息,请参见 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call() 。
- pixel_values (
torch.FloatTensor
,形状为(seq_length, num_channels * image_size * image_size)
) — 对应于输入图像的张量。像素值可以使用 AutoImageProcessor 获得。 详情请参阅 GotOcr2ImageProcessor.call()。 GotOcr2Processor 使用 GotOcr2ImageProcessor 处理图像。 - attention_mask (
torch.Tensor
,形状为(batch_size, sequence_length)
,可选) — 用于避免对填充 token 索引执行 attention 的掩码。掩码值在[0, 1]
中选择:- 1 表示 token 未被掩码,
- 0 表示 token 已被掩码。
索引可以使用 AutoTokenizer 获得。 详情请参阅 PreTrainedTokenizer.encode() 和 PreTrainedTokenizer.call()。
如果使用
past_key_values
,则可以选择仅输入最后一个decoder_input_ids
(请参阅past_key_values
)。如果您想更改填充行为,您应该阅读
modeling_opt._prepare_decoder_attention_mask
并根据您的需求进行修改。 有关默认策略的更多信息,请参阅 论文 中的图 1。- 1 表示 head 未被掩码,
- 0 表示 head 已被掩码。
- position_ids (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 位置嵌入中每个输入序列 token 的位置索引。在范围[0, config.n_positions - 1]
中选择。 什么是 position IDs? - past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
,其中每个 tuple 有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量,以及 2 个形状为(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)
的额外张量。包含预先计算的 hidden-states(self-attention 块和 cross-attention 块中的 key 和 values),可以用于(参见
past_key_values
输入)加速顺序解码。如果使用
past_key_values
,用户可以选择仅输入最后一个decoder_input_ids
(那些没有将其 past key value states 提供给此模型的)形状为(batch_size, 1)
,而不是所有形状为(batch_size, sequence_length)
的decoder_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
,可选) — 是否返回所有 attention 层的 attentions 张量。 有关更多详细信息,请参阅返回张量下的attentions
。 - output_hidden_states (
bool
,可选) — 是否返回所有层的 hidden states。 有关更多详细信息,请参阅返回张量下的hidden_states
。 - return_dict (
bool
,可选) — 是否返回 ModelOutput 而不是普通元组。 - cache_position (
torch.LongTensor
,形状为(sequence_length)
,可选) — 描述输入序列 token 在序列中位置的索引。 与position_ids
相反,此张量不受填充的影响。 它用于在正确的位置更新缓存并推断完整的序列长度。 - labels (
torch.LongTensor
,形状为(batch_size, sequence_length)
,可选) — 用于计算 masked language modeling loss 的标签。 索引应为[0, ..., config.vocab_size]
或 -100(请参阅input_ids
文档字符串)。 索引设置为-100
的 token 将被忽略(掩码),loss 仅针对标签在[0, ..., config.vocab_size]
中的 token 计算。 - logits_to_keep (
int
或torch.Tensor
,可选) — 如果为int
,则计算最后logits_to_keep
个 token 的 logits。 如果为0
,则计算所有input_ids
的 logits(特殊情况)。 仅生成最后一个 token logits 是必需的,并且仅针对该 token 计算它们可以节省内存,这对于长序列或大词汇量而言变得非常重要。 如果为torch.Tensor
,则必须是 1D,对应于在序列长度维度中要保留的索引。 这在使用 packed tensor 格式(批次和序列长度的单个维度)时非常有用。
返回值
transformers.models.got_ocr2.modeling_got_ocr2.GotOcr2CausalLMOutputWithPast
或 tuple(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 (
torch.FloatTensor
,形状为(batch_size, sequence_length, config.vocab_size)
) — 语言建模 head 的预测分数(SoftMax 之前每个词汇 token 的分数)。 -
past_key_values (
tuple(tuple(torch.FloatTensor))
,可选,当传递use_cache=True
或config.use_cache=True
时返回) — 长度为config.n_layers
的tuple(tuple(torch.FloatTensor))
,其中每个 tuple 有 2 个形状为(batch_size, num_heads, sequence_length, embed_size_per_head)
的张量)包含预先计算的 hidden-states(self-attention 块中的 key 和 values),可以用于(参见
past_key_values
输入)加速顺序解码。 -
hidden_states (
tuple(torch.FloatTensor)
,可选,当传递output_hidden_states=True
或config.output_hidden_states=True
时返回) —torch.FloatTensor
的元组(如果模型具有嵌入层,则为嵌入输出一个,+ 每个层的输出一个),形状为(batch_size, sequence_length, hidden_size)
。模型在每一层输出的 hidden-states 加上可选的初始嵌入输出。
-
attentions (
tuple(torch.FloatTensor)
,可选,当传递output_attentions=True
或config.output_attentions=True
时返回) —torch.FloatTensor
的元组(每层一个),形状为(batch_size, num_heads, sequence_length, sequence_length)
。attention softmax 之后的 attentions 权重,用于计算 self-attention head 中的加权平均值。
-
image_hidden_states (
torch.FloatTensor
,可选) — 大小为(batch_size, num_images, sequence_length, hidden_size)
的torch.FloatTensor
。 由 vision encoder 生成并在投影最后一个 hidden state 之后,模型的 image_hidden_states。
GotOcr2ForConditionalGeneration
forward 方法,覆盖了 __call__
特殊方法。
虽然 forward pass 的配方需要在该函数中定义,但之后应该调用 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."