EduTechTeam's picture
Create app.py
1963ca3 verified
import gradio as gr
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import openai
import matplotlib as mpl
import matplotlib.font_manager as fm
import jieba
import jieba.analyse
# 載入停用詞
def load_stopwords(file_path):
stopwords = set()
with open(file_path, 'r', encoding='utf-8') as f:
for line in f:
stopwords.add(line.strip())
return stopwords
# 加載停用詞
stopwords = load_stopwords("stopwords.txt")
# 使用 OpenAI API 進行情緒分析
def analyze_text(api_key, text):
try:
openai.api_key = api_key
response = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": f"範例輸出:正面情緒。請分析此文本情緒,輸出其主要為正面、負面或中性情緒: {text}"}
]
)
return response.choices[0].message.content, None # 返回分析結果
except Exception as e:
error_message = f"錯誤發生: {str(e)}"
print(error_message)
return None, error_message # 返回錯誤訊息
# 文本處理函數
def process_text(api_key, text, colormap):
# 使用 jieba 進行中文分詞並過濾停用詞
words = [word for word in jieba.cut(text) if word not in stopwords]
words_filtered = " ".join(words)
# 生成文字雲
wordcloud = WordCloud(
font_path='TaipeiSansTCBeta-Regular.ttf', # 繁體中文字型
width=400,
height=200,
colormap=colormap, # 套用選擇的顏色地圖
background_color='white',
min_font_size=10,
max_words=200
).generate(words_filtered)
# 保存圖片
fig, ax = plt.subplots(figsize=(8, 4))
ax.imshow(wordcloud, interpolation='bilinear')
ax.axis('off')
plt.savefig("wordcloud.png", bbox_inches='tight', pad_inches=0)
plt.close(fig)
# 呼叫情緒分析函數
analysis_result, error = analyze_text(api_key, text)
return "wordcloud.png", analysis_result
# 加載字型
fm.fontManager.addfont('TaipeiSansTCBeta-Regular.ttf')
mpl.rc('font', family='Taipei Sans TC Beta')
# jieba 設定
jieba.set_dictionary("dict.txt")
jieba.analyse.set_stop_words("stopwords.txt")
# 定義僅限圖片中提供的顏色地圖
color_maps = [
"Greys", "Purples", "Blues", "Greens", "Oranges", "Reds",
"YlOrBr", "YlOrRd", "OrRd", "PuRd", "RdPu", "BuPu", "GnBu",
"PuBu", "YlGnBu", "PuBuGn", "BuGn", "YlGn"
]
# 創建 Gradio 介面
iface = gr.Interface(
fn=process_text,
inputs=[
gr.Textbox(label="請輸入你的 API 金鑰", placeholder="在此輸入 API 金鑰...", type="password"),
gr.Textbox(label="請輸入文本", placeholder="在此輸入文本...", lines=5),
gr.Dropdown(label="選擇文字雲風格", choices=color_maps, value="Blues")
],
outputs=[gr.Image(type="filepath"), "text"],
title="文字雲與情緒分析工具",
description="輸入中文或英文文本,生成文字雲並分析其情緒(正面、負面或中性)。"
)
# 啟動介面
iface.launch()