File size: 1,190 Bytes
50a43ab
 
3f09f55
 
 
50a43ab
 
3f09f55
 
 
50a43ab
 
3f09f55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from transformers import pipeline

# 指定使用 Hugging Face 上支援中文的摘要模型
# 例如:"IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese" 是免費的中文摘要模型
# device=0(如果有 GPU)可加速;沒有 GPU 可以移除 device 參數
summarizer = pipeline(
    "summarization",
    model="IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese",
    tokenizer="IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese",
    device=0   # 若在 CPU 請刪除這一行
)

def 摘要(文本, 最大長度=128, 最小長度=30):
    """

    用於生成中文長文摘要

    :param 文本: 輸入的待摘要中文文本

    :param 最大長度: 摘要最大字數

    :param 最小長度: 摘要最小字數

    :return: 返回摘要字串

    """
    # transformers 需要將文本丟進 summarizer
    results = summarizer(文本, max_length=最大長度, min_length=最小長度, do_sample=False)
    return results[0]['summary_text']

# 範例測試(可刪)
if __name__ == "__main__":
    測試文 = "人工智慧(Artificial Intelligence,簡稱 AI)是計算機科學的一個分支,..."
    print("摘要結果:", 摘要(測試文))