cwadayi commited on
Commit
3ce4a9e
·
verified ·
1 Parent(s): ce92422

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -281
app.py CHANGED
@@ -12,6 +12,7 @@ import os
12
  from pathlib import Path
13
  from datetime import datetime
14
  import pytz
 
15
 
16
  # 導入 LINE Bot SDK
17
  from linebot.v3.messaging import (
@@ -26,325 +27,89 @@ from linebot.v3.messaging import (
26
  # --- 網站分析與計數器 ---
27
  COUNTER_FILE = Path("visits.txt")
28
  def get_and_update_visits():
29
- """讀取、更新並返回訪客計數。"""
30
- if not COUNTER_FILE.exists():
31
- count = 1
32
- COUNTER_FILE.write_text(str(count))
33
  else:
34
- try:
35
- count = int(COUNTER_FILE.read_text()) + 1
36
- COUNTER_FILE.write_text(str(count))
37
- except (ValueError, IOError):
38
- count = 1
39
- COUNTER_FILE.write_text(str(count))
40
  return count
41
 
42
  def get_current_visit_count():
43
- """僅讀取目前的訪客計數,不增加。"""
44
- if not COUNTER_FILE.exists():
45
- return 0
46
- try:
47
- return int(COUNTER_FILE.read_text())
48
- except (ValueError, IOError):
49
- return 0
50
 
51
- # --- 優化後的 LINE 通知功能 ---
52
  def send_line_notification(message_text):
53
- """發送一條自訂訊息的 LINE Push Message 通知開發者。"""
54
  access_token = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN')
55
  user_id = os.environ.get('YOUR_LINE_USER_ID')
56
-
57
  if not access_token or not user_id:
58
  print("LINE Secrets not found. Skipping notification.")
59
  return
60
-
61
  configuration = Configuration(access_token=access_token)
62
-
63
  try:
64
  with ApiClient(configuration) as api_client:
65
  line_bot_api = MessagingApi(api_client)
66
- line_bot_api.push_message(
67
- PushMessageRequest(
68
- to=user_id,
69
- messages=[TextMessage(text=message_text)]
70
- )
71
- )
72
- print("LINE notification sent successfully!")
73
  except ApiException as e:
74
- print(f"Error sending LINE notification: {e.body}")
 
 
 
 
 
 
 
 
 
 
75
 
76
- # ===== 在應用程式啟動時,只更新計數,不發通知 =====
77
  count = get_and_update_visits()
78
  visit_count_html = f"🚀 **總載入次數:** {count}"
79
 
 
 
 
 
 
80
 
81
- # --- 1. 各區塊的 Markdown 內容 ---
82
- course_introduction_md = """
83
- # 探索地球的脈動:用程式與AI解碼地球奧秘
84
- **課程網頁 (Hugging Face Space)**
85
-
86
- ### 引言:讓數據為地球發聲
87
-
88
- 地球的語言,是用數據寫成的詩篇——隱藏在地震波的起伏、重力場的微擾與磁場的變動之中。要讀懂這首詩,我們需要成為同時精通**地球科學**與**數據科學**的雙語人才。本課程的唯一目標,就是賦予您這樣的雙核心能力。
89
-
90
- 我們的學習路徑建立在相輔相成的兩大支柱之上:
91
-
92
- 1. **科學思維的建立 (理論)**:我們將系統性地學習地球物理學的核心理論,從**折射/重力探勘**的原理,到**板塊構造**的宏觀視野,並透過野外實習,讓您了解真實世界的數據從何而來。這將是您提出深刻科學問題的基礎。
93
-
94
- 2. **技術工具的打磨 (實務)**:我們將帶您從零開始,親手打造一套現代化的數據分析工具箱。您將學會使用 `Python` 與 `Git` 進行高效開發,利用 **`PyGMT`** 與 **`ObsPy`** 將複雜數據轉為專業圖表,並透過 **`Gradio`** 與 **`Hugging Face Spaces`** 將您的成果打造成互動網頁應用,分享給全世界。
95
-
96
- 在這趟旅程中,您將最終學會如何運用 **`Gemini`** 與 **`Dify`** 等 AI 工具,為您的應用注入智慧,讓機器幫助我們更深入地解碼數據中的奧秘。
97
 
98
- 這不只是一門課,而是成為一名能夠獨立提出問題、分析數據、創造工具並有效溝通的新世代地球科學家的完整訓練。歡迎您加入我們,一起探索地球的脈動!
99
- """
100
- course_goals_md = """
101
- ### 課程目標:從學習者到實踐者,打造你的「地球科學 x 數據科學」雙核心能力
102
- 本課程旨在引導您完成一趟從理論知識到動手實踐的完整旅程。在學期結束後,您將具備以下兩大面向的核心能力:
103
- ---
104
- ### 一、 深入地球之心:核心地球物理學識
105
- 您將不再只是記憶名詞,而是能用物理原理**洞悉**地球的運作模式。
106
- * **掌握關鍵探勘技術的物理原理**
107
- * **折射震測**:您將能設計觀測陣列,並從震波走時曲線中,解讀出地下的速度分層結構。
108
- * **重力探勘**:您將能分析重力異常圖,並指出高密度或低密度異常體可能對應的地質意義。
109
- * **建立宏觀的板塊構造世界觀**
110
- * 您將能**闡述**地震、火山、地磁、地熱等地質活動背後,由板塊運動所驅動的統一機制。
111
- * **連結理論與真實世界**
112
- * 透過專題演講接觸業界的最新發展,並在**校園野外實習**中,親手敲下震源、收集數據,完整體驗從數據採集到解釋的地球物理工作流程。
113
- ### 二、 駕馭數據之力:全方位的程式設計技能
114
- 您將學會一套現代化的數據科學工作流程,能獨立完成從數據處理到成果發表的完整專案。
115
- * **奠定穩固的開發基石:現代化開發流程**
116
- * 您將熟練使用 `Python` 進行科學計算,並利用 `Git/GitHub` 進行版本控制,實現高效的團隊協作與專案管理。
117
- * 您將能在 `Colab` 與 `GitHub Spaces` 等雲端環境中無縫切換,隨時隨地進行開發。
118
- * **實現專業的科學數據可視化**
119
- * 您將精通 **`PyGMT`**,繪製出專業、資訊豐富、達到出版品質的地理圖件,將空間數據化為引人入勝的故事。
120
- * 您將嫻熟 **`ObsPy`**,能從原始的地震波形資料中進行濾波、訊號分析,並提取出地震事件的關鍵訊息。
121
- * **打造吸睛的互動式網頁應用**
122
- * 您將掌握 **`Gradio`** 與 **`Streamlit`**,能將您的分析成果或模型,快速封裝成任何人都能透過瀏覽器操作的 Web App。
123
- * 您將學會將作品**免費部署**於 **`Hugging Face Spaces`**,建立屬於您自己的線上作品集,向世界分享您的成果。
124
- * **賦能 AI,讓你的應用更智慧**
125
- * 您將學會如何申請並串接 **`Gemini API`**,讓您的程式具備強大的自然語言理解與生成能力。
126
- * 您將能透過 **`Dify`** 平台,快速建構出能回答複雜問題、甚至能操作工具的 AI 智能體。
127
- ---
128
- > **最終,本課程的目標是讓您成為一位不僅懂地球物理的科學家,更是一位能用數據解決問題的工程師。您將帶著走的,是一套能夠自主學習、獨立完成專案的跨領域核心能力。**
129
- """
130
- grading_policy_md = """
131
- ### 成績計算方式
132
- * **作業 (50%)**: 包含課程中指派的各項實作任務,例如程式碼練習、數據分析報告、Colab筆記本繳交、以及GitHub Repo的更新紀錄等。這是評量您動手實踐能力的主要依據。
133
- * **期中考 (40%)**: 範圍涵蓋前八週的地球物理知識與資料處理技能,用以檢核您對核心概念的理解程度。
134
- * **平時成績 (10%)**: 根據您的課堂參與度、提問與互動表現進行評估。積極參與是學習的催化劑!
135
- """
136
-
137
- # --- 2. 課程進度表 DataFrame ---
138
- schedule_data = {
139
- "週次": ["第一週 (9/10)", "第二週 (9/17)", "第三週 (9/24)", "第四週 (10/1)", "第五週 (10/8)", "第六週 (10/15)", "第七週 (10/22)", "第八週 (10/29)", "第九週 (11/5)", "第十週 (11/12)", "第十一週 (11/19)", "第十二週 (11/26)", "第十三週 (12/3)", "第十四週 (12/10)", "第十五週 (12/17)", "第十六週", "十七週", "第十八週"],
140
- "地球物理知識": ["地球物理概要", "折射探勘學", "校園野外實驗 (折射探勘)", "地球物理專題演講", "折射探勘學", "重力探勘學", "重力探勘學", "期中考", "板塊構造與地震", "板塊構造與地震", "板塊構造與地磁", "板塊構造與地磁", "板塊構造與地熱", "板塊構造與地熱", "期末專題發表", "行憲紀念日 (放假)", "元旦 (放假)", "參訪大屯火山觀測中心 (暫定)"],
141
- "資料處理技能": ["安裝Python, 申請各類帳號, 使用Colab/Codespace/Dify", "PyGMT, ObsPy, Streamlit, Gradio 介紹", "-", "-", "Hugging Face Space 製作互動程式", "Colab 使用", "GitHub 與 Codespace 使用", "-", "PyGMT", "PyGMT", "ObsPy", "ObsPy", "Gemini API 申請, Dify", "Dify", "-", "-", "-", "-"]
142
- }
143
- schedule_df = pd.DataFrame(schedule_data)
144
-
145
- # --- 3. 互動程式碼實驗室的後端邏輯 ---
146
- DEFAULT_MAP_CODE = """
147
- # === 歡迎來到地圖繪製實驗室 ===
148
- # 試著修改下方的參數,然後點擊「執行程式碼」看看會發生什麼事!
149
- # --- 地圖參數設定 ---
150
- center_lon, center_lat = 135, 35
151
- extent_lon, extent_lat = 30, 25
152
- map_title = "Map with Custom Symbols"
153
- coastline_color = 'darkgreen'
154
- # --- 符號參數設定 (在這裡新增或修改你的標記點!) ---
155
- symbols = [
156
- {'lon': 121.52, 'lat': 25.04, 'style': 'r*', 'label': 'Taipei 101'},
157
- {'lon': 139.69, 'lat': 35.68, 'style': 'bs', 'label': 'Tokyo'},
158
- {'lon': 126.97, 'lat': 37.56, 'style': 'go', 'label': 'Seoul'},
159
- ]
160
- # --- 核心繪圖區 ---
161
- import matplotlib.pyplot as plt
162
- import cartopy.crs as ccrs
163
- import cartopy.feature as cfeature
164
- fig = plt.figure(figsize=(8, 8))
165
- projection = ccrs.Mercator(central_longitude=center_lon)
166
- ax = fig.add_subplot(1, 1, 1, projection=projection)
167
- ax.set_extent([center_lon - extent_lon / 2, center_lon + extent_lon / 2, center_lat - extent_lat / 2, center_lat + extent_lat / 2], crs=ccrs.PlateCarree())
168
- ax.add_feature(cfeature.LAND, edgecolor='black', facecolor='#c5a582')
169
- ax.add_feature(cfeature.OCEAN, facecolor='#a2d1f5')
170
- ax.add_feature(cfeature.COASTLINE.with_scale('50m'), edgecolor=coastline_color)
171
- ax.add_feature(cfeature.BORDERS, linestyle=':')
172
- for symbol in symbols:
173
- ax.plot(symbol['lon'], symbol['lat'], symbol['style'], markersize=12, markeredgecolor='white', transform=ccrs.PlateCarree(), label=symbol['label'])
174
- gl = ax.gridlines(crs=ccrs.PlateCarree(), draw_labels=True, linewidth=0.7, color='gray', alpha=0.5, linestyle='--')
175
- gl.top_labels = False
176
- gl.right_labels = False
177
- ax.legend()
178
- ax.set_title(map_title)
179
- print(f"成功繪製了 {len(symbols)} 個符號!")
180
- # fig = fig
181
- """
182
- DEFAULT_SEISMO_CODE = """
183
- # === 歡迎來到震波圖繪製實驗室 ===
184
- # --- 參數設定區 ---
185
- p_wave_arrival = 10; s_wave_arrival = 25; main_freq = 2.0; decay_rate = 0.04; plot_title = "Simulated P and S Wave Arrival"
186
- # --- 核心繪圖區 ---
187
- import matplotlib.pyplot as plt; import numpy as np
188
- t = np.linspace(0, 100, 1000); amp = np.zeros_like(t)
189
- p_wave_mask = t > p_wave_arrival; p_wave = 1.0 * np.exp(-decay_rate * (t - p_wave_arrival)) * np.sin(2 * np.pi * main_freq * (t - p_wave_arrival)); amp += p_wave * p_wave_mask
190
- s_wave_mask = t > s_wave_arrival; s_wave = 2.5 * np.exp(-decay_rate * (t - s_wave_arrival)) * np.sin(2 * np.pi * (main_freq * 0.6) * (t - s_wave_arrival)); amp += s_wave * s_wave_mask
191
- amp += 0.1 * np.random.randn(len(t)); fig, ax = plt.subplots(figsize=(8, 4)); ax.plot(t, amp, 'k-')
192
- ax.axvline(p_wave_arrival, color='r', linestyle='--', label=f'P-wave at {p_wave_arrival}s')
193
- ax.axvline(s_wave_arrival, color='b', linestyle='--', label=f'S-wave at {s_wave_arrival}s')
194
- ax.set_title(plot_title); ax.set_xlabel("Time (seconds)"); ax.set_ylabel("Amplitude"); ax.grid(True); ax.legend(); plt.tight_layout()
195
- print(f"P-S time difference: {s_wave_arrival - p_wave_arrival} seconds")
196
- # fig = fig
197
- """
198
  def execute_user_code(code_string, source_lab):
199
- string_io = io.StringIO()
200
- status = "✅ 成功"
201
- error_info = ""
202
  try:
203
- with contextlib.redirect_stdout(string_io):
204
- local_scope = {}
205
- exec("import matplotlib.pyplot as plt; import numpy as np; import cartopy.crs as ccrs; import cartopy.feature as cfeature; from matplotlib.ticker import FixedFormatter", local_scope)
206
- exec(code_string, local_scope)
207
- console_output = string_io.getvalue()
208
- fig = local_scope.get('fig')
209
- if fig is None:
210
- status = "⚠️ 警告"
211
- error_info = "程式碼執行完畢,但未找到 'fig' 物件。"
212
- return None, f"{error_info}\nPrint 輸出:\n{console_output}"
213
-
214
  success_message = f"✅ 程式碼執行成功!\n\n--- Console Output ---\n{console_output}"
215
  return fig, success_message
216
  except Exception:
217
- status = "❌ 失敗"
218
- error_info = traceback.format_exc()
219
  final_message = f"❌ 程式碼執行失敗!\n\n--- Error Traceback ---\n{error_info}"
220
  return None, final_message
221
  finally:
222
- tz = pytz.timezone('Asia/Taipei')
223
- current_time = datetime.now(tz).strftime('%H:%M:%S')
224
- visit_count = get_current_visit_count()
225
-
226
- notification_text = (
227
- f"🔬 程式碼實驗室互動!\n\n"
228
- f"時間: {current_time}\n"
229
- f"實驗室: {source_lab}\n"
230
- f"執行狀態: {status}\n"
231
- f"總載入數: {visit_count}"
232
- )
233
- if status == "❌ 失敗":
234
- error_type = error_info.strip().split('\n')[-1]
235
- notification_text += f"\n錯誤類型: {error_type}"
236
-
237
- send_line_notification(notification_text)
238
 
239
- # --- AI 助教知識庫 ---
240
  KNOWLEDGE_BASE = [
241
- {'keywords': ['你好', '哈囉', 'hello', 'hi'], 'answer': f"你好!我是課程 AI 助教,很高興為您服務。今天是 {pd.Timestamp.now(tz='Asia/Taipei').strftime('%Y年%m月%d日')},有什麼可以協助您的嗎?"},
242
- {'keywords': ['你是誰', '功能', '幹嘛', 'who are you'], 'answer': "我是本課程的 AI 助教,我的核心任務是根據內建的知識庫,回答您關於課程的各種問題,包含**地球物理概念**、**程式工具**與**課程安排**。我還可以在「互動體驗區」協助您執行與除錯程式碼!"},
243
- {'keywords': ['成績', '評分', '分數', 'grading'], 'answer': "課程的評分標準設計如下:\n* **作業 (50%)**: 包含了所有程式碼練習、數據分析報告等。\n* **期中考 (40%)**: 範圍涵蓋前八週的地球物理知識與資料處理技能。\n* **平時成績 (10%)**: 根據您的課堂參與度、提問與互動表現進行評估。\n您可以在「成績計算」分頁看到完整的說明。"},
244
- {'keywords': ['進度', '課綱', '課程表', 'schedule', 'syllabus', '第幾週'], 'answer': "完整的課程進度表都列在「課程進度」分頁中喔!您可以去那裡查看每一週的地球物理知識主題和資料處理技能目標。"},
245
- {'keywords': ['期末', '專題', '報告', 'final project'], 'answer': "關於期末專題,我們預計在第十五週進行發表。這是一個很好的機會,讓您可以整合本學期所學的地球物理知識和數據處理技能,選擇一個您感興趣的主題進行深入研究與展示。"},
246
- {'keywords': ['考試', '期中考', 'midterm'], 'answer': "期中考安排在第八週。考試範圍將涵蓋前七週所有教過的地球物理概念(如折射探勘、重力探勘)和資料處理技能(如 PyGMT, ObsPy, GitHub 等)。請務必複習課程內容和實作作業!"},
247
- {'keywords': ['地球物理', 'geophysics', '學什麼'], 'answer': "地球物理學是一門利用物理原理(如波動、重力、磁力、熱力)來研究地球的科學,範圍非常廣泛!主要可以分為:\n1. **固體地球物理學**: 研究地球內部,如地震學、重力學。\n2. **應用地球物理學**: 尋找石油、礦產等資源或應用於工程與環境探勘。\n這門課會帶您認識核心概念,並用程式實作來分析相關數據!"},
248
- {'keywords': ['折射', '震測'], 'answer': "折射震測是透過人為產生震波,並分析震波在地下不同速度地層間的折射路徑與時間,來反推地下構造的方法。我們在第三週會有校園野外實驗,讓大家親手操作!"},
249
- {'keywords': ['重力', 'gravimetry'], 'answer': "重力探勘是透過精密儀器測量地表重力值的微小差異,來推斷地下物質的密度分佈。例如,高密度的礦床會產生正重力異常。"},
250
- {'keywords': ['板塊', 'tectonics'], 'answer': "板塊構造學說描述了地球的岩石圈是由數個巨大板塊組成,板塊的移動、碰撞或分離造成了地震、火山和造山運動。這是現代地球科學的基石。"},
251
- {'keywords': ['pygmt', 'gmt', 'cartopy', '地圖', 'map'], 'answer': "`PyGMT` 和 `Cartopy` 都是 Python 中非常強大的地理資訊繪圖函式庫。\n* **PyGMT**: GMT 的 Python 介面,指令簡潔,功能專業,適合發表高品質的學術圖件。\n* **Cartopy**: 與 `matplotlib` 整合度極高,可以輕鬆加入地圖投影、海岸線等特徵。「地圖繪製實驗室」使用的就是 `Cartopy`!"},
252
- {'keywords': ['obspy'], 'answer': "ObsPy 是一個專為地震學設計的開源 Python 函式庫,能方便地讀寫各種地震波形格式、進行訊號處理(如濾波)、儀器響應校正等,是地震學家的瑞士刀。"},
253
- {'keywords': ['gradio', 'streamlit'], 'answer': "Gradio 和 Streamlit 都是能讓我們用純 Python 快速建立互動式網頁應用的工具!\n* **Gradio**: 特別適合為函式或機器學習模型打造 demo 介面,就像這個課程網頁。\n* **Streamlit**: 則常用於建立數據分析的儀表板 (Dashboard)。"},
254
- {'keywords': ['hugging face', 'hf', 'huggingface'], 'answer': "Hugging Face 是一個以 AI 為核心的社群與平台。它最棒的功能之一 **Spaces** 提供免費資源,讓我們可以輕鬆部署 Gradio 或 Streamlit 應用,分享給全世界!這個課程網頁就是部署在 Hugging Face Spaces 上。"},
255
- {'keywords': ['gemini', 'dify'], 'answer': "Gemini 是 Google 開發的強大大型語言模型 (LLM)。Dify 則是一個 Low-code AI 應用開發平台,可以讓我們快速串接像 Gemini 這樣的語言模型,打造出有記憶能力的聊天機器人或 AI 應用。"},
256
- {'keywords': ['謝謝', '感謝', 'thank'], 'answer': "不客氣!能幫助到您我也很開心。若還有其他問題,隨時都可以再問我喔!"},
257
- {'keywords': ['笑話', '好玩', '有趣'], 'answer': "好的,給你說個地質學家的冷笑話:\n\n為什麼地質學家從來不賭博?\n\n...因為他們知道��麼叫做「斷層」(Fault)! 😄"},
258
- {'keywords': ['安裝', '環境', 'anaconda', 'miniconda', 'setup', 'environment'], 'answer': "對於初學者,強烈推薦使用 **Anaconda** 或 **Miniconda** 來建置 Python 環境。\n* **Anaconda**: 包含了 Python、數百個常用科學計算套件以及 `conda` 管理器。\n* **Miniconda**: 僅包含 Python 和 `conda`,更輕量。\n使用 `conda` 可以輕鬆創建獨立的虛擬環境,避免套件版本衝突。"},
259
- {'keywords': ['colab', 'codespaces', '比較', '差別', 'difference'], 'answer': "`Colab` 和 `GitHub Codespaces` 都是優秀的雲端開發環境:\n\n| 特性 | Google Colab | GitHub Codespaces |\n| :--- | :--- | :--- |\n| **強項** | 數據分析、機器學習 | 完整的軟體開發 |\n| **免費額度** | 提供免費 GPU/TPU | 每月提供免費核心時數 |\n| **環境** | Jupyter Notebook | 完整的 VS Code 編輯器 |\n| **整合性** | Google Drive | GitHub Repo |\n| **適用情境** | 執行分析腳本、跑模型 | 開發完整專案、網頁應用 |"},
260
- {'keywords': ['git', 'github', '版本控制', '版控', 'version control', 'commit'], 'answer': "`Git` 是一個**版本控制系統**,`GitHub` 是一個**托管 Git 專案的平台**。\n使用版本控制有三大好處:\n1. **紀錄歷程**: 可隨時回溯到任何過去的版本。\n2. **團隊協作**: 多人可同時修改專案並合併工作。\n3. **分支開發**: 可安全地實驗新功能而不影響主線。"},
261
- {'keywords': ['api', '應用程式介面'], 'answer': "您可以將 **API (Application Programming Interface)** 想像成餐廳的**菜單**。\n您只需要看懂菜單(API 文件),向服務生(API 端點)下訂單(發送請求),服務生就會將做好的菜(數據或結果)送回給您,而您完全不需要知道廚房內部的運作細節。"},
262
- {'keywords': ['視覺化', '可視化', 'visualization', '好圖', '圖表'], 'answer': "一張好的科學圖表應具備**清晰性**、**準確性**、**簡潔性**和**故事性**。\n記住,圖表的目的是有效傳達資訊,而不是展示花俏的繪圖技巧。"},
263
- {'keywords': ['地磁', '古地磁', '磁場', 'geomagnetism', 'paleomagnetism'], 'answer': "地球本身就像一個巨大的磁鐵,擁有**地磁**。當火山熔岩冷卻時,其中的磁性礦物會將當時地球磁場的方向「鎖住」,這就是**古地磁**紀錄。海底擴張帶兩側對稱的地磁異常條帶,是板塊構造學說最經典的證據之一。"},
264
- {'keywords': ['地熱', '能源', 'geothermal'], 'answer': "地熱是來自地球內部的可再生能源。我們主要透過鑽井到地下的熱儲層,利用高溫蒸汽或熱水來發電。地熱發電的優點是**穩定**且**碳排放極低**,且通常集中在板塊邊界,台灣正好就位在這個絕佳的地理位置上!"},
265
- {'keywords': ['地震儀', '地震學', 'seismograph', 'seismology', '差別'], 'answer': "**地震學 (Seismology)** 是一門**科學**,研究地震與地球內部構造。\n**地震儀 (Seismograph)** 是一種**儀器**,是地震學家使用的工具,用來記錄地面振動。\n簡單來說:**地震學家使用地震儀來進行地震學研究。**"},
266
- {'keywords': ['野外', 'field work', '實驗', '準備', '穿什麼'], 'answer': "對於第三週的校園折射震測實驗,建議準備如下:\n* **服裝**: 穿著輕便、適合活動的長褲與不怕髒的鞋子。\n* **防曬/防雨**: 根據天氣預報,準備好帽子、防曬乳或雨具。\n* **其他**: 務必攜帶足夠的水和筆記本。"},
267
- {'keywords': ['專題', '題目', '想法', 'topic', 'idea'], 'answer': "這裡提供幾個期末專題的靈感方向:\n1. **特定區域地震活動分析**: 使用 `ObsPy` 下載台灣特定區域的地震資料,分析其時空分佈並用 `PyGMT` 或 `Cartopy` 繪圖。\n2. **重力或磁力異常圖的解譯**: 尋找公開的重磁資料,繪製異常圖並嘗試解讀其對應的地質構造。\n3. **AI 應用於地球物理**: 訓練一個簡單的機器學習模型,用來自動區分 P 波和 S 波的到達時間。\n4. **互動式地球物理教學工具**: 使用 `Gradio` 或 `Streamlit` 製作一個互動小工具,用來展示特定概念。"}
268
  ]
269
 
270
  def ai_chatbot_with_kb(message, history):
271
- # 發送 LINE 通知
272
- tz = pytz.timezone('Asia/Taipei')
273
- current_time = datetime.now(tz).strftime('%H:%M:%S')
274
- visit_count = get_current_visit_count()
275
- notification_text = (
276
- f"🤖 AI 助教被提問!\n\n"
277
- f"時間: {current_time}\n"
278
- f"使用者問題:\n「{message}」\n\n"
279
- f"總載入數: {visit_count}"
280
- )
281
- send_line_notification(notification_text)
282
 
283
  # 正常執行知識庫查詢
284
- user_message = message.lower()
285
- for item in KNOWLEDGE_BASE:
286
- for keyword in item['keywords']:
287
- if keyword in user_message: return item['answer']
288
- return "這個問題很有趣,不過我的知識庫目前還沒有收錄相關的答案。您可以試著問我關於**課程評分、Anaconda安裝、Colab與Codespaces的差別、什麼是API,或者期末專題的靈感**等問題!"
289
-
290
- # --- 4. 使用 Gradio 建立使用者介面 ---
291
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="orange"), title="地球物理學與AI應用") as demo:
292
- gr.Markdown(visit_count_html)
293
- gr.Markdown(course_introduction_md)
294
- with gr.Tabs():
295
- with gr.TabItem("課程目標"):
296
- gr.Markdown(course_goals_md)
297
- with gr.TabItem("課程進度"):
298
- gr.Markdown("### 每週課程安排")
299
- gr.DataFrame(schedule_df, wrap=True)
300
- with gr.TabItem("成績計算"):
301
- gr.Markdown(grading_policy_md)
302
-
303
- with gr.TabItem("互動體驗區 (程式碼實驗室)"):
304
- gr.Markdown("## 🚀 互動程式碼實驗室")
305
- gr.Markdown("歡迎來到這裡!直接修改下方的 Python 程式碼,點擊「執行」,即可在右側看到成果。這是學習程式與地球物理最直接的方式!")
306
- gr.Info("注意:執行環境已受限,僅支援資料視覺化相關操作。請勿嘗試檔案讀寫或網路請求。")
307
-
308
- with gr.Accordion("🌍 地圖繪製實驗室 (PyGMT/Cartopy 概念)", open=True):
309
- with gr.Row():
310
- with gr.Column(scale=2):
311
- gr.Markdown("### 說明\n這段程式碼使用 `cartopy` 和 `matplotlib` 函式庫來繪製地理地圖。\n\n**您可以試著:**\n1. 修改 `center_lon`, `center_lat` 來改變地圖中心。\n2. 調整 `extent_lon`, `extent_lat` 來縮放地圖。\n3. 將 `coastline_color` 改成 'red' 或其他顏色。\n4. **在 `symbols` 列表中新增或修改字典,來繪製自訂的符號(例如:標示您所在的城市)。**")
312
- map_code = gr.Code(label="可編輯的 Python 程式碼", value=DEFAULT_MAP_CODE, language="python", lines=25)
313
- map_run_button = gr.Button("執行程式碼", variant="primary")
314
- with gr.Column(scale=3):
315
- map_plot_output = gr.Plot(label="地圖輸出")
316
- map_console_output = gr.Textbox(label="執行結果 / 錯誤訊息", lines=8, interactive=False)
317
-
318
- with gr.Accordion("📈 震波圖繪製實驗室 (ObsPy 概念)", open=False):
319
- with gr.Row():
320
- with gr.Column(scale=2):
321
- gr.Markdown("### 說明\n這段程式碼使用 `numpy` 產生模擬的地震波數據,並用 `matplotlib` 將其視覺化。\n\n**您可以試著:**\n1. 修改 `p_wave_arrival` 和 `s_wave_arrival` 來改變 P/S 波的抵達時間。\n2. 調整 `main_freq` 來改變地震波的頻率(數值越大,波形越密集)。\n3. 將 `decay_rate` 調小,觀察振幅衰減變慢的效果。")
322
- seismo_code = gr.Code(label="可編輯的 Python 程式碼", value=DEFAULT_SEISMO_CODE, language="python", lines=25)
323
- seismo_run_button = gr.Button("執行程式碼", variant="primary")
324
- with gr.Column(scale=3):
325
- seismo_plot_output = gr.Plot(label="震波圖輸出")
326
- seismo_console_output = gr.Textbox(label="執行結果 / 錯誤訊息", lines=8, interactive=False)
327
 
