文書分割とは
文書分割は自然言語処理(NLP)の基本的なタスクの一つであり、連続したテキストを意味のあるセグメント(文、段落、構造要素など)に分割することを目的としています。この処理により、情報抽出、機械翻訳、感情分析など、さまざまなNLP応用処理の精度が向上します。
BERTを用いた文書分割モデル
本記事では、BERTベースの文書分割モデル(nlp_bert_document-segmentation_chinese-base)を取り上げます。このモデルはwiki-zhの公開コーパスで学習されており、未分割の長文テキストを段落単位に分割するのに適しています。
モデルのデプロイ手順
3.1 モデルのダウンロード
git clone https://www.modelscope.cn/iic/nlp_bert_document-segmentation_chinese-base.git
3.2 必要なライブラリのインストール
# requirements.txt
fastapi>=0.110.0
uvicorn>=0.29.0
pydantic>=2.7.0
tiktoken>=0.6.0
sse-starlette>=2.0.0
transformers>=4.37.0
torch>=2.1.0
sentencepiece>=0.2.0
sentence-transformers>=2.4.0
accelerate
modelscope
依存パッケージのインストール:
pip install -r requirements.txt
3.3 モデルのデプロイ
以下は、FastAPIを使用してモデルをAPIとして提供するためのコード例です:
# ファイル名:document_segmentation_server.py
import argparse
import os
import uuid
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from modelscope.outputs import OutputKeys
import uvicorn
# モデル名とパスの設定
MODEL_NAME = ""
MODEL_PATH = ""
# APIのインスタンス化
app = FastAPI()
# リクエストモデル
class DocumentSegmentationRequest(BaseModel):
model: str
content: str
# 文書分割処理
@app.post("/api/v1/segmentation")
async def document_segmentation(request: DocumentSegmentationRequest):
if not request.content:
return JSONResponse({"error": "コンテンツが空です"}, status_code=400)
request_id = str(uuid.uuid4())
result = pipeline(documents=request.content)
segmented_text = result[OutputKeys.TEXT].splitlines()
filtered_text = [line.strip() for line in segmented_text if line.strip()]
return JSONResponse({
"request_id": request_id,
"result": {
"segments": [
{"text": text, "order": idx} for idx, text in enumerate(filtered_text)
]
}
})
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="文書分割モデルの起動スクリプト")
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--port", type=int, default=8880)
parser.add_argument("--model_path", type=str, required=True)
parser.add_argument("--model_name", type=str, default="")
args = parser.parse_args()
MODEL_PATH = args.model_path
MODEL_NAME = args.model_name or os.path.basename(MODEL_PATH)
# モデルのロード
segmentation_pipeline = pipeline(
task=Tasks.document_segmentation,
model=MODEL_PATH
)
# サーバー起動
uvicorn.run(app, host=args.host, port=args.port)
3.4 サービスの起動
python document_segmentation_server.py --model_path=/path/to/model_directory
モデルのテスト
以下は、curlを使用してAPIをテストする際の例です:
curl -X POST -H "Content-Type: application/json" 'http://localhost:8880/api/v1/segmentation' \
-d '{
"model": "nlp_bert_document-segmentation_chinese-base",
"content": "ここに分割したい長文のテキストを入力します。"
}'