EduTechTeam commited on
Commit
1963ca3
·
verified ·
1 Parent(s): b08b756

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -0
app.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from wordcloud import WordCloud
3
+ import matplotlib.pyplot as plt
4
+ import openai
5
+ import matplotlib as mpl
6
+ import matplotlib.font_manager as fm
7
+ import jieba
8
+ import jieba.analyse
9
+
10
+ # 載入停用詞
11
+ def load_stopwords(file_path):
12
+ stopwords = set()
13
+ with open(file_path, 'r', encoding='utf-8') as f:
14
+ for line in f:
15
+ stopwords.add(line.strip())
16
+ return stopwords
17
+
18
+ # 加載停用詞
19
+ stopwords = load_stopwords("stopwords.txt")
20
+
21
+ # 使用 OpenAI API 進行情緒分析
22
+ def analyze_text(api_key, text):
23
+ try:
24
+ openai.api_key = api_key
25
+ response = openai.chat.completions.create(
26
+ model="gpt-3.5-turbo",
27
+ messages=[
28
+ {"role": "user", "content": f"範例輸出:正面情緒。請分析此文本情緒,輸出其主要為正面、負面或中性情緒: {text}"}
29
+ ]
30
+ )
31
+ return response.choices[0].message.content, None # 返回分析結果
32
+ except Exception as e:
33
+ error_message = f"錯誤發生: {str(e)}"
34
+ print(error_message)
35
+ return None, error_message # 返回錯誤訊息
36
+
37
+ # 文本處理函數
38
+ def process_text(api_key, text, colormap):
39
+ # 使用 jieba 進行中文分詞並過濾停用詞
40
+ words = [word for word in jieba.cut(text) if word not in stopwords]
41
+ words_filtered = " ".join(words)
42
+
43
+ # 生成文字雲
44
+ wordcloud = WordCloud(
45
+ font_path='TaipeiSansTCBeta-Regular.ttf', # 繁體中文字型
46
+ width=400,
47
+ height=200,
48
+ colormap=colormap, # 套用選擇的顏色地圖
49
+ background_color='white',
50
+ min_font_size=10,
51
+ max_words=200
52
+ ).generate(words_filtered)
53
+
54
+ # 保存圖片
55
+ fig, ax = plt.subplots(figsize=(8, 4))
56
+ ax.imshow(wordcloud, interpolation='bilinear')
57
+ ax.axis('off')
58
+ plt.savefig("wordcloud.png", bbox_inches='tight', pad_inches=0)
59
+ plt.close(fig)
60
+
61
+ # 呼叫情緒分析函數
62
+ analysis_result, error = analyze_text(api_key, text)
63
+ return "wordcloud.png", analysis_result
64
+
65
+ # 加載字型
66
+ fm.fontManager.addfont('TaipeiSansTCBeta-Regular.ttf')
67
+ mpl.rc('font', family='Taipei Sans TC Beta')
68
+
69
+ # jieba 設定
70
+ jieba.set_dictionary("dict.txt")
71
+ jieba.analyse.set_stop_words("stopwords.txt")
72
+
73
+ # 定義僅限圖片中提供的顏色地圖
74
+ color_maps = [
75
+ "Greys", "Purples", "Blues", "Greens", "Oranges", "Reds",
76
+ "YlOrBr", "YlOrRd", "OrRd", "PuRd", "RdPu", "BuPu", "GnBu",
77
+ "PuBu", "YlGnBu", "PuBuGn", "BuGn", "YlGn"
78
+ ]
79
+
80
+ # 創建 Gradio 介面
81
+ iface = gr.Interface(
82
+ fn=process_text,
83
+ inputs=[
84
+ gr.Textbox(label="請輸入你的 API 金鑰", placeholder="在此輸入 API 金鑰...", type="password"),
85
+ gr.Textbox(label="請輸入文本", placeholder="在此輸入文本...", lines=5),
86
+ gr.Dropdown(label="選擇文字雲風格", choices=color_maps, value="Blues")
87
+ ],
88
+ outputs=[gr.Image(type="filepath"), "text"],
89
+ title="文字雲與情緒分析工具",
90
+ description="輸入中文或英文文本,生成文字雲並分析其情緒(正面、負面或中性)。"
91
+ )
92
+
93
+ # 啟動介面
94
+ iface.launch()