3a05chatgpt commited on
Commit
3f09f55
·
verified ·
1 Parent(s): 50a43ab

Upload textsumm.py

Browse files
Files changed (1) hide show
  1. textsumm.py +22 -16
textsumm.py CHANGED
@@ -1,22 +1,28 @@
1
  from transformers import pipeline
2
 
3
- # 使用 Hugging Face 支援中文的 Pegasus 模型
 
 
4
  summarizer = pipeline(
5
  "summarization",
6
- model="IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese"
 
 
7
  )
8
 
9
- def 摘要(text, max_length=128, min_length=20):
10
- if not text.strip():
11
- return "⚠️ 請輸入要摘要的內容"
12
- # 依據模型最大長度做裁剪
13
- if len(text) > 1500:
14
- text = text[:1500]
15
- result = summarizer(text, max_length=max_length, min_length=min_length, do_sample=False)
16
- # 處理不同模型回傳格式
17
- if isinstance(result, list) and "summary_text" in result[0]:
18
- return result[0]["summary_text"]
19
- elif isinstance(result, str):
20
- return result
21
- else:
22
- return str(result)
 
 
 
1
  from transformers import pipeline
2
 
3
+ # 指定使用 Hugging Face 上支援中文的摘要模型
4
+ # 例如:"IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese" 是免費的中文摘要模型
5
+ # device=0(如果有 GPU)可加速;沒有 GPU 可以移除 device 參數
6
  summarizer = pipeline(
7
  "summarization",
8
+ model="IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese",
9
+ tokenizer="IDEA-CCNL/Randeng-Pegasus-523M-Summary-Chinese",
10
+ device=0 # 若在 CPU 請刪除這一行
11
  )
12
 
13
+ def 摘要(文本, 最大長度=128, 最小長度=30):
14
+ """
15
+ 用於生成中文長文摘要
16
+ :param 文本: 輸入的待摘要中文文本
17
+ :param 最大長度: 摘要最大字數
18
+ :param 最小長度: 摘要最小字數
19
+ :return: 返回摘要字串
20
+ """
21
+ # transformers 需要將文本丟進 summarizer
22
+ results = summarizer(文本, max_length=最大長度, min_length=最小長度, do_sample=False)
23
+ return results[0]['summary_text']
24
+
25
+ # 範例測試(可刪)
26
+ if __name__ == "__main__":
27
+ 測試文 = "人工智慧(Artificial Intelligence,簡稱 AI)是計算機科學的一個分支,..."
28
+ print("摘要結果:", 摘要(測試文))