Roberta2024 commited on
Commit
fb133a4
·
verified ·
1 Parent(s): 7f57202

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -0
app.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import pandas as pd
4
+ import jieba
5
+ from keybert import KeyBERT
6
+ from sklearn.feature_extraction.text import CountVectorizer
7
+ import streamlit as st
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.font_manager import FontProperties
10
+
11
+ # 下載字體
12
+ def download_font(url, save_path):
13
+ response = requests.get(url)
14
+ with open(save_path, 'wb') as f:
15
+ f.write(response.content)
16
+
17
+ # 字體URL和保存路徑
18
+ font_url = 'https://drive.google.com/uc?id=1eGAsTN1HBpJAkeVM57_C7ccp7hbgSz3_&export=download'
19
+ font_path = 'TaipeiSansTCBeta-Regular.ttf'
20
+
21
+ # 下載字體
22
+ download_font(font_url, font_path)
23
+
24
+ # 設置字體
25
+ font_prop = FontProperties(fname=font_path)
26
+
27
+ # 抓取Yahoo新聞標題和內容
28
+ def fetch_yahoo_news(url):
29
+ response = requests.get(url)
30
+ web_content = response.content
31
+ soup = BeautifulSoup(web_content, 'html.parser')
32
+ title = soup.find('h1').text
33
+ content = soup.find('article').text
34
+ return title, content
35
+
36
+ # 斷詞函數
37
+ def jieba_tokenizer(text):
38
+ return jieba.lcut(text)
39
+
40
+ # 初始化CountVectorizer並定義KeyBERT模型
41
+ vectorizer = CountVectorizer(tokenizer=jieba_tokenizer)
42
+ kw_model = KeyBERT()
43
+
44
+ # 提取關鍵詞的函數(使用MMR)
45
+ def extract_keywords(doc, diversity=0.7):
46
+ keywords = kw_model.extract_keywords(doc, vectorizer=vectorizer, use_mmr=True, diversity=diversity)
47
+ return keywords
48
+
49
+ # 畫圖函數
50
+ def plot_keywords(keywords, title):
51
+ words = [kw[0] for kw in keywords]
52
+ scores = [kw[1] for kw in keywords]
53
+
54
+ plt.figure(figsize=(10, 6))
55
+ bars = plt.barh(words, scores, color='skyblue', edgecolor='black', linewidth=1.2)
56
+ plt.xlabel('分數', fontproperties=font_prop, fontsize=14)
57
+ plt.title(title, fontproperties=font_prop, fontsize=16)
58
+ plt.gca().invert_yaxis() # 反轉Y軸,使得分數最高的關鍵詞在最上面
59
+ plt.xticks(fontproperties=font_prop, fontsize=12)
60
+ plt.yticks(fontproperties=font_prop, fontsize=12)
61
+ plt.grid(axis='x', linestyle='--', alpha=0.7)
62
+
63
+ # 添加分數標籤
64
+ for bar in bars:
65
+ plt.gca().text(bar.get_width() + 0.01, bar.get_y() + bar.get_height() / 2,
66
+ f'{bar.get_width():.4f}', va='center', ha='left', fontsize=12, fontproperties=font_prop)
67
+
68
+ st.pyplot(plt)
69
+
70
+ # 建立Streamlit網頁應用程式
71
+ st.title("🤙🤙🤙YAHOO新聞關鍵詞提取工具👂👂")
72
+
73
+ # 抓取Yahoo新聞的URL輸入框
74
+ url = st.text_input("請輸入Yahoo新聞的URL:")
75
+
76
+ if st.button("抓取並提取關鍵詞"):
77
+ if url:
78
+ title, content = fetch_yahoo_news(url)
79
+ st.write("新聞標題:", title)
80
+ st.write("新聞內容:", content)
81
+
82
+ # 將內容轉為DataFrame
83
+ data = {'Title': [title], 'Content': [content]}
84
+ df = pd.DataFrame(data)
85
+ st.write("新聞內容的DataFrame:")
86
+ st.write(df)
87
+
88
+ # 提取關鍵詞
89
+ diversity = st.slider("選擇MMR多樣性參數", 0.0, 1.0, 0.7)
90
+ keywords = extract_keywords(content, diversity=diversity)
91
+ st.write("關鍵詞提取結果:")
92
+ for keyword in keywords:
93
+ st.write(f"{keyword[0]}: {keyword[1]:.4f}")
94
+
95
+ plot_keywords(keywords, "關鍵詞提取結果")
96
+
97
+ # 使用另一個模型進行關鍵詞提取
98
+ kw_model_multilingual = KeyBERT(model='distiluse-base-multilingual-cased-v1')
99
+ keywords_multilingual = kw_model_multilingual.extract_keywords(content, vectorizer=vectorizer, use_mmr=True, diversity=diversity)
100
+ st.write("多語言模型關鍵詞提取結果:")
101
+ for keyword in keywords_multilingual:
102
+ st.write(f"{keyword[0]}: {keyword[1]:.4f}")
103
+
104
+ plot_keywords(keywords_multilingual, "多語言模型關鍵詞提取結果")
105
+ else:
106
+ st.write("請輸入有效的Yahoo新聞URL。")