モデル概要
モデル特徴
モデル能力
使用事例
🚀 モデルの概要
このモデルは、47 の言語における句読点の復元、大文字化(True - case)、および文境界(句点)の検出を行うために微調整された xlm - roberta
モデルです。
🚀 クイックスタート
モデルの使い方
もしモデルを試してみたいだけであれば、このページのウィジェットで十分です。モデルをオフラインで使用する場合は、以下のコードスニペットで、ラッパーを使用する方法と手動で使用する方法の両方を示します。
✨ 主な機能
- 47 の言語で句読点の復元、大文字化、文境界の検出を行うことができます。
- ラッパーを使用することで簡単にモデルを利用できます。
- 手動で ONNX と SentencePiece モデルを使用することも可能です。
📦 インストール
punctuators
パッケージを使用する場合
このモデルを使用する最も簡単な方法は、[punctuators](https://github.com/1 - 800 - BAD - CODE/punctuators) をインストールすることです。
$ pip install punctuators
💻 使用例
基本的な使用法
punctuators
パッケージを使用する場合
from typing import List
from punctuators.models import PunctCapSegModelONNX
m: PunctCapSegModelONNX = PunctCapSegModelONNX.from_pretrained(
"1-800-BAD-CODE/xlm-roberta_punctuation_fullstop_truecase"
)
input_texts: List[str] = [
"hola mundo cómo estás estamos bajo el sol y hace mucho calor santa coloma abre los huertos urbanos a las escuelas de la ciudad",
"hello friend how's it going it's snowing outside right now in connecticut a large storm is moving in",
"未來疫苗將有望覆蓋3歲以上全年齡段美國與北約軍隊已全部撤離還有鐵路公路在內的各項基建的來源都將枯竭",
"በባለፈው ሳምንት ኢትዮጵያ ከሶማሊያ 3 ሺህ ወታደሮቿንም እንዳስወጣች የሶማሊያው ዳልሳን ሬድዮ ዘግቦ ነበር ጸጥታ ሃይሉና ህዝቡ ተቀናጅቶ በመስራቱ በመዲናዋ ላይ የታቀደው የጥፋት ሴራ ከሽፏል",
"こんにちは友人" "調子はどう" "今日は雨の日でしたね" "乾いた状態を保つために一日中室内で過ごしました",
"hallo freund wie geht's es war heute ein regnerischer tag nicht wahr ich verbrachte den tag drinnen um trocken zu bleiben",
"हैलो दोस्त ये कैसा चल रहा है आज बारिश का दिन था न मैंने सूखा रहने के लिए दिन घर के अंदर बिताया",
"كيف تجري الامور كان يومًا ممطرًا اليوم أليس كذلك قضيت اليوم في الداخل لأظل جافًا",
]
results: List[List[str]] = m.infer(
texts=input_texts, apply_sbd=True,
)
for input_text, output_texts in zip(input_texts, results):
print(f"Input: {input_text}")
print(f"Outputs:")
for text in output_texts:
print(f"\t{text}")
print()
手動で使用する場合
from typing import List
import numpy as np
import onnxruntime as ort
from huggingface_hub import hf_hub_download
from omegaconf import OmegaConf
from sentencepiece import SentencePieceProcessor
# Download the models from HF hub. Note: to clean up, you can find these files in your HF cache directory
spe_path = hf_hub_download(repo_id="1-800-BAD-CODE/xlm-roberta_punctuation_fullstop_truecase", filename="sp.model")
onnx_path = hf_hub_download(repo_id="1-800-BAD-CODE/xlm-roberta_punctuation_fullstop_truecase", filename="model.onnx")
config_path = hf_hub_download(
repo_id="1-800-BAD-CODE/xlm-roberta_punctuation_fullstop_truecase", filename="config.yaml"
)
# Load the SP model
tokenizer: SentencePieceProcessor = SentencePieceProcessor(spe_path) # noqa
# Load the ONNX graph
ort_session: ort.InferenceSession = ort.InferenceSession(onnx_path)
# Load the model config with labels, etc.
config = OmegaConf.load(config_path)
# Potential classification labels before each subtoken
pre_labels: List[str] = config.pre_labels
# Potential classification labels after each subtoken
post_labels: List[str] = config.post_labels
# Special class that means "predict nothing"
null_token = config.get("null_token", "<NULL>")
# Special class that means "all chars in this subtoken end with a period", e.g., "am" -> "a.m."
acronym_token = config.get("acronym_token", "<ACRONYM>")
# Not used in this example, but if your sequence exceed this value, you need to fold it over multiple inputs
max_len = config.max_length
# For reference only, graph has no language-specific behavior
languages: List[str] = config.languages
# Encode some input text, adding BOS + EOS
input_text = "hola mundo cómo estás estamos bajo el sol y hace mucho calor santa coloma abre los huertos urbanos a las escuelas de la ciudad"
input_ids = [tokenizer.bos_id()] + tokenizer.EncodeAsIds(input_text) + [tokenizer.eos_id()]
# Create a numpy array with shape [B, T], as the graph expects as input.
# Note that we do not pass lengths to the graph; if you are using a batch, padding should be tokenizer.pad_id() and the
# graph's attention mechanisms will ignore pad_id() without requiring explicit sequence lengths.
input_ids_arr: np.array = np.array([input_ids])
# Run the graph, get outputs for all analytics
pre_preds, post_preds, cap_preds, sbd_preds = ort_session.run(None, {"input_ids": input_ids_arr})
# Squeeze off the batch dimensions and convert to lists
pre_preds = pre_preds[0].tolist()
post_preds = post_preds[0].tolist()
cap_preds = cap_preds[0].tolist()
sbd_preds = sbd_preds[0].tolist()
# Segmented sentences
output_texts: List[str] = []
# Current sentence, which is built until we hit a sentence boundary prediction
current_chars: List[str] = []
# Iterate over the outputs, ignoring the first (BOS) and final (EOS) predictions and tokens
for token_idx in range(1, len(input_ids) - 1):
token = tokenizer.IdToPiece(input_ids[token_idx])
# Simple SP decoding
if token.startswith("▁") and current_chars:
current_chars.append(" ")
# Token-level predictions
pre_label = pre_labels[pre_preds[token_idx]]
post_label = post_labels[post_preds[token_idx]]
# If we predict "pre-punct", insert it before this token
if pre_label != null_token:
current_chars.append(pre_label)
# Iterate over each char. Skip SP's space token,
char_start = 1 if token.startswith("▁") else 0
for token_char_idx, char in enumerate(token[char_start:], start=char_start):
# If this char should be capitalized, apply upper case
if cap_preds[token_idx][token_char_idx]:
char = char.upper()
# Append char
current_chars.append(char)
# if this is an acronym, add a period after every char (p.m., a.m., etc.)
if post_label == acronym_token:
current_chars.append(".")
# Maybe this subtoken ends with punctuation
if post_label != null_token and post_label != acronym_token:
current_chars.append(post_label)
# If this token is a sentence boundary, finalize the current sentence and reset
if sbd_preds[token_idx]:
output_texts.append("".join(current_chars))
current_chars.clear()
# Maybe push final sentence, if the final token was not classified as a sentence boundary
if current_chars:
output_texts.append("".join(current_chars))
# Pretty print
print(f"Input: {input_text}")
print("Outputs:")
for text in output_texts:
print(f"\t{text}")
📚 ドキュメント
モデルアーキテクチャ
このモデルは、以下のグラフを実装しており、言語固有の動作なしに、すべての言語で句読点、大文字化、および句点の予測を行うことができます。
グラフの説明を見るにはクリック
まず、テキストをトークナイズし、XLM - Roberta でエンコードします。これは、このグラフの事前学習部分です。次に、各サブトークンの前後の句読点を予測します。各トークンの前の予測は、スペイン語の逆疑問符を可能にします。各トークンの後の予測は、連続スクリプト言語や頭字語内の句読点を含む、他のすべての句読点を可能にします。
予測された句読点トークンを表すために埋め込みを使用し、文章境界ヘッドにテキストに挿入される句読点を通知します。これにより、特定の句読点トークン(句点、疑問符など)が文章境界と強く相関しているため、適切な句点の予測が可能になります。
次に、句点の予測を 1 つ右にシフトして、各新しい文章の始まりを大文字化ヘッドに通知します。大文字化は文章境界と強く相関しているため、これは重要です。
大文字化については、各サブトークンに対して N
個の予測を行います。ここで、N
はサブトークン内の文字数です。実際には、N
は最大サブトークン長であり、余分な予測は無視されます。基本的に、大文字化はマルチラベル問題としてモデル化されています。これにより、「NATO」、「MacDonald」、「mRNA」などの任意の文字を大文字にすることができます。
これらのすべての予測を入力テキストに適用することで、任意の言語で句読点を付け、大文字化し、文章を分割することができます。
トークナイザー
XLM - Roberta トークナイザーの修正方法を見るにはクリック
FairSeq で使用され、HuggingFace によって奇妙に移植(修正されていない)されたハッキーなラッパーの代わりに、`xlm - roberta` の SentencePiece モデルを調整して、テキストを正しくエンコードするようにしました。HF のコメントによると、 ```python # Original fairseq vocab and spm vocab must be "aligned": # Vocab | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ---- # fairseq | 'm = ModelProto() m.ParseFromString(open("/path/to/xlmroberta/sentencepiece.bpe.model", "rb").read())
pieces = list(m.pieces)
pieces = (
[
ModelProto.SentencePiece(piece="", type=ModelProto.SentencePiece.Type.CONTROL),
ModelProto.SentencePiece(piece="", type=ModelProto.SentencePiece.Type.CONTROL),
ModelProto.SentencePiece(piece="
with open("/path/to/new/sp.model", "wb") as f: f.write(m.SerializeToString())
これで、ラッパーなしで SP モデルを使用することができます。
</details>
### トークンの句読点予測
#### サブトークン後の句読点トークン
このモデルは、各サブトークンの後の以下の句読点トークンを予測します。
| トークン | 説明 | 関連言語 |
| ---: | :---------- | :----------- |
| \<NULL\> | 句読点なし | すべて |
| \<ACRONYM\> | このサブワード内のすべての文字の後に句点が付く | 主に英語、一部のヨーロッパ言語 |
| . | ラテン語の句点 | 多くの言語 |
| , | ラテン語のコンマ | 多くの言語 |
| ? | ラテン語の疑問符 | 多くの言語 |
| ? | 全角疑問符 | 中国語、日本語 |
| , | 全角コンマ | 中国語、日本語 |
| 。 | 全角句点 | 中国語、日本語 |
| 、 | 漢字コンマ | 中国語、日本語 |
| ・ | 中点 | 日本語 |
| । | ダンダ | ヒンディー語、ベンガル語、オリヤー語 |
| ؟ | アラビア語の疑問符 | アラビア語 |
| ; | ギリシャ語の疑問符 | ギリシャ語 |
| ። | エチオピア語の句点 | アムハラ語 |
| ፣ | エチオピア語のコンマ | アムハラ語 |
| ፧ | エチオピア語の疑問符 | アムハラ語 |
#### サブワード前の句読点トークン
このモデルは、各サブワードの前の以下の句読点トークンを予測します。
| トークン | 説明 | 関連言語 |
| ---: | :---------- | :----------- |
| (元文書でこの表の続きがありませんでしたが、そのままの形式で残しておきます) | | |
## 📄 ライセンス
このモデルは Apache - 2.0 ライセンスの下で提供されています。








