Spaces:
Sleeping
Sleeping
Commit
·
60b8094
1
Parent(s):
db9126f
要約機能の実装
Browse files- src/ai_api/config.py +9 -0
- src/ai_api/core/inference.py +23 -1
- tests/core/test_inference.py +29 -4
src/ai_api/config.py
CHANGED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dataclasses import dataclass
|
2 |
+
|
3 |
+
|
4 |
+
@dataclass(frozen=True)
|
5 |
+
class ModelConfig:
|
6 |
+
"""使用するAIモデルに関する情報を一元管理します。"""
|
7 |
+
|
8 |
+
NAME: str = "llm-jp/t5-small-japanese-finetuned-sum"
|
9 |
+
REVISION: str = "main"
|
src/ai_api/core/inference.py
CHANGED
@@ -1,6 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
class Summarizer:
|
2 |
"""
|
3 |
AIモデルを管理し、テキスト要約を実行するクラス。
|
4 |
"""
|
5 |
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import cast
|
2 |
+
|
3 |
+
from transformers import pipeline
|
4 |
+
|
5 |
+
from ai_api.config import ModelConfig
|
6 |
+
|
7 |
+
|
8 |
class Summarizer:
|
9 |
"""
|
10 |
AIモデルを管理し、テキスト要約を実行するクラス。
|
11 |
"""
|
12 |
|
13 |
+
def __init__(self, config: ModelConfig) -> None:
|
14 |
+
self.config = config
|
15 |
+
# __init__で一度だけpipelineを初期化
|
16 |
+
self.summarizer = pipeline(
|
17 |
+
"summarization",
|
18 |
+
model=self.config.NAME,
|
19 |
+
revision=self.config.REVISION,
|
20 |
+
)
|
21 |
+
|
22 |
+
def summarize(self, text: str) -> str:
|
23 |
+
"""
|
24 |
+
与えられたテキストを要約する。
|
25 |
+
"""
|
26 |
+
# 保持しているsummarizerを使って要約
|
27 |
+
result = self.summarizer(text)
|
28 |
+
return cast(str, result[0]["summary_text"])
|
tests/core/test_inference.py
CHANGED
@@ -1,8 +1,33 @@
|
|
|
|
|
|
1 |
|
2 |
|
3 |
-
def
|
4 |
"""
|
5 |
-
Summarizer
|
6 |
"""
|
7 |
-
#
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from ai_api.config import ModelConfig
|
2 |
+
from ai_api.core.inference import Summarizer
|
3 |
|
4 |
|
5 |
+
def test_summarizer_initialization_with_test_model() -> None:
|
6 |
"""
|
7 |
+
テスト用の軽量モデルでSummarizerが初期化できることをテストする。
|
8 |
"""
|
9 |
+
# Arrange: テスト専用の軽量モデルを指定
|
10 |
+
config = ModelConfig(NAME="sshleifer/distilbart-cnn-6-6", REVISION="main")
|
11 |
+
|
12 |
+
# Act: 実際にモデルをロードして初期化
|
13 |
+
summarizer = Summarizer(config=config)
|
14 |
+
|
15 |
+
# Assert
|
16 |
+
assert isinstance(summarizer, Summarizer)
|
17 |
+
|
18 |
+
|
19 |
+
def test_summarize_with_test_model() -> None:
|
20 |
+
"""
|
21 |
+
テスト用の軽量モデルでsummarizeメソッドが動作することをテストする。
|
22 |
+
"""
|
23 |
+
# Arrange: テスト専用の軽量モデルを指定
|
24 |
+
config = ModelConfig(NAME="sshleifer/distilbart-cnn-6-6", REVISION="main")
|
25 |
+
summarizer = Summarizer(config=config)
|
26 |
+
text = "This is a test sentence. It is a very nice sentence to summarize."
|
27 |
+
|
28 |
+
# Act: 実際に要約を実行
|
29 |
+
summary = summarizer.summarize(text)
|
30 |
+
|
31 |
+
# Assert: 要約結果が文字列であり、空でないことを確認
|
32 |
+
assert isinstance(summary, str)
|
33 |
+
assert len(summary) > 0
|