Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import pipeline
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import trafilatura
|
| 4 |
+
|
| 5 |
+
# 載入輕量摘要模型(CPU 友好)
|
| 6 |
+
summarizer = pipeline(
|
| 7 |
+
"summarization",
|
| 8 |
+
model="sshleifer/distilbart-cnn-12-6",
|
| 9 |
+
device=-1 # 強制使用 CPU
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
def summarize_url(url):
|
| 13 |
+
if not url or not url.startswith("http"):
|
| 14 |
+
return "請輸入有效的網址(需包含 http:// 或 https://)"
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
# 抓取網頁
|
| 18 |
+
downloaded = trafilatura.fetch_url(url)
|
| 19 |
+
if downloaded is None:
|
| 20 |
+
return "無法載入該網頁,請確認網址是否正確或網站是否允許訪問。"
|
| 21 |
+
|
| 22 |
+
# 提取乾淨正文
|
| 23 |
+
text = trafilatura.extract(
|
| 24 |
+
downloaded,
|
| 25 |
+
include_comments=False,
|
| 26 |
+
include_tables=False,
|
| 27 |
+
output_format="txt",
|
| 28 |
+
max_length=2000 # 限制長度以加速處理
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
if not text or len(text.strip()) < 100:
|
| 32 |
+
return "無法提取足夠的文字內容(可能不是文章頁面)。"
|
| 33 |
+
|
| 34 |
+
# 摘要(限制輸入長度)
|
| 35 |
+
input_text = text[:2000]
|
| 36 |
+
summary = summarizer(
|
| 37 |
+
input_text,
|
| 38 |
+
max_length=130,
|
| 39 |
+
min_length=40,
|
| 40 |
+
do_sample=False,
|
| 41 |
+
truncation=True
|
| 42 |
+
)
|
| 43 |
+
return summary[0]['summary_text']
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
return f"處理時發生錯誤:{str(e)}"
|
| 47 |
+
|
| 48 |
+
# Gradio 介面
|
| 49 |
+
with gr.Blocks(title="網頁重點整理 Agent") as demo:
|
| 50 |
+
gr.Markdown("# 🌐 網頁重點整理 Agent\n輸入一篇新聞、部落格或文章的網址,自動幫你生成重點摘要(CPU 版本)")
|
| 51 |
+
url_input = gr.Textbox(label="請輸入網址", placeholder="https://example.com/article")
|
| 52 |
+
output = gr.Textbox(label="重點摘要", lines=6)
|
| 53 |
+
btn = gr.Button("開始整理")
|
| 54 |
+
btn.click(fn=summarize_url, inputs=url_input, outputs=output)
|
| 55 |
+
gr.Markdown("💡 提示:僅支援文字為主的網頁(如新聞、技術文章),不支援登入頁、影片頁或動態內容過多的網站。")
|
| 56 |
+
|
| 57 |
+
demo.launch()
|