# SLANeXt

## 概要

**SLANeXt_wired** と **SLANeXt_wireless** は、文書や自然なシーンにおける表構造の正確な認識に焦点を当てた、表構造認識専用の軽量モデルシリーズの一部です。SLANeXt シリーズモデルの詳細については、[公式ドキュメント](https://www.paddleocr.ai/latest/en/version3.x/module_usage/table_structure_recognition.html)を参照してください。

## モデルアーキテクチャ

SLANeXt シリーズは、Baidu PaddlePaddle Vision チームが独自に開発した次世代の表構造認識モデルです。SLANeXt は表構造認識に特化しており、有線表と無線表それぞれに専用の重みを学習しています。あらゆる種類の表に対する認識能力が大幅に向上し、特に有線表において顕著な改善が見られます。

## 使用方法

### 単一入力推論

以下の例では、[AutoModel](/docs/transformers/main/ja/model_doc/auto#transformers.AutoModel)を使用してPP-OCRV5_Mobile_Detでテキストを検出する方法を示しています。

```python
import requests
from PIL import Image

from transformers import AutoImageProcessor, AutoModelForTableRecognition

model_path="PaddlePaddle/SLANeXt_wired_safetensors"
model = AutoModelForTableRecognition.from_pretrained(model_path, device_map="auto")
image_processor = AutoImageProcessor.from_pretrained(model_path)

image = Image.open(requests.get("https://huggingface.co/datasets/hf-internal-testing/transformers-synthetic-assets/resolve/main/images/paddle_table_recognition.jpg", stream=True).raw)
inputs = image_processor(images=image, return_tensors="pt").to(model.device)
outputs = model(**inputs)

results = image_processor.post_process_table_recognition(outputs)

print(result['structure'])
print(result['structure_score'])
```

## SLANeXtConfig[[transformers.SLANeXtConfig]]

#### transformers.SLANeXtConfig[[transformers.SLANeXtConfig]]

```python
transformers.SLANeXtConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, vision_config: dict | transformers.models.slanext.configuration_slanext.SLANeXtVisionConfig | None = None, post_conv_in_channels: int = 256, post_conv_out_channels: int = 512, out_channels: int = 50, hidden_size: int = 512, max_text_length: int = 500)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/configuration_slanext.py#L70)

**パラメータ:**

vision_config (`dict`または[SLANeXtVisionConfig](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtVisionConfig)、*optional*) : ビジョンエンコーダーの設定。`None`の場合、デフォルトの[SLANeXtVisionConfig](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtVisionConfig)が使用されます。

post_conv_in_channels (`int`、*optional*、デフォルトは 256) : エンコーダー後の畳み込み層の入力チャネル数。

post_conv_out_channels (`int`, *optional*, デフォルトは 512) : エンコーダー後の畳み込み層の出力チャネル数。

out_channels (`int`、*optional*、デフォルトは 50) : テーブル構造トークン予測ヘッドの語彙サイズ、つまりモデルが予測できる異なる構造トークンの数です。

hidden_size (`int`、*optional*、デフォルトは 512) : attention GRU セルおよび構造/位置予測ヘッドにおける隠れ状態の次元数。

max_text_length (`int`, *任意*, デフォルト値は 500) : 構造および位置デコーダーの自己回帰デコーディングステップ（トークン）の最大数。

これはSlanextModelの設定を保存するための設定クラスです。指定された引数に基づいてSlanextモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[PaddlePaddle/SLANeXt_wired_safetensors](https://huggingface.co/PaddlePaddle/SLANeXt_wired_safetensors)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

## SLANeXtVisionConfig[[transformers.SLANeXtVisionConfig]]

#### transformers.SLANeXtVisionConfig[[transformers.SLANeXtVisionConfig]]

```python
transformers.SLANeXtVisionConfig(transformers_version: str | None = None, architectures: list[str] | None = None, output_hidden_states: bool | None = False, return_dict: bool | None = True, dtype: str | torch.dtype | None = None, chunk_size_feed_forward: int = 0, is_encoder_decoder: bool = False, id2label: dict[int, str] | dict[str, str] | None = None, label2id: dict[str, int] | dict[str, str] | None = None, problem_type: Literal['regression', 'single_label_classification', 'multi_label_classification'] | None = None, hidden_size: int = 768, output_channels: int = 256, num_hidden_layers: int = 12, num_attention_heads: int = 12, num_channels: int = 3, image_size: int = 512, patch_size: int | list[int] | tuple[int, int] = 16, hidden_act: str = 'gelu', layer_norm_eps: float = 1e-06, attention_dropout: float | int = 0.0, 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] | tuple[int, ...] = (2, 5, 8, 11), mlp_dim: int = 3072)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/configuration_slanext.py#L30)

**パラメータ:**

hidden_size (`int`、*任意*、デフォルトは`768`) : 隠れ表現の次元数。

output_channels (`int`、*任意*、デフォルトは 256) : Patch Encoder の出力チャネルの次元数。

num_hidden_layers (`int`, *任意*, デフォルトは `12`) : Transformer デコーダーの隠れ層の数。

num_attention_heads (`int`、*任意*、デフォルトは `12`) : Transformer デコーダーの各アテンション層におけるアテンションヘッドの数。

num_channels (`int`、*任意*、デフォルトは`3`) : 入力チャネル数。

image_size (`int`, *optional*, デフォルトは `512`) : 各画像のサイズ（解像度）。

patch_size (`Union[int, list[int], tuple[int, int]]`、*任意*、デフォルトは`16`) : 各パッチのサイズ（解像度）。

hidden_act (`str`、*任意*、デフォルトは`gelu`) : デコーダーで使用する非線形活性化関数（関数または文字列）。例えば、`"gelu"`、`"relu"`、`"silu"`など。

layer_norm_eps (`float`、*任意*、デフォルトは`1e-06`) : Layer Normalization 層で使用する epsilon です。

attention_dropout (`Union[float, int]`、*任意*、デフォルトは`0.0`) : 注意確率のドロップアウト率。

initializer_range (`float`、*任意*、デフォルトは `1e-10`) : 全重み行列の初期化に使用される truncated_normal_initializer の標準偏差です。

qkv_bias (`bool`, *任意*, デフォルトは `True`) : クエリ、キー、バリューにバイアスを追加するかどうか。

use_abs_pos (`bool`、*任意*、デフォルトは`True`) : 絶対位置埋め込みを使用するかどうか。

use_rel_pos (`bool`、*任意*、デフォルトは`True`) : 相対位置埋め込みを使用するかどうか。

window_size (`int`, *optional*, デフォルトは 14) : 相対位置のウィンドウサイズ。

global_attn_indexes (`list[int]`、*任意*、デフォルトは`[2, 5, 8, 11]`) : グローバルアテンションレイヤーのインデックスです。

mlp_dim (`int`、*optional*、デフォルトは 3072) : Transformer エンコーダーにおける MLP レイヤーの次元数。

これはSlanextModelの設定を保存するための設定クラスです。指定された引数に基づいてSlanextモデルをインスタンス化し、モデルのアーキテクチャを定義するために使用されます。デフォルト値で設定をインスタンス化すると、[PaddlePaddle/SLANeXt_wired_safetensors](https://huggingface.co/PaddlePaddle/SLANeXt_wired_safetensors)と類似した設定が得られます。

設定オブジェクトは [PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) を継承し、モデルの出力を制御するために使用できます。詳細については、[PreTrainedConfig](/docs/transformers/main/ja/main_classes/configuration#transformers.PreTrainedConfig) のドキュメントを参照してください。

## SLANeXtForTableRecognition[[transformers.SLANeXtForTableRecognition]]

#### transformers.SLANeXtForTableRecognition[[transformers.SLANeXtForTableRecognition]]

```python
transformers.SLANeXtForTableRecognition(config: SLANeXtConfig)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/modeling_slanext.py#L618)

**パラメータ:**

config ([SLANeXtConfig](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtConfig)) : モデルのすべてのパラメータを含むモデル設定クラスです。設定ファイルで初期化しても、モデルに関連する重みは読み込まれず、設定のみが読み込まれます。モデルの重みをロードするには、[from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) メソッドを確認してください。

のタスク用のSLANeXt Table Recognitionモデル。SLANeXtPreTrainedModelをラップし、TransformersのAPIと互換性のある出力を返します。

このモデルは [PreTrainedModel](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel) を継承しています。ライブラリがすべてのモデルに対して実装している汎用的なメソッド（ダウンロードや保存、入力埋め込みのリサイズ、ヘッドのプルーニングなど）については、スーパークラスのドキュメントを参照してください。

このモデルは、PyTorchの[torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module)のサブクラスでもあります。通常のPyTorch Moduleとして使用し、一般的な使用方法や動作に関する詳細については、PyTorchのドキュメントを参照してください。

#### forward[[transformers.SLANeXtForTableRecognition.forward]]

```python
forward(pixel_values: FloatTensor, **kwargs: *<class 'transformers.utils.generic.TransformersKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/modeling_slanext.py#L625)

**パラメータ:**

pixel_values (`torch.FloatTensor`、shape `(batch_size, num_channels, image_size, image_size)`) : 入力画像に対応するテンソルです。ピクセル値は[SLANeXtImageProcessor](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtImageProcessor)を使用して取得できます。詳細は[SLANeXtImageProcessor.__call__()](/docs/transformers/main/ja/model_doc/molmo2#transformers.Molmo2ImageProcessor.__call__)を参照してください（`processor_class`は画像の処理に[SLANeXtImageProcessor](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtImageProcessor)を使用します）。

**戻り値:** `SLANeXtForTableRecognitionOutput` または `tuple(torch.FloatTensor)`

`SLANeXtForTableRecognitionOutput`、または`torch.FloatTensor`のタプル（`return_dict=False`が渡された場合、または`config.return_dict=False`の場合）。設定（[SLANeXtConfig](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtConfig)）や入力に応じて、さまざまな要素で構成されます。

[SLANeXtForTableRecognition](/docs/transformers/main/ja/model_doc/slanext#transformers.SLANeXtForTableRecognition)のforwardメソッドは、`__call__`特殊メソッドをオーバーライドします。

この関数内でフォワードパスの手順を定義する必要がありますが、その後、この関数ではなく`Module`インスタンスを呼び出すべきです。前者は前処理と後処理の実行を適切に処理するのに対し、後者はそれらを無視してしまいます。

- **last_hidden_state** (`torch.FloatTensor`、shape `(batch_size, sequence_length, hidden_size)`) -- モデルの最終層の出力における隠れ状態のシーケンス。
- **hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合または `config.output_hidden_states=True` の場合に返されます) -- `torch.FloatTensor` のタプル（埋め込み層を持つモデルの場合、埋め込みの出力用が 1 つ、各層の出力用が 1 つずつ）で、形状は `(batch_size, sequence_length, hidden_size)` です。

  各層の出力におけるモデルのHidden-states、および任意の初期埋め込み出力。
- **attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合または `config.output_attentions=True` の場合に返されます) -- `torch.FloatTensor` のタプル（各レイヤーごとに1つ）で、形状は `(batch_size, num_heads, sequence_length, sequence_length)` です。

  アテンションのsoftmax後のアテンション重み。自己アテンションヘッド内で加重平均を計算するために使用されます。
- **head_hidden_states** (`tuple(torch.FloatTensor)`、*optional*、`output_hidden_states=True` が渡された場合、または `config.output_hidden_states=True` の場合に返されます) -- 各予測ステップにおける SLANeXtSLAHead の隠れ状態。早期終了に依存して、最大 `self.config.max_text_length` 個の状態まで変化します。
- **head_attentions** (`tuple(torch.FloatTensor)`、*optional*、`output_attentions=True` が渡された場合、または `config.output_attentions=True` の場合に返されます) -- 各予測ステップにおける SLANeXtSLAHead のアテンション。早期終了に依存して、最大 `self.config.max_text_length` 個のアテンションまで変動します。

## SLANeXtBackbone[[transformers.SLANeXtBackbone]]

#### transformers.SLANeXtBackbone[[transformers.SLANeXtBackbone]]

```python
transformers.SLANeXtBackbone(config: dict | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/modeling_slanext.py#L522)

## SLANeXtSLAHead[[transformers.SLANeXtSLAHead]]

#### transformers.SLANeXtSLAHead[[transformers.SLANeXtSLAHead]]

```python
transformers.SLANeXtSLAHead(config: dict | None = None, **kwargs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/modeling_slanext.py#L546)

## SLANeXtImageProcessor[[transformers.SLANeXtImageProcessor]]

#### transformers.SLANeXtImageProcessor[[transformers.SLANeXtImageProcessor]]

```python
transformers.SLANeXtImageProcessor(**kwargs: *<class 'transformers.processing_utils.ImagesKwargs'>)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/image_processing_slanext.py#L38)

**パラメータ:**

do_convert_rgb (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を RGB に変換するかどうか。

do_resize (`bool`, *kwargs*, *任意*, デフォルトは `True`) : 画像をリサイズするかどうか。

size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*、デフォルト値は`{'height' : 512, 'width': 512}`): モデルへの最大入力次元を記述します。

default_to_square (`bool`, *kwargs*, *任意*、デフォルトは `True`) : size が整数の場合、リサイズ時に正方形の画像をデフォルトとするかどうか。

crop_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*) : `center_crop` を適用した後の出力画像のサイズ。

resample (`Annotated[Union[int, PILImageResampling, NoneType], None]`, *kwargs*、デフォルト値は`2`) : 画像のリサイズ時に使用するリサンプリングフィルタです。これは列挙型`PILImageResampling`のいずれかになります。`do_resize`が`True`に設定されている場合のみ、効果が現れます。

do_rescale (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像をリスケールするかどうか。

rescale_factor (`float`, *kwargs*, *optional*, デフォルトは `0.00392156862745098`) : `do_rescale` が `True` に設定されている場合、画像をリスケールするための係数。

do_normalize (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像を正規化するかどうかを指定します。

image_mean (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.485, 0.456, 0.406]`) : 正規化に使用する画像の平均値です。`do_normalize` が `True` に設定されている場合のみ有効です。

image_std (`Union[float, list[float], tuple[float, ...]]`, *kwargs*, *optional*, デフォルトは `[0.229, 0.224, 0.225]`) : 正規化に使用する画像の標準偏差。`do_normalize` が `True` に設定されている場合のみ有効です。

do_pad (`bool`, *kwargs*, *optional*, デフォルトは `True`) : 画像にパディングを適用するかどうか。パディングは、バッチ内の最大サイズに合わせるか、画像ごとに固定の正方形サイズに合わせるかのいずれかで行われます。正確なパディング戦略はモデルによって異なります。

pad_size (`Annotated[int | list[int] | tuple[int, ...] | dict[str, int] | None, None]`, *kwargs*, defaults to `{'height' : 512, 'width': 512}`): The size in `{"height": int, "width" int}` to pad the images to. Must be larger than any image size provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest height and width in the batch. Applied only when `do_pad=True.`

do_center_crop (`bool`, *kwargs*, *optional*) : 画像を中央クロップするかどうか。

data_format (`Union[str, ~image_utils.ChannelDimension]`、*kwargs*、*optional*) : 対応するのは `ChannelDimension.FIRST` のみです。slow processors との互換性のために追加されました。

input_data_format (`Union[str, ~image_utils.ChannelDimension]`, *kwargs*, *任意*) : 入力画像のチャネル次元の形式です。設定されていない場合、入力画像からチャネル次元の形式が推論されます。以下のいずれかになります: - `"channels_first"` または `ChannelDimension.FIRST`: (num_channels, height, width) 形式の画像。 - `"channels_last"` または `ChannelDimension.LAST`: (height, width, num_channels) 形式の画像。 - `"none"` または `ChannelDimension.NONE`: (height, width) 形式の画像。

device (`Annotated[Union[str, torch.device, NoneType], None]`, *kwargs*) : 動画を処理するデバイスです。未設定の場合、入力動画からデバイスが推論されます。

return_tensors (`Annotated[str | ~utils.generic.TensorType | None, None]`, *kwargs*) : `'pt'`に設定されている場合はスタックされたテンソルを返し、それ以外の場合はテンソルのリストを返します。

disable_grouping (`bool`, *kwargs*, *optional*) : 画像をサイズごとにグループ化してバッチ処理するのではなく、個別に処理するためにグループ化を無効にするかどうかを指定します。None の場合、画像が CPU にある場合は True、それ以外の場合は False に設定されます。この選択は、https://github.com/huggingface/transformers/pull/38157 に詳しく記載されている実証的な観察に基づいています。

image_seq_length (`int`, *kwargs*, *任意*) : 入力内の各画像に使用される画像トークンの数です。後方互換性のために追加されましたが、将来のモデルではプロセッサの属性として設定されるべきです。

SLANeXtImageProcessor 画像プロセッサを構築します。

#### init_decoder[[transformers.SLANeXtImageProcessor.init_decoder]]

```python
init_decoder()
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/image_processing_slanext.py#L170)

構造認識用のデコーダー語彙を初期化します。

HTMLテーブル構造トークン（例: `<thead>`、`<tr>`、`<td>`、colspan/rowspan属性）を整数インデックスにマッピングする文字列辞書を構築します。辞書には、特殊トークンである`"sos"`（シーケンス開始）と`"eos"`（シーケンス終了）が含まれます。適用可能な場合、単独の`<td>`トークンの代わりに、マージされた`<td></td>`トークンが使用されます。

#### post_process_table_recognition[[transformers.SLANeXtImageProcessor.post_process_table_recognition]]

```python
post_process_table_recognition(outputs)
```

[ソース](https://github.com/huggingface/transformers/blob/main/src/transformers/models/slanext/image_processing_slanext.py#L206)

**パラメータ:**

outputs (`SLANeXtForTableRecognitionOutput`) : SLANeXtモデルの生出力です。`last_hidden_state`フィールドには、各デコーディングステップにおける構造語彙に対する予測確率分布が含まれており、その形状は`(batch_size, max_text_length, num_classes)`です。

**戻り値:** `dict`

以下の内容を含む辞書:
- **structure** (`list[str]`): `<html>`、`<body>`、`<table>` タグでラップされた、トークンのリストとしての予測された HTML テーブル構造。
- **structure_score** (`float`): 予測されたすべてのトークンにわたる平均信頼度スコア。

生のモデル出力を後処理し、予測されたテーブル構造をHTMLトークン列にデコードします。

モデルが構造語彙に対して予測した確率分布を、テーブル構造を表すHTMLトークンのシーケンスに変換します。デコードされたトークンは`<html>`、`<body>`、`<table>`タグでラップされ、完全なHTMLテーブル構造が形成されます。