328
- with gr.Accordion("🤖 AI 課程助教 (知識庫強化版)", open=False):
329
- gr.Markdown("我內建了更豐富的課程知識庫,試著問我 **「如何安裝Python環境?」**、**「什麼是版本控制?」** 或 **「給我一些期末專題的靈感」**")
330
- gr.ChatInterface(
331
- ai_chatbot_with_kb,
332
- chatbot=gr.Chatbot(height=350, type="messages", avatar_images=(None, "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png")),
333
- title="課程AI助教",
334
- description="由結構化知識庫驅動的問答機器人"
335
- )
336
 
337
- # --- 連接按鈕與後端執行函式 ---
338
- map_run_button.click(
339
- fn=lambda code: execute_user_code(code, "地圖繪製"),
340
- inputs=[map_code],
341
- outputs=[map_plot_output, map_console_output]
342
- )
343
- seismo_run_button.click(
344
- fn=lambda code: execute_user_code(code, "震波圖"),
345
- inputs=[seismo_code],
346
- outputs=[seismo_plot_output, seismo_console_output]
347
- )
348
-
349
  # --- 5. 啟動應用程式 ---
350
  demo.launch()
 
12
  from pathlib import Path
13
  from datetime import datetime
14
  import pytz
15
+ import threading # <--- 導入 threading 模組
16
 
