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