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endReq
|
| 4 |
+
import plotly.express as px
|
| 5 |
+
import plotly.graph_objects as go
|
| 6 |
+
|
| 7 |
+
DEVELOPER_NAME = "黃千宥、陳奕瑄、汪于捷、李哲弘、洪寓澤"
|
| 8 |
+
|
| 9 |
+
# 初始化 pytrends
|
| 10 |
+
# hl='zh-TW' -> 繁體中文, tz=480 -> 台灣時區 (GMT+8)
|
| 11 |
+
pytrends = TrendReq(hl='zh-TW', tz=480)
|
| 12 |
+
PLOTLY_TEMPLATE = "plotly_dark"
|
| 13 |
+
def analyze_google_trends(keywords_str: str, timeframe: str):
|
| 14 |
+
"""
|
| 15 |
+
根據輸入的關鍵字和時間範圍,從 Google Trends 獲取並分析資料。
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
keywords_str: 以逗號分隔的關鍵字字串。
|
| 19 |
+
timeframe: Gradio 選項對應的時間範圍字串。
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
一個包含兩個 Plotly 圖表的元組 (時間趨勢圖, 區域熱度圖)。
|
| 23 |
+
"""
|
| 24 |
+
if not keywords_str:
|
| 25 |
+
gr.Warning("請至少輸入一個關鍵字!")
|
| 26 |
+
# 回傳空的圖表
|
| 27 |
+
return go.Figure(), go.Figure()
|
| 28 |
+
|
| 29 |
+
# 解析關鍵字
|
| 30 |
+
kw_list = [kw.strip() for kw in keywords_str.split(',')]
|
| 31 |
+
if len(kw_list) > 5:
|
| 32 |
+
gr.Warning("為了圖表清晰,最多支援比較 5 個關鍵字。")
|
| 33 |
+
kw_list = kw_list[:5]
|
| 34 |
+
|
| 35 |
+
# 對應 Gradio 選項到 pytrends 的時間格式
|
| 36 |
+
timeframe_map = {
|
| 37 |
+
"過去 7 天": 'now 7-d',
|
| 38 |
+
"過去一個月": 'today 1-m',
|
| 39 |
+
"過去三個月": 'today 3-m',
|
| 40 |
+
"過去一年": 'today 12-m',
|
| 41 |
+
}
|
| 42 |
+
selected_timeframe = timeframe_map.get(timeframe, 'now 7-d')
|
| 43 |
+
|
| 44 |
+
try:
|
| 45 |
+
# 1. 獲取時間序列資料
|
| 46 |
+
pytrends.build_payload(kw_list, cat=0, timeframe=selected_timeframe, geo='', gprop='')
|
| 47 |
+
interest_over_time_df = pytrends.interest_over_time()
|
| 48 |
+
|
| 49 |
+
if interest_over_time_df.empty:
|
| 50 |
+
gr.Warning(f"找不到關於 '{keywords_str}' 的時間趨勢資料。")
|
| 51 |
+
time_fig = go.Figure()
|
| 52 |
+
else:
|
| 53 |
+
interest_over_time_df = interest_over_time_df.drop(columns=['isPartial'], errors='ignore')
|
| 54 |
+
time_fig = plot_interest_over_time(interest_over_time_df, f"'{', '.join(kw_list)}' 在過去 {timeframe} 的搜尋熱度趨勢")
|
| 55 |
+
|
| 56 |
+
# 2. 獲取區域熱度資料
|
| 57 |
+
# 注意:區域熱度分析不支援多個關鍵字同時比較,因此我們只分析第一個關鍵字
|
| 58 |
+
first_keyword = kw_list[0]
|
| 59 |
+
pytrends.build_payload([first_keyword], cat=0, timeframe=selected_timeframe, geo='', gprop='')
|
| 60 |
+
interest_by_region_df = pytrends.interest_by_region(resolution='COUNTRY', inc_low_vol=True, inc_geo_code=False)
|
| 61 |
+
|
| 62 |
+
if interest_by_region_df.empty:
|
| 63 |
+
gr.Warning(f"找不到關於 '{first_keyword}' 的區域熱度資料。")
|
| 64 |
+
region_fig = go.Figure()
|
| 65 |
+
else:
|
| 66 |
+
# 只取前 20 名
|
| 67 |
+
interest_by_region_df = interest_by_region_df.sort_values(by=first_keyword, ascending=False).head(20)
|
| 68 |
+
region_fig = plot_interest_by_region(interest_by_region_df, f"'{first_keyword}' 在全球的區域熱度 Top 20")
|
| 69 |
+
|
| 70 |
+
return time_fig, region_fig
|
| 71 |
+
|
| 72 |
+
except Exception as e:
|
| 73 |
+
gr.Error(f"查詢時發生錯誤: {e}")
|
| 74 |
+
return go.Figure(), go.Figure()
|
| 75 |
+
|
| 76 |
+
def plot_interest_over_time(df: pd.DataFrame, title: str):
|
| 77 |
+
"""使用 Plotly 繪製時間趨勢圖。"""
|
| 78 |
+
fig = px.line(df, x=df.index, y=df.columns, title=title, labels={'value': '相對熱度', 'date': '日期', 'variable': '關鍵字'})
|
| 79 |
+
fig.update_layout(
|
| 80 |
+
template=PLOTLY_TEMPLATE,
|
| 81 |
+
paper_bgcolor='rgba(0,0,0,0)',
|
| 82 |
+
plot_bgcolor='rgba(0,0,0,0.2)',
|
| 83 |
+
legend_title_text=''
|
| 84 |
+
)
|
| 85 |
+
return fig
|
| 86 |
+
|
| 87 |
+
def plot_interest_by_region(df: pd.DataFrame, title: str):
|
| 88 |
+
"""使用 Plotly 繪製區域熱度長條圖。"""
|
| 89 |
+
fig = px.bar(df, x=df.index, y=df.columns[0], title=title, labels={'y': '相對熱度', 'index': '國家/地區'})
|
| 90 |
+
fig.update_layout(
|
| 91 |
+
template=PLOTLY_TEMPLATE,
|
| 92 |
+
paper_bgcolor='rgba(0,0,0,0)',
|
| 93 |
+
plot_bgcolor='rgba(0,0,0,0.2)'
|
| 94 |
+
)
|
| 95 |
+
fig.update_xaxes(categoryorder='total descending')
|
| 96 |
+
return fig
|
| 97 |
+
|
| 98 |
+
with gr.Blocks(
|
| 99 |
+
theme=gr.themes.Soft(
|
| 100 |
+
primary_hue="blue",
|
| 101 |
+
secondary_hue="cyan",
|
| 102 |
+
font=["Arial", "sans-serif"]
|
| 103 |
+
)
|
| 104 |
+
) as app:
|
| 105 |
+
gr.Markdown(f"""
|
| 106 |
+
<div style='text-align: center; padding: 20px; color: white;'>
|
| 107 |
+
<h1 style='font-size: 3em; color: #2563eb;'>📊 Google Trends 趨勢分析儀表板</h1>
|
| 108 |
+
<p style='font-size: 1.2em; color: #A9A9A9;'>輸入關鍵字,洞察全球搜尋趨勢與市場脈動</p>
|
| 109 |
+
<p style='font-size: 0.9em; color: #888;'>Designed by: {DEVELOPER_NAME}</p>
|
| 110 |
+
</div>
|
| 111 |
+
""")
|
| 112 |
+
|
| 113 |
+
with gr.Group():
|
| 114 |
+
with gr.Row():
|
| 115 |
+
keywords_input = gr.Textbox(
|
| 116 |
+
label="🔍 輸入關鍵字",
|
| 117 |
+
placeholder="例如:Bitcoin, Ethereum, Dogecoin (以逗號分隔)",
|
| 118 |
+
scale=3
|
| 119 |
+
)
|
| 120 |
+
timeframe_input = gr.Radio(
|
| 121 |
+
["過去 7 天", "過去一個月", "過去三個月", "過去一年"],
|
| 122 |
+
label="🗓️ 選擇時間範圍",
|
| 123 |
+
value="過去 7 天",
|
| 124 |
+
scale=2
|
| 125 |
+
)
|
| 126 |
+
analyze_button = gr.Button("🚀 開始分析", variant="primary")
|
| 127 |
+
|
| 128 |
+
with gr.Tabs():
|
| 129 |
+
with gr.TabItem("📈 時間趨勢比較"):
|
| 130 |
+
time_series_plot = gr.Plot()
|
| 131 |
+
with gr.TabItem("🌍 全球區域熱度"):
|
| 132 |
+
region_plot = gr.Plot()
|
| 133 |
+
gr.Markdown("<p style='text-align: center; color: #888;'>註:區域熱度分析僅針對您輸入的第一個關鍵字。</p>")
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
analyze_button.click(
|
| 137 |
+
fn=analyze_google_trends,
|
| 138 |
+
inputs=[keywords_input, timeframe_input],
|
| 139 |
+
outputs=[time_series_plot, region_plot]
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
gr.Examples(
|
| 143 |
+
examples=[
|
| 144 |
+
["Bitcoin, Ethereum", "過去三個月"],
|
| 145 |
+
["穩定幣, Coinbase", "過去一年"],
|
| 146 |
+
["NVIDIA, AMD, TSMC", "過去一個月"],
|
| 147 |
+
],
|
| 148 |
+
inputs=[keywords_input, timeframe_input]
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
app.launch(share=True, debug=False, show_error=True, show_api=False)
|