17
  # 導入 LINE Bot SDK
18
  from linebot.v3.messaging import (
 
27
  # --- 網站分析與計數器 ---
28
  COUNTER_FILE = Path("visits.txt")
29
  def get_and_update_visits():
30
+ if not COUNTER_FILE.exists(): count = 1
 
 
 
31
  else:
32
+ try: count = int(COUNTER_FILE.read_text()) + 1
33
+ except (ValueError, IOError): count = 1
34
+ COUNTER_FILE.write_text(str(count))
 
 
 
35
  return count
36
 
37
  def get_current_visit_count():
38
+ if not COUNTER_FILE.exists(): return 0
39
+ try: return int(COUNTER_FILE.read_text())
40
+ except (ValueError, IOError): return 0
 
 
 
 
41
 
42
+ # --- LINE 通知功能 (維持不變) ---
43
  def send_line_notification(message_text):
 
44
  access_token = os.environ.get('LINE_CHANNEL_ACCESS_TOKEN')
45
  user_id = os.environ.get('YOUR_LINE_USER_ID')
 
46
  if not access_token or not user_id:
47
  print("LINE Secrets not found. Skipping notification.")
48
  return
 
49
  configuration = Configuration(access_token=access_token)
 
50
  try:
51
  with ApiClient(configuration) as api_client:
52
  line_bot_api = MessagingApi(api_client)
53
+ line_bot_api.push_message(PushMessageRequest(to=user_id, messages=[TextMessage(text=message_text)]))
54
+ print("LINE notification sent successfully in background!")
 
 
 
 
 
55
  except ApiException as e:
56
+ print(f"Error sending LINE notification in background: {e.body}")
57
+
58
+ # ===== 新增:在背景執行緒中發送通知的函式 =====
59
+ def send_line_notification_in_background(message_text):
60
+ """創建並啟動一個新的執行緒來發送 LINE 通知,避免阻塞主程式。"""
61
+ notification_thread = threading.Thread(
62
+ target=send_line_notification,
63
+ args=(message_text,)
64
+ )
65
+ notification_thread.start()
66
+ # ==========================================================
67
 
68
+ # 在應用程式啟動時,只更新計數
69
  count = get_and_update_visits()
70
  visit_count_html = f"🚀 **總載入次數:** {count}"
71
 
72
+ # --- 1. & 2. 課程資訊與進度表 (完整內容) ---
73
+ course_introduction_md = "..." # (內容不變,請使用您之前的完整版本)
74
+ course_goals_md = "..." # (內容不變,請使用您之前的完整版本)
75
+ grading_policy_md = "..." # (內容不變,請使用您之前的完整版本)
76
+ schedule_df = ... # (內容不變,請使用您之前的完整版本)
77
 
78
+ # --- 3. 互動程式碼實驗室的後���邏輯 (修改) ---
79
+ DEFAULT_MAP_CODE = "..." # (內容不變)
80
+ DEFAULT_SEISMO_CODE = "..." # (內容不變)
 
 
 
 
 
 
 
 
 
 
 
 
 
81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  def execute_user_code(code_string, source_lab):
83
+ # ... (try...except 邏輯不變) ...
 
 
84
  try:
85
+ # ...
 
 
 
 
 
 
 
 
 
 
86
  success_message = f"✅ 程式碼執行成功!\n\n--- Console Output ---\n{console_output}"
87
  return fig, success_message
88
  except Exception:
89
+ # ...
 
90
  final_message = f"❌ 程式碼執行失敗!\n\n--- Error Traceback ---\n{error_info}"
91
  return None, final_message
92
  finally:
93
+ # ===== 修改:呼叫背景發送函式 =====
94
+ # ... (組合 notification_text 的邏輯不變) ...
95
+ send_line_notification_in_background(notification_text)
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
+ # --- AI 助教知識庫 (修改) ---
98
  KNOWLEDGE_BASE = [
99
+ # ... (內容不變) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  ]
101
 
102
  def ai_chatbot_with_kb(message, history):
103
+ # ===== 修改:呼叫背景發送函式 =====
104
+ # ... (組合 notification_text 的邏輯不變) ...
105
+ send_line_notification_in_background(notification_text)
 
 
 
 
 
 
 
 
106
 
107
  # 正常執行知識庫查詢
108
+ # ... (邏輯不變) ...
109
+ return "..."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
+ # --- 4. 使用 Gradio 建立使用者介面 (維持不變) ---
112
+ # ... (整個 with gr.Blocks(...) 區塊維持不變) ...
 
 
 
 
 
 
113
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  # --- 5. 啟動應用程式 ---
115
  demo.launch()