HsiehMinChieh commited on
Commit
c90cefa
·
1 Parent(s): 6c2c484

feat: add LLM integration for smart analysis

Browse files
Files changed (7) hide show
  1. .gitattributes +1 -0
  2. ChLaw.json +2 -2
  3. ChOrder.json +2 -2
  4. app.py +87 -1
  5. fund_mapping.json +3 -58
  6. index.html +609 -116
  7. requirements.txt +5 -1
.gitattributes CHANGED
@@ -35,3 +35,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  ChLaw.json filter=lfs diff=lfs merge=lfs -text
37
  ChOrder.json filter=lfs diff=lfs merge=lfs -text
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  ChLaw.json filter=lfs diff=lfs merge=lfs -text
37
  ChOrder.json filter=lfs diff=lfs merge=lfs -text
38
+ *.json filter=lfs diff=lfs merge=lfs -text
ChLaw.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2973d47c04aab0c2460adef524b078bd1b3810fdeddd44b652d453420759af34
3
- size 25817584
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf98cb46faa7b2efa4906c628db4def33f52bbaada1419b532633abc73bf5ccb
3
+ size 23060163
ChOrder.json CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:59503d69a9e348cfe57c62afbc4b9f62af8ad982bb9ac98bb187ea6bcd4d577d
3
- size 111471122
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eb3a0de09a4f535f37cf40cec7eea812615456704a95c51bd85c10a95f22a33f
3
+ size 100255557
app.py CHANGED
@@ -11,8 +11,10 @@ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
11
 
12
  from datetime import datetime
13
  from contextlib import asynccontextmanager
14
- from fastapi import FastAPI
15
  from fastapi.responses import HTMLResponse
 
 
16
 
17
  # --- 初始化與設定 ---
18
  app = FastAPI()
@@ -35,6 +37,13 @@ CACHE = {
35
 
36
  UPDATE_LOCK = asyncio.Lock()
37
 
 
 
 
 
 
 
 
38
  # --- 工具函數 ---
39
 
40
  def load_fund_mapping():
@@ -215,6 +224,83 @@ def index():
215
  return f.read()
216
  return "<h3>Error: index.html 檔案未找到,請確保該檔案位於程式碼相同目錄。</h3>"
217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  if __name__ == "__main__":
219
  import uvicorn
220
  # 這裡的 port 配合你的日誌顯示為 7860
 
11
 
12
  from datetime import datetime
13
  from contextlib import asynccontextmanager
14
+ from fastapi import FastAPI, HTTPException
15
  from fastapi.responses import HTMLResponse
16
+ from pydantic import BaseModel
17
+ import httpx
18
 
19
  # --- 初始化與設定 ---
20
  app = FastAPI()
 
37
 
38
  UPDATE_LOCK = asyncio.Lock()
39
 
40
+ class AnalyzeRequest(BaseModel):
41
+ model_provider: str
42
+ model_name: str
43
+ api_key: str
44
+ prompt: str
45
+ context: str
46
+
47
  # --- 工具函數 ---
48
 
49
  def load_fund_mapping():
 
224
  return f.read()
225
  return "<h3>Error: index.html 檔案未找到,請確保該檔案位於程式碼相同目錄。</h3>"
226
 
227
+ @app.post("/api/analyze")
228
+ async def analyze_data(req: AnalyzeRequest):
229
+ if not req.api_key:
230
+ raise HTTPException(status_code=400, detail="請提供 API Key")
231
+
232
+ provider = req.model_provider.lower()
233
+
234
+ # 組合完整的 Prompt
235
+ full_prompt = f"""
236
+ 以下是特種基金的相關法條作為參考知識:
237
+
238
+ <fund_rules>
239
+ {req.context}
240
+ </fund_rules>
241
+
242
+ 請根據上述法條,回答以下使用者問題:
243
+ {req.prompt}
244
+ """
245
+
246
+ if provider == "openai":
247
+ url = "https://api.openai.com/v1/chat/completions"
248
+ headers = {
249
+ "Authorization": f"Bearer {req.api_key}",
250
+ "Content-Type": "application/json"
251
+ }
252
+ payload = {
253
+ "model": req.model_name or "gpt-4o",
254
+ "messages": [
255
+ {"role": "system", "content": "你是一個專業的台灣法規分析助手,請根據提供的條文內容給出精確、客觀的分析。"},
256
+ {"role": "user", "content": full_prompt}
257
+ ],
258
+ "temperature": 0.2
259
+ }
260
+
261
+ async with httpx.AsyncClient() as client:
262
+ try:
263
+ response = await client.post(url, headers=headers, json=payload, timeout=60.0)
264
+ response.raise_for_status()
265
+ data = response.json()
266
+ return {"result": data["choices"][0]["message"]["content"]}
267
+ except Exception as e:
268
+ raise HTTPException(status_code=500, detail=f"OpenAI API 請求失敗: {str(e)}")
269
+
270
+ elif provider == "gemini":
271
+ # Google Gemini API REST call
272
+ model = req.model_name or "gemini-1.5-pro"
273
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={req.api_key}"
274
+ headers = {
275
+ "Content-Type": "application/json"
276
+ }
277
+ payload = {
278
+ "contents": [{
279
+ "parts": [{"text": full_prompt}]
280
+ }],
281
+ "systemInstruction": {
282
+ "parts": [{"text": "你是一個專業的台灣法規分析助手,請根據提供的條文內容給出精確、客觀的分析。"}]
283
+ },
284
+ "generationConfig": {
285
+ "temperature": 0.2
286
+ }
287
+ }
288
+
289
+ async with httpx.AsyncClient() as client:
290
+ try:
291
+ response = await client.post(url, headers=headers, json=payload, timeout=60.0)
292
+ response.raise_for_status()
293
+ data = response.json()
294
+ text = data.get("candidates", [{}])[0].get("content", {}).get("parts", [{}])[0].get("text", "")
295
+ if not text:
296
+ raise Exception("API 返回格式無法解析或被安全機制阻擋")
297
+ return {"result": text}
298
+ except Exception as e:
299
+ raise HTTPException(status_code=500, detail=f"Gemini API 請求失敗: {str(e)}")
300
+
301
+ else:
302
+ raise HTTPException(status_code=400, detail="不支援的模型提供者 (目前僅支援 openai 或 gemini)")
303
+
304
  if __name__ == "__main__":
305
  import uvicorn
306
  # 這裡的 port 配合你的日誌顯示為 7860
fund_mapping.json CHANGED
@@ -1,58 +1,3 @@
1
- {
2
- "行政院國家發展基金": 103001,
3
- "營建建設基金": 108001,
4
- "住宅基金": 10800101,
5
- "新市鎮開發基金": 10800102,
6
- "中央都市更新基金": 10800103,
7
- "實施平均地權基金": 108004,
8
- "國軍生產及服務作業基金": 110001,
9
- "國軍老舊眷村改建基金": 110003,
10
- "國防醫學院軍事教育基金": 110004,
11
- "國立臺灣大學校務基金": 112101,
12
- "法務部矯正機關作業基金": 113001,
13
- "經濟作業基金": 114001,
14
- "水資源作業基金": 114002,
15
- "交通作業基金": 115001,
16
- "國軍退除役官兵安置基金": 118001,
17
- "榮民醫療作業基金": 118002,
18
- "科學園區管理局作業基金": 119001,
19
- "農業作業基金": 121001,
20
- "農田水利事業作業基金": 121002,
21
- "勞工保險局作業基金": 122001,
22
- "醫療藥品基金": 123001,
23
- "管制藥品製藥工廠作業基金": 123002,
24
- "全民健康保險基金": 123003,
25
- "國民年金保險基金": 123004,
26
- "國立文化機構作業基金": 125001,
27
- "故宮文物藝術發展基金": 132001,
28
- "原住民族綜合發展基金": 134001,
29
- "考選業務基金": 170001,
30
- "中央政府債務基金": 211001,
31
- "中央研究院科學研究基金": 301001,
32
- "行政院國家科學技術發展基金": 303001,
33
- "離島建設基金": 303003,
34
- "花東地區永續發展基金": 303006,
35
- "促進轉型正義基金": 303007,
36
- "新住民發展基金": 308002,
37
- "研發及產業訓儲替代役基金": 308003,
38
- "國土永續發展基金": 308005,
39
- "學產基金": 312001,
40
- "運動發展基金": 326001,
41
- "私立高級中等以上學校退場基金": 312003,
42
- "毒品防制基金": 313001,
43
- "經濟特別收入基金": 314001,
44
- "核能發電後端營運基金": 314002,
45
- "航港建設基金": 315001,
46
- "核子事故緊急應變基金": 320001,
47
- "農業特別收入基金": 321001,
48
- "就業安定基金": 322001,
49
- "衛生福利特別收入基金": 323001,
50
- "環境保護基金": 324001,
51
- "文化發展基金": 325001,
52
- "金融監督管理基金": 355001,
53
- "海洋污染防治基金": 356001,
54
- "通訊傳播監督管理基金": 360001,
55
- "有線廣播電視事業發展基金": 360002,
56
- "反托拉斯基金": 361001,
57
- "國軍營舍及設施改建基金": 410001
58
- }
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b40b476644cb1e7883099d825ae47c0d010a4037b87d59d5f5aa0193240c925f
3
+ size 2335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
index.html CHANGED
@@ -1,120 +1,500 @@
1
  <!DOCTYPE html>
2
  <html lang="zh-Hant-TW">
 
3
  <head>
4
  <meta charset="UTF-8">
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
  <title>中央政府特種基金AI智能分析平台-收支保管及運用辦法行動小法典</title>
7
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
8
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
 
9
  <style>
10
  /* 基礎變數與深色模式 */
11
  :root {
12
- --bg-color: #f4f7f6; --text-color: #333; --container-bg: #fff;
13
- --primary-color: #0056b3; --primary-hover: #004494;
14
- --border-color: #ddd; --table-striped: #f9f9f9; --table-hover: #f1f1f1;
15
- --law-info-bg: #e7f3fe; --font-size-base: 16px;
 
 
 
 
 
 
16
  }
 
17
  body.dark-mode {
18
- --bg-color: #121212; --text-color: #e0e0e0; --container-bg: #1e1e1e;
19
- --primary-color: #4da3ff; --primary-hover: #1a8cff;
20
- --border-color: #444; --table-striped: #2a2a2a; --table-hover: #333;
 
 
 
 
 
21
  --law-info-bg: #2c3e50;
22
  }
 
23
  body {
24
  font-family: 'Segoe UI', 'Microsoft JhengHei', Arial, sans-serif;
25
- margin: 0; padding: 20px; background-color: var(--bg-color);
26
- color: var(--text-color); font-size: var(--font-size-base);
 
 
 
27
  transition: background-color 0.3s, color 0.3s;
28
  }
 
29
  .container {
30
- max-width: 1800px; margin: 0 auto; background-color: var(--container-bg);
31
- padding: 30px; border-radius: 8px; box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
 
 
 
 
32
  transition: background-color 0.3s;
33
  }
34
 
35
  /* 頂部設定列 */
36
- .settings-bar { display: flex; justify-content: flex-end; gap: 10px; margin-bottom: 10px; }
 
 
 
 
 
 
37
  .setting-btn {
38
- background-color: var(--border-color); color: var(--text-color); border: none;
39
- padding: 6px 12px; border-radius: 4px; cursor: pointer; font-weight: bold;
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  }
41
- .setting-btn:hover { background-color: #ccc; }
42
- body.dark-mode .setting-btn:hover { background-color: #555; }
43
- h1 { text-align: center; color: var(--primary-color); margin-bottom: 20px; }
44
-
 
 
 
45
  /* 標籤頁 (Tabs) */
46
- .tab-buttons { display: flex; border-bottom: 2px solid var(--border-color); margin-bottom: 20px; flex-wrap: wrap; }
 
 
 
 
 
 
47
  .tab-button {
48
- padding: 10px 20px; cursor: pointer; background-color: var(--table-hover);
49
- border: 1px solid var(--border-color); border-bottom: none; border-radius: 5px 5px 0 0;
50
- margin-right: 5px; font-size: 1em; color: var(--text-color);
 
 
 
 
 
 
51
  }
52
- .tab-button.active {
53
- background-color: var(--container-bg); border-bottom: 2px solid var(--container-bg);
54
- margin-bottom: -2px; color: var(--primary-color); font-weight: bold;
 
 
 
 
 
 
 
 
55
  }
56
- .tab-content { display: none; }
57
 
58
  /* 表格與按鈕 */
59
- .controls-container {
60
- display: flex; justify-content: space-between; align-items: center;
61
- margin-bottom: 20px; flex-wrap: wrap; gap: 15px; position: sticky; top: 0; z-index: 100;
62
- background-color: var(--container-bg); padding: 15px 0; border-bottom: 1px solid var(--border-color);
63
- }
64
- #filter-input, #exclude-input, #fund-select, #fund-full-select {
65
- padding: 10px; border: 1px solid var(--border-color); border-radius: 4px; font-size: 1em; background-color: var(--container-bg); color: var(--text-color);
66
- }
67
- #filter-input, #exclude-input { flex-grow: 1; min-width: 200px; }
68
- .action-button { padding: 10px 20px; font-size: 1em; color: white; border: none; border-radius: 4px; cursor: pointer; }
69
- #search-btn { background-color: var(--primary-color); }
70
- #export-btn { background-color: #28a745; }
71
-
72
- table { width: 100%; border-collapse: collapse; margin-top: 10px; table-layout: fixed; }
73
- th, td { border: 1px solid var(--border-color); padding: 12px; text-align: center; vertical-align: middle; word-wrap: break-word; }
74
- th { background-color: var(--primary-color); color: white; cursor: pointer; }
75
- tbody tr:nth-child(even) { background-color: var(--table-striped); }
76
- tbody tr:hover { background-color: var(--table-hover); }
77
-
78
- .loader { border: 5px solid #f3f3f3; border-top: 5px solid var(--primary-color); border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite; display: inline-block; vertical-align: middle; }
79
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
80
- #json-update-info { text-align: right; margin-bottom: 10px; color: #888; font-size: 0.9em; font-weight: bold; }
81
- mark { background-color: #fff3cd; color: #856404; padding: 0.2em; border-radius: 3px; font-weight: bold; }
82
- .status-badge { background-color: #dc3545; color: white; padding: 2px 6px; border-radius: 4px; font-size: 0.8em; margin-left: 8px; vertical-align: text-bottom; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  /* 儀表板 (Dashboard) 專屬樣式 */
85
- .kpi-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 30px; }
86
- .kpi-card {
87
- background-color: var(--table-striped); padding: 20px; border-radius: 8px;
88
- border-left: 5px solid var(--primary-color); box-shadow: 0 2px 5px rgba(0,0,0,0.05); text-align: center;
89
- }
90
- .kpi-title { font-size: 1.1em; color: #666; margin-bottom: 10px; }
91
- body.dark-mode .kpi-title { color: #aaa; }
92
- .kpi-value { font-size: 2.2em; font-weight: bold; color: var(--primary-color); }
93
-
94
- .charts-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(400px, 1fr)); gap: 30px; margin-bottom: 20px; }
95
- .chart-box { background-color: var(--table-striped); padding: 20px; border-radius: 8px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
96
- .chart-title { text-align: center; font-size: 1.2em; font-weight: bold; margin-bottom: 15px; color: var(--text-color); }
97
- .chart-container { position: relative; height: 300px; width: 100%; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
  /* 其他原有樣式保留 */
100
- .pagination { display: flex; justify-content: center; align-items: center; gap: 15px; margin-top: 20px; }
101
- .page-btn { padding: 8px 15px; background-color: var(--primary-color); color: white; border: none; border-radius: 4px; cursor: pointer; }
102
- .page-btn:disabled { background-color: #aaa; cursor: not-allowed; }
103
- #back-to-top { display: none; position: fixed; bottom: 30px; right: 30px; z-index: 99; font-size: 20px; background-color: var(--primary-color); color: white; cursor: pointer; padding: 12px 16px; border-radius: 50%; }
104
- .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); }
105
- .modal-content { background-color: var(--container-bg); margin: 10% auto; padding: 20px; width: 60%; border-radius: 8px; }
106
- .close-modal { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; }
107
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  @media (max-width: 768px) {
109
- table, thead, tbody, th, td, tr { display: block; }
110
- thead tr { display: none; }
111
- tr { margin-bottom: 15px; border: 1px solid var(--border-color); border-radius: 8px; padding: 10px; }
112
- td { text-align: left !important; border: none; border-bottom: 1px dotted var(--border-color); position: relative; padding-left: 35%; }
113
- td::before { content: attr(data-label); position: absolute; left: 10px; width: 30%; font-weight: bold; color: var(--primary-color); text-align: left; }
114
- .charts-grid { grid-template-columns: 1fr; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  }
116
  </style>
117
  </head>
 
118
  <body>
119
 
120
  <div class="settings-bar">
@@ -136,7 +516,7 @@
136
  <div id="json-update-info">
137
  <div class="loader" id="main-loader"></div> 資料載入中,請稍候... (首次載入需下載全國法規資料庫)
138
  </div>
139
-
140
  <div id="dashboard-content" style="display: none;">
141
  <div class="kpi-grid">
142
  <div class="kpi-card">
@@ -179,14 +559,45 @@
179
  <label for="fund-full-select" style="margin-right: 10px;">選擇基金名稱:</label>
180
  <select id="fund-full-select" style="flex-grow: 0; min-width: 300px;"></select>
181
  </div>
182
- <div id="full-article-law-info" style="display:none; background-color: var(--law-info-bg); padding:15px; margin-bottom:15px;"></div>
 
183
  <div id="full-article-info" style="text-align: center; margin-top: 20px;">請選擇一個基金名稱以顯示完整法條。</div>
184
  <table id="full-article-table" style="display:none;">
185
  <thead>
186
- <tr><th data-column="0">條次</th><th data-column="1">規定</th></tr>
 
 
 
187
  </thead>
188
  <tbody id="full-article-table-body"></tbody>
189
  </table>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  </div>
191
 
192
  <div id="tab2" class="tab-content">
@@ -201,8 +612,11 @@
201
  <table id="analyzed-table">
202
  <thead>
203
  <tr>
204
- <th data-column="0">基金名稱</th><th data-column="1">規定名稱</th>
205
- <th data-column="2">最近發布日期</th><th data-column="3">條次</th><th data-column="4">規定</th>
 
 
 
206
  </tr>
207
  </thead>
208
  <tbody id="analyzed-table-body"></tbody>
@@ -215,17 +629,22 @@
215
  </div>
216
  </div>
217
 
218
- <div id="reasonModal" class="modal"><div class="modal-content"><span class="close-modal" onclick="closeModal()">&times;</span><h2 id="modal-title"></h2><div id="modal-text"></div></div></div>
 
 
 
 
 
219
  <button id="back-to-top" onclick="scrollToTop()">▲</button>
220
 
221
  <script>
222
  // --- 核心變數 ---
223
  let globalAnalyzedData = [];
224
- let currentFilteredData = [];
225
  let currentPage = 1;
226
- const pageSize = 50;
227
  let ui;
228
-
229
  // Chart.js 實例追蹤 (避免重複渲染時破圖)
230
  let chartInstances = {};
231
 
@@ -239,16 +658,16 @@
239
  document.body.classList.toggle('dark-mode');
240
  localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
241
  // 切換深色模式時,重新繪製圖表以更新字體顏色
242
- if(globalAnalyzedData.length > 0 && document.getElementById('tab-dashboard').style.display === 'block') {
243
- renderDashboard();
244
  }
245
  }
246
- if(localStorage.getItem('darkMode') === 'true') document.body.classList.add('dark-mode');
247
 
248
- window.onscroll = function() {
249
  document.getElementById("back-to-top").style.display = (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) ? "block" : "none";
250
  };
251
- function scrollToTop() { window.scrollTo({top: 0, behavior: 'smooth'}); }
252
 
253
  // --- 儀表板與數據視覺化邏輯 ---
254
  function renderDashboard() {
@@ -260,7 +679,7 @@
260
  // 由於法條是「逐條」存放在陣列裡,我們需要用 Set 來篩選出不重複的基金名稱。
261
  const allFunds = {};
262
  globalAnalyzedData.forEach(item => {
263
- if(!allFunds[item.基金名稱]) {
264
  allFunds[item.基金名稱] = item.法規狀態; // 記錄每個基金的狀態
265
  }
266
  });
@@ -268,8 +687,8 @@
268
  let activeCount = 0; let abolishedCount = 0;
269
  const uniqueFundNames = Object.keys(allFunds);
270
  uniqueFundNames.forEach(name => {
271
- if(allFunds[name] === '現行法規') activeCount++;
272
- else if(allFunds[name] === '廢止法規') abolishedCount++;
273
  });
274
 
275
  document.getElementById('kpi-total-funds').innerText = uniqueFundNames.length;
@@ -285,12 +704,12 @@
285
  const authorityCount = {};
286
  globalAnalyzedData.filter(i => i.法規狀態 === '現行法規').forEach(item => {
287
  // 為了避免一檔多條重複計算,我們用之前提取的邏輯,但這裡簡化:如果該基金已被計入,就跳過
288
- if(!authorityCount[item.基金名稱]) {
289
  // 擷取大部會名稱,例如「行政院 > 經濟部」取「經濟部」
290
  let auth = item.主管機關 || '其他';
291
  let mainAuth = auth.includes('>') ? auth.split('>')[1].trim() : auth.split('>')[0].trim();
292
- if(mainAuth === '') mainAuth = '未分類';
293
-
294
  authorityCount[item.基金名稱] = mainAuth;
295
  }
296
  });
@@ -299,9 +718,9 @@
299
  Object.values(authorityCount).forEach(auth => {
300
  aggregatedAuth[auth] = (aggregatedAuth[auth] || 0) + 1;
301
  });
302
-
303
  // 排序並繪製圓餅圖
304
- const sortedAuthKeys = Object.keys(aggregatedAuth).sort((a,b) => aggregatedAuth[b] - aggregatedAuth[a]);
305
  drawChart('authorityChart', 'pie', sortedAuthKeys, sortedAuthKeys.map(k => aggregatedAuth[k]), chartTextColor);
306
 
307
  // 3. 基金複雜度排行 Top 10 (條文數 - 現行法規)
@@ -317,7 +736,7 @@
317
  // 通用圖表繪製函式
318
  function drawChart(canvasId, type, labels, data, textColor) {
319
  const ctx = document.getElementById(canvasId).getContext('2d');
320
-
321
  // 如果該圖表已經存在,先銷毀它,避免游標懸停時出現舊資料殘影
322
  if (chartInstances[canvasId]) {
323
  chartInstances[canvasId].destroy();
@@ -365,10 +784,10 @@
365
  fundNames.forEach(name => {
366
  const isAbolished = globalAnalyzedData.find(i => i.基金名稱 === name).法規狀態 === '廢止法規';
367
  const text = isAbolished ? `(廢) ${name}` : name;
368
-
369
  let opt1 = new Option(text, name); let opt2 = new Option(text, name);
370
  if (isAbolished) { opt1.style.color = '#888'; opt2.style.color = '#888'; }
371
-
372
  ui.fundSelect.add(opt1); ui.fundFullSelect.add(opt2);
373
  });
374
  }
@@ -377,18 +796,18 @@
377
  function applyAnalyzedFilters() {
378
  let filtered = globalAnalyzedData;
379
  if (ui.fundSelect.value) filtered = filtered.filter(i => i.基金名稱 === ui.fundSelect.value);
380
-
381
  const q = ui.filterInput.value.trim().toLowerCase();
382
  if (q) {
383
  const terms = q.split(/\s+or\s+/i);
384
  filtered = filtered.filter(item => {
385
  const text = Object.values(item).join(' ').toLowerCase();
386
- return terms.some(t => t.replace(/\s+and\s+/ig, ' ').split(/\s+/).filter(k=>k).every(k => text.includes(k)));
387
  });
388
  }
389
  const ex = ui.excludeInput.value.trim().toLowerCase();
390
  if (ex) {
391
- const exWords = ex.split(/\s+/).filter(k=>k);
392
  filtered = filtered.filter(item => {
393
  const text = Object.values(item).join(' ').toLowerCase();
394
  return exWords.every(w => !text.includes(w));
@@ -414,7 +833,7 @@
414
 
415
  function changePage(d) {
416
  currentPage = Math.max(1, Math.min(Math.ceil(currentFilteredData.length / pageSize), currentPage + d));
417
- renderPaginatedTable(); window.scrollTo({top: 0, behavior: 'smooth'});
418
  }
419
 
420
  // 表格渲染
@@ -423,7 +842,7 @@
423
  const isTab3 = tbody.id === 'full-article-table-body';
424
  const headers = isTab3 ? ["條次", "規定"] : ["基金名稱", "規定名稱", "最近發布日期", "條次", "規定"];
425
  const keyword = document.getElementById('filter-input').value.trim();
426
-
427
  data.forEach(item => {
428
  const tr = document.createElement('tr');
429
  headers.forEach(h => {
@@ -431,11 +850,11 @@
431
  let text = item[h] || '';
432
  if (h === '規定') {
433
  let html = text.replace(/([:。])/g, '$1\n').trim().replace(/(第\s*\d+(\-\d+)?\s*條)/g, '<span style="color:var(--primary-color); font-weight:bold;">$1</span>');
434
- if(keyword && !isTab3) try { html = html.replace(new RegExp(`(${keyword})`, 'gi'), '<mark>$1</mark>'); } catch(e){}
435
  td.innerHTML = `<div style="text-align:left; white-space:pre-wrap;">${html}</div>`;
436
  } else {
437
- td.innerText = text; td.style.textAlign = (h==='基金名稱' || h==='規定名稱') ? 'left' : 'center';
438
- if(h==='基金名稱' && item.法規狀態 === '廢止法規') td.innerHTML += ' <span class="status-badge">已廢止</span>';
439
  }
440
  tr.appendChild(td);
441
  });
@@ -447,15 +866,88 @@
447
  const fund = ui.fundFullSelect.value;
448
  ui.fullArticleTableBody.innerHTML = '';
449
  const info = document.getElementById('full-article-law-info'); info.style.display = 'none';
450
- if (!fund) { document.getElementById('full-article-table').style.display='none'; return; }
451
-
452
  const arts = globalAnalyzedData.filter(i => i.基金名稱 === fund);
453
- if(arts.length > 0) {
454
  info.innerHTML = `<h3 style="color:var(--primary-color); margin:0 0 10px 0;">${arts[0].規定名稱}</h3><p>發布日期: ${arts[0].最近發布日期}</p><p>沿革: ${arts[0].法規沿革}</p>`;
455
  info.style.display = 'block';
456
- arts.sort((a,b) => (a.條次.match(/\d+/)?.[0]||0) - (b.條次.match(/\d+/)?.[0]||0));
457
  renderTable(ui.fullArticleTableBody, arts);
458
  document.getElementById('full-article-table').style.display = 'table';
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  }
460
  }
461
 
@@ -464,8 +956,8 @@
464
  document.querySelectorAll('.tab-content').forEach(t => t.style.display = 'none');
465
  document.querySelectorAll('.tab-button').forEach(b => b.classList.remove('active'));
466
  document.getElementById(tabId).style.display = 'block';
467
- if(evt) evt.currentTarget.classList.add('active');
468
-
469
  if (tabId === 'tab-dashboard') renderDashboard(); // 切換到儀表板時繪圖
470
  if (tabId === 'tab2') { applyAnalyzedFilters(); }
471
  if (tabId === 'tab3') { displayFullArticles(); }
@@ -504,4 +996,5 @@
504
  });
505
  </script>
506
  </body>
 
507
  </html>
 
1
  <!DOCTYPE html>
2
  <html lang="zh-Hant-TW">
3
+
4
  <head>
5
  <meta charset="UTF-8">
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
7
  <title>中央政府特種基金AI智能分析平台-收支保管及運用辦法行動小法典</title>
8
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
9
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
10
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
11
  <style>
12
  /* 基礎變數與深色模式 */
13
  :root {
14
+ --bg-color: #f4f7f6;
15
+ --text-color: #333;
16
+ --container-bg: #fff;
17
+ --primary-color: #0056b3;
18
+ --primary-hover: #004494;
19
+ --border-color: #ddd;
20
+ --table-striped: #f9f9f9;
21
+ --table-hover: #f1f1f1;
22
+ --law-info-bg: #e7f3fe;
23
+ --font-size-base: 16px;
24
  }
25
+
26
  body.dark-mode {
27
+ --bg-color: #121212;
28
+ --text-color: #e0e0e0;
29
+ --container-bg: #1e1e1e;
30
+ --primary-color: #4da3ff;
31
+ --primary-hover: #1a8cff;
32
+ --border-color: #444;
33
+ --table-striped: #2a2a2a;
34
+ --table-hover: #333;
35
  --law-info-bg: #2c3e50;
36
  }
37
+
38
  body {
39
  font-family: 'Segoe UI', 'Microsoft JhengHei', Arial, sans-serif;
40
+ margin: 0;
41
+ padding: 20px;
42
+ background-color: var(--bg-color);
43
+ color: var(--text-color);
44
+ font-size: var(--font-size-base);
45
  transition: background-color 0.3s, color 0.3s;
46
  }
47
+
48
  .container {
49
+ max-width: 1800px;
50
+ margin: 0 auto;
51
+ background-color: var(--container-bg);
52
+ padding: 30px;
53
+ border-radius: 8px;
54
+ box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
55
  transition: background-color 0.3s;
56
  }
57
 
58
  /* 頂部設定列 */
59
+ .settings-bar {
60
+ display: flex;
61
+ justify-content: flex-end;
62
+ gap: 10px;
63
+ margin-bottom: 10px;
64
+ }
65
+
66
  .setting-btn {
67
+ background-color: var(--border-color);
68
+ color: var(--text-color);
69
+ border: none;
70
+ padding: 6px 12px;
71
+ border-radius: 4px;
72
+ cursor: pointer;
73
+ font-weight: bold;
74
+ }
75
+
76
+ .setting-btn:hover {
77
+ background-color: #ccc;
78
+ }
79
+
80
+ body.dark-mode .setting-btn:hover {
81
+ background-color: #555;
82
  }
83
+
84
+ h1 {
85
+ text-align: center;
86
+ color: var(--primary-color);
87
+ margin-bottom: 20px;
88
+ }
89
+
90
  /* 標籤頁 (Tabs) */
91
+ .tab-buttons {
92
+ display: flex;
93
+ border-bottom: 2px solid var(--border-color);
94
+ margin-bottom: 20px;
95
+ flex-wrap: wrap;
96
+ }
97
+
98
  .tab-button {
99
+ padding: 10px 20px;
100
+ cursor: pointer;
101
+ background-color: var(--table-hover);
102
+ border: 1px solid var(--border-color);
103
+ border-bottom: none;
104
+ border-radius: 5px 5px 0 0;
105
+ margin-right: 5px;
106
+ font-size: 1em;
107
+ color: var(--text-color);
108
  }
109
+
110
+ .tab-button.active {
111
+ background-color: var(--container-bg);
112
+ border-bottom: 2px solid var(--container-bg);
113
+ margin-bottom: -2px;
114
+ color: var(--primary-color);
115
+ font-weight: bold;
116
+ }
117
+
118
+ .tab-content {
119
+ display: none;
120
  }
 
121
 
122
  /* 表格與按鈕 */
123
+ .controls-container {
124
+ display: flex;
125
+ justify-content: space-between;
126
+ align-items: center;
127
+ margin-bottom: 20px;
128
+ flex-wrap: wrap;
129
+ gap: 15px;
130
+ position: sticky;
131
+ top: 0;
132
+ z-index: 100;
133
+ background-color: var(--container-bg);
134
+ padding: 15px 0;
135
+ border-bottom: 1px solid var(--border-color);
136
+ }
137
+
138
+ #filter-input,
139
+ #exclude-input,
140
+ #fund-select,
141
+ #fund-full-select {
142
+ padding: 10px;
143
+ border: 1px solid var(--border-color);
144
+ border-radius: 4px;
145
+ font-size: 1em;
146
+ background-color: var(--container-bg);
147
+ color: var(--text-color);
148
+ }
149
+
150
+ #filter-input,
151
+ #exclude-input {
152
+ flex-grow: 1;
153
+ min-width: 200px;
154
+ }
155
+
156
+ .action-button {
157
+ padding: 10px 20px;
158
+ font-size: 1em;
159
+ color: white;
160
+ border: none;
161
+ border-radius: 4px;
162
+ cursor: pointer;
163
+ }
164
+
165
+ #search-btn {
166
+ background-color: var(--primary-color);
167
+ }
168
+
169
+ #export-btn {
170
+ background-color: #28a745;
171
+ }
172
+
173
+ table {
174
+ width: 100%;
175
+ border-collapse: collapse;
176
+ margin-top: 10px;
177
+ table-layout: fixed;
178
+ }
179
+
180
+ th,
181
+ td {
182
+ border: 1px solid var(--border-color);
183
+ padding: 12px;
184
+ text-align: center;
185
+ vertical-align: middle;
186
+ word-wrap: break-word;
187
+ }
188
+
189
+ th {
190
+ background-color: var(--primary-color);
191
+ color: white;
192
+ cursor: pointer;
193
+ }
194
+
195
+ tbody tr:nth-child(even) {
196
+ background-color: var(--table-striped);
197
+ }
198
+
199
+ tbody tr:hover {
200
+ background-color: var(--table-hover);
201
+ }
202
+
203
+ .loader {
204
+ border: 5px solid #f3f3f3;
205
+ border-top: 5px solid var(--primary-color);
206
+ border-radius: 50%;
207
+ width: 30px;
208
+ height: 30px;
209
+ animation: spin 2s linear infinite;
210
+ display: inline-block;
211
+ vertical-align: middle;
212
+ }
213
+
214
+ @keyframes spin {
215
+ 0% {
216
+ transform: rotate(0deg);
217
+ }
218
+
219
+ 100% {
220
+ transform: rotate(360deg);
221
+ }
222
+ }
223
+
224
+ #json-update-info {
225
+ text-align: right;
226
+ margin-bottom: 10px;
227
+ color: #888;
228
+ font-size: 0.9em;
229
+ font-weight: bold;
230
+ }
231
+
232
+ mark {
233
+ background-color: #fff3cd;
234
+ color: #856404;
235
+ padding: 0.2em;
236
+ border-radius: 3px;
237
+ font-weight: bold;
238
+ }
239
+
240
+ .status-badge {
241
+ background-color: #dc3545;
242
+ color: white;
243
+ padding: 2px 6px;
244
+ border-radius: 4px;
245
+ font-size: 0.8em;
246
+ margin-left: 8px;
247
+ vertical-align: text-bottom;
248
+ }
249
 
250
  /* 儀表板 (Dashboard) 專屬樣式 */
251
+ .kpi-grid {
252
+ display: grid;
253
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
254
+ gap: 15px;
255
+ margin-bottom: 30px;
256
+ }
257
+
258
+ .kpi-card {
259
+ background-color: var(--table-striped);
260
+ padding: 20px;
261
+ border-radius: 8px;
262
+ border-left: 5px solid var(--primary-color);
263
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
264
+ text-align: center;
265
+ }
266
+
267
+ .kpi-title {
268
+ font-size: 1.1em;
269
+ color: #666;
270
+ margin-bottom: 10px;
271
+ }
272
+
273
+ body.dark-mode .kpi-title {
274
+ color: #aaa;
275
+ }
276
+
277
+ .kpi-value {
278
+ font-size: 2.2em;
279
+ font-weight: bold;
280
+ color: var(--primary-color);
281
+ }
282
+
283
+ .charts-grid {
284
+ display: grid;
285
+ grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
286
+ gap: 30px;
287
+ margin-bottom: 20px;
288
+ }
289
+
290
+ .chart-box {
291
+ background-color: var(--table-striped);
292
+ padding: 20px;
293
+ border-radius: 8px;
294
+ box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
295
+ }
296
+
297
+ .chart-title {
298
+ text-align: center;
299
+ font-size: 1.2em;
300
+ font-weight: bold;
301
+ margin-bottom: 15px;
302
+ color: var(--text-color);
303
+ }
304
+
305
+ .chart-container {
306
+ position: relative;
307
+ height: 300px;
308
+ width: 100%;
309
+ }
310
 
311
  /* 其他原有樣式保留 */
312
+ .pagination {
313
+ display: flex;
314
+ justify-content: center;
315
+ align-items: center;
316
+ gap: 15px;
317
+ margin-top: 20px;
318
+ }
319
+
320
+ .page-btn {
321
+ padding: 8px 15px;
322
+ background-color: var(--primary-color);
323
+ color: white;
324
+ border: none;
325
+ border-radius: 4px;
326
+ cursor: pointer;
327
+ }
328
+
329
+ .page-btn:disabled {
330
+ background-color: #aaa;
331
+ cursor: not-allowed;
332
+ }
333
+
334
+ #back-to-top {
335
+ display: none;
336
+ position: fixed;
337
+ bottom: 30px;
338
+ right: 30px;
339
+ z-index: 99;
340
+ font-size: 20px;
341
+ background-color: var(--primary-color);
342
+ color: white;
343
+ cursor: pointer;
344
+ padding: 12px 16px;
345
+ border-radius: 50%;
346
+ }
347
+
348
+ .modal {
349
+ display: none;
350
+ position: fixed;
351
+ z-index: 1000;
352
+ left: 0;
353
+ top: 0;
354
+ width: 100%;
355
+ height: 100%;
356
+ background-color: rgba(0, 0, 0, 0.6);
357
+ }
358
+
359
+ .modal-content {
360
+ background-color: var(--container-bg);
361
+ margin: 10% auto;
362
+ padding: 20px;
363
+ width: 60%;
364
+ border-radius: 8px;
365
+ }
366
+
367
+ .close-modal {
368
+ color: #aaa;
369
+ float: right;
370
+ font-size: 28px;
371
+ font-weight: bold;
372
+ cursor: pointer;
373
+ }
374
+
375
+ /* AI 分析區塊樣式 */
376
+ .ai-panel {
377
+ background-color: var(--law-info-bg);
378
+ border: 1px solid var(--border-color);
379
+ border-radius: 8px;
380
+ padding: 20px;
381
+ margin-top: 20px;
382
+ margin-bottom: 20px;
383
+ }
384
+
385
+ .ai-panel h3 {
386
+ margin-top: 0;
387
+ color: var(--primary-color);
388
+ }
389
+
390
+ .ai-controls {
391
+ display: flex;
392
+ flex-wrap: wrap;
393
+ gap: 15px;
394
+ margin-bottom: 15px;
395
+ }
396
+
397
+ .ai-controls select,
398
+ .ai-controls input,
399
+ .ai-controls textarea {
400
+ padding: 10px;
401
+ border: 1px solid var(--border-color);
402
+ border-radius: 4px;
403
+ font-size: 1em;
404
+ background-color: var(--container-bg);
405
+ color: var(--text-color);
406
+ }
407
+
408
+ .ai-controls textarea {
409
+ width: 100%;
410
+ min-height: 80px;
411
+ resize: vertical;
412
+ }
413
+
414
+ .ai-btn {
415
+ background-color: #8a2be2;
416
+ color: white;
417
+ padding: 10px 20px;
418
+ border: none;
419
+ border-radius: 4px;
420
+ cursor: pointer;
421
+ font-size: 1em;
422
+ }
423
+
424
+ .ai-btn:hover {
425
+ background-color: #7a22cc;
426
+ }
427
+
428
+ .ai-btn:disabled {
429
+ background-color: #ccc;
430
+ cursor: not-allowed;
431
+ }
432
+
433
+ .ai-result {
434
+ margin-top: 15px;
435
+ padding: 15px;
436
+ background-color: var(--container-bg);
437
+ border: 1px solid var(--border-color);
438
+ border-radius: 4px;
439
+ display: none;
440
+ }
441
+
442
+ .ai-result.loading {
443
+ text-align: center;
444
+ color: var(--text-color);
445
+ }
446
+
447
+ .ai-result-content {
448
+ line-height: 1.6;
449
+ }
450
+
451
  @media (max-width: 768px) {
452
+
453
+ table,
454
+ thead,
455
+ tbody,
456
+ th,
457
+ td,
458
+ tr {
459
+ display: block;
460
+ }
461
+
462
+ thead tr {
463
+ display: none;
464
+ }
465
+
466
+ tr {
467
+ margin-bottom: 15px;
468
+ border: 1px solid var(--border-color);
469
+ border-radius: 8px;
470
+ padding: 10px;
471
+ }
472
+
473
+ td {
474
+ text-align: left !important;
475
+ border: none;
476
+ border-bottom: 1px dotted var(--border-color);
477
+ position: relative;
478
+ padding-left: 35%;
479
+ }
480
+
481
+ td::before {
482
+ content: attr(data-label);
483
+ position: absolute;
484
+ left: 10px;
485
+ width: 30%;
486
+ font-weight: bold;
487
+ color: var(--primary-color);
488
+ text-align: left;
489
+ }
490
+
491
+ .charts-grid {
492
+ grid-template-columns: 1fr;
493
+ }
494
  }
495
  </style>
496
  </head>
497
+
498
  <body>
499
 
500
  <div class="settings-bar">
 
516
  <div id="json-update-info">
517
  <div class="loader" id="main-loader"></div> 資料載入中,請稍候... (首次載入需下載全國法規資料庫)
518
  </div>
519
+
520
  <div id="dashboard-content" style="display: none;">
521
  <div class="kpi-grid">
522
  <div class="kpi-card">
 
559
  <label for="fund-full-select" style="margin-right: 10px;">選擇基金名稱:</label>
560
  <select id="fund-full-select" style="flex-grow: 0; min-width: 300px;"></select>
561
  </div>
562
+ <div id="full-article-law-info"
563
+ style="display:none; background-color: var(--law-info-bg); padding:15px; margin-bottom:15px;"></div>
564
  <div id="full-article-info" style="text-align: center; margin-top: 20px;">請選擇一個基金名稱以顯示完整法條。</div>
565
  <table id="full-article-table" style="display:none;">
566
  <thead>
567
+ <tr>
568
+ <th data-column="0">條次</th>
569
+ <th data-column="1">規定</th>
570
+ </tr>
571
  </thead>
572
  <tbody id="full-article-table-body"></tbody>
573
  </table>
574
+
575
+ <!-- AI 分析區塊 -->
576
+ <div id="ai-analysis-panel" class="ai-panel" style="display:none;">
577
+ <h3>🤖 AI 智能分析 (目前基金)</h3>
578
+ <p style="color: #d9534f; font-size: 0.9em; margin-bottom: 15px;">⚠️ <strong>注意:</strong> AI
579
+ 生成的回答僅供參考,不代表正式法律意見或解釋。分析結果受限於使用者所選擇之模型能力,請自行判斷其正確性。</p>
580
+ <div class="ai-controls">
581
+ <select id="ai-model-provider" onchange="updateModelOptions()">
582
+ <option value="gemini">Google Gemini</option>
583
+ <option value="openai">OpenAI</option>
584
+ </select>
585
+ <select id="ai-model-name">
586
+ <option value="gemini-1.5-pro">Gemini 1.5 Pro</option>
587
+ <option value="gemini-1.5-flash">Gemini 1.5 Flash</option>
588
+ </select>
589
+ <input type="password" id="ai-api-key" placeholder="輸入 API Key..." style="flex-grow: 1;">
590
+ </div>
591
+ <div class="ai-controls">
592
+ <textarea id="ai-prompt" placeholder="輸入您想對此基金法條詢問的問題,例如:這檔基金的資金來源有哪些?"></textarea>
593
+ </div>
594
+ <button id="ai-submit-btn" class="ai-btn" onclick="analyzeContext()">開始 AI 分析</button>
595
+
596
+ <div id="ai-result-box" class="ai-result">
597
+ <div id="ai-result-content" class="ai-result-content"></div>
598
+ </div>
599
+ </div>
600
+
601
  </div>
602
 
603
  <div id="tab2" class="tab-content">
 
612
  <table id="analyzed-table">
613
  <thead>
614
  <tr>
615
+ <th data-column="0">基金名稱</th>
616
+ <th data-column="1">規定名稱</th>
617
+ <th data-column="2">最近發布日期</th>
618
+ <th data-column="3">條次</th>
619
+ <th data-column="4">規定</th>
620
  </tr>
621
  </thead>
622
  <tbody id="analyzed-table-body"></tbody>
 
629
  </div>
630
  </div>
631
 
632
+ <div id="reasonModal" class="modal">
633
+ <div class="modal-content"><span class="close-modal" onclick="closeModal()">&times;</span>
634
+ <h2 id="modal-title"></h2>
635
+ <div id="modal-text"></div>
636
+ </div>
637
+ </div>
638
  <button id="back-to-top" onclick="scrollToTop()">▲</button>
639
 
640
  <script>
641
  // --- 核心變數 ---
642
  let globalAnalyzedData = [];
643
+ let currentFilteredData = [];
644
  let currentPage = 1;
645
+ const pageSize = 50;
646
  let ui;
647
+
648
  // Chart.js 實例追蹤 (避免重複渲染時破圖)
649
  let chartInstances = {};
650
 
 
658
  document.body.classList.toggle('dark-mode');
659
  localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
660
  // 切換深色模式時,重新繪製圖表以更新字體顏色
661
+ if (globalAnalyzedData.length > 0 && document.getElementById('tab-dashboard').style.display === 'block') {
662
+ renderDashboard();
663
  }
664
  }
665
+ if (localStorage.getItem('darkMode') === 'true') document.body.classList.add('dark-mode');
666
 
667
+ window.onscroll = function () {
668
  document.getElementById("back-to-top").style.display = (document.body.scrollTop > 300 || document.documentElement.scrollTop > 300) ? "block" : "none";
669
  };
670
+ function scrollToTop() { window.scrollTo({ top: 0, behavior: 'smooth' }); }
671
 
672
  // --- 儀表板與數據視覺化邏輯 ---
673
  function renderDashboard() {
 
679
  // 由於法條是「逐條」存放在陣列裡,我們需要用 Set 來篩選出不重複的基金名稱。
680
  const allFunds = {};
681
  globalAnalyzedData.forEach(item => {
682
+ if (!allFunds[item.基金名稱]) {
683
  allFunds[item.基金名稱] = item.法規狀態; // 記錄每個基金的狀態
684
  }
685
  });
 
687
  let activeCount = 0; let abolishedCount = 0;
688
  const uniqueFundNames = Object.keys(allFunds);
689
  uniqueFundNames.forEach(name => {
690
+ if (allFunds[name] === '現行法規') activeCount++;
691
+ else if (allFunds[name] === '廢止法規') abolishedCount++;
692
  });
693
 
694
  document.getElementById('kpi-total-funds').innerText = uniqueFundNames.length;
 
704
  const authorityCount = {};
705
  globalAnalyzedData.filter(i => i.法規狀態 === '現行法規').forEach(item => {
706
  // 為了避免一檔多條重複計算,我們用之前提取的邏輯,但這裡簡化:如果該基金已被計入,就跳過
707
+ if (!authorityCount[item.基金名稱]) {
708
  // 擷取大部會名稱,例如「行政院 > 經濟部」取「經濟部」
709
  let auth = item.主管機關 || '其他';
710
  let mainAuth = auth.includes('>') ? auth.split('>')[1].trim() : auth.split('>')[0].trim();
711
+ if (mainAuth === '') mainAuth = '未分類';
712
+
713
  authorityCount[item.基金名稱] = mainAuth;
714
  }
715
  });
 
718
  Object.values(authorityCount).forEach(auth => {
719
  aggregatedAuth[auth] = (aggregatedAuth[auth] || 0) + 1;
720
  });
721
+
722
  // 排序並繪製圓餅圖
723
+ const sortedAuthKeys = Object.keys(aggregatedAuth).sort((a, b) => aggregatedAuth[b] - aggregatedAuth[a]);
724
  drawChart('authorityChart', 'pie', sortedAuthKeys, sortedAuthKeys.map(k => aggregatedAuth[k]), chartTextColor);
725
 
726
  // 3. 基金複雜度排行 Top 10 (條文數 - 現行法規)
 
736
  // 通用圖表繪製函式
737
  function drawChart(canvasId, type, labels, data, textColor) {
738
  const ctx = document.getElementById(canvasId).getContext('2d');
739
+
740
  // 如果該圖表已經存在,先銷毀它,避免游標懸停時出現舊資料殘影
741
  if (chartInstances[canvasId]) {
742
  chartInstances[canvasId].destroy();
 
784
  fundNames.forEach(name => {
785
  const isAbolished = globalAnalyzedData.find(i => i.基金名稱 === name).法規狀態 === '廢止法規';
786
  const text = isAbolished ? `(廢) ${name}` : name;
787
+
788
  let opt1 = new Option(text, name); let opt2 = new Option(text, name);
789
  if (isAbolished) { opt1.style.color = '#888'; opt2.style.color = '#888'; }
790
+
791
  ui.fundSelect.add(opt1); ui.fundFullSelect.add(opt2);
792
  });
793
  }
 
796
  function applyAnalyzedFilters() {
797
  let filtered = globalAnalyzedData;
798
  if (ui.fundSelect.value) filtered = filtered.filter(i => i.基金名稱 === ui.fundSelect.value);
799
+
800
  const q = ui.filterInput.value.trim().toLowerCase();
801
  if (q) {
802
  const terms = q.split(/\s+or\s+/i);
803
  filtered = filtered.filter(item => {
804
  const text = Object.values(item).join(' ').toLowerCase();
805
+ return terms.some(t => t.replace(/\s+and\s+/ig, ' ').split(/\s+/).filter(k => k).every(k => text.includes(k)));
806
  });
807
  }
808
  const ex = ui.excludeInput.value.trim().toLowerCase();
809
  if (ex) {
810
+ const exWords = ex.split(/\s+/).filter(k => k);
811
  filtered = filtered.filter(item => {
812
  const text = Object.values(item).join(' ').toLowerCase();
813
  return exWords.every(w => !text.includes(w));
 
833
 
834
  function changePage(d) {
835
  currentPage = Math.max(1, Math.min(Math.ceil(currentFilteredData.length / pageSize), currentPage + d));
836
+ renderPaginatedTable(); window.scrollTo({ top: 0, behavior: 'smooth' });
837
  }
838
 
839
  // 表格渲染
 
842
  const isTab3 = tbody.id === 'full-article-table-body';
843
  const headers = isTab3 ? ["條次", "規定"] : ["基金名稱", "規定名稱", "最近發布日期", "條次", "規定"];
844
  const keyword = document.getElementById('filter-input').value.trim();
845
+
846
  data.forEach(item => {
847
  const tr = document.createElement('tr');
848
  headers.forEach(h => {
 
850
  let text = item[h] || '';
851
  if (h === '規定') {
852
  let html = text.replace(/([:。])/g, '$1\n').trim().replace(/(第\s*\d+(\-\d+)?\s*條)/g, '<span style="color:var(--primary-color); font-weight:bold;">$1</span>');
853
+ if (keyword && !isTab3) try { html = html.replace(new RegExp(`(${keyword})`, 'gi'), '<mark>$1</mark>'); } catch (e) { }
854
  td.innerHTML = `<div style="text-align:left; white-space:pre-wrap;">${html}</div>`;
855
  } else {
856
+ td.innerText = text; td.style.textAlign = (h === '基金名稱' || h === '規定名稱') ? 'left' : 'center';
857
+ if (h === '基金名稱' && item.法規狀態 === '廢止法規') td.innerHTML += ' <span class="status-badge">已廢止</span>';
858
  }
859
  tr.appendChild(td);
860
  });
 
866
  const fund = ui.fundFullSelect.value;
867
  ui.fullArticleTableBody.innerHTML = '';
868
  const info = document.getElementById('full-article-law-info'); info.style.display = 'none';
869
+ if (!fund) { document.getElementById('full-article-table').style.display = 'none'; return; }
870
+
871
  const arts = globalAnalyzedData.filter(i => i.基金名稱 === fund);
872
+ if (arts.length > 0) {
873
  info.innerHTML = `<h3 style="color:var(--primary-color); margin:0 0 10px 0;">${arts[0].規定名稱}</h3><p>發布日期: ${arts[0].最近發布日期}</p><p>沿革: ${arts[0].法規沿革}</p>`;
874
  info.style.display = 'block';
875
+ arts.sort((a, b) => (a.條次.match(/\d+/)?.[0] || 0) - (b.條次.match(/\d+/)?.[0] || 0));
876
  renderTable(ui.fullArticleTableBody, arts);
877
  document.getElementById('full-article-table').style.display = 'table';
878
+ document.getElementById('ai-analysis-panel').style.display = 'block';
879
+
880
+ // 儲存當前背景知識
881
+ window.currentFundContext = arts.map(a => `${a.條次}: ${a.規定}`).join('\n');
882
+ } else {
883
+ document.getElementById('ai-analysis-panel').style.display = 'none';
884
+ window.currentFundContext = "";
885
+ }
886
+ }
887
+
888
+ // --- AI 分析功能 ---
889
+ function updateModelOptions() {
890
+ const provider = document.getElementById('ai-model-provider').value;
891
+ const modelSelect = document.getElementById('ai-model-name');
892
+ modelSelect.innerHTML = '';
893
+ if (provider === 'gemini') {
894
+ modelSelect.add(new Option('Gemini 1.5 Pro', 'gemini-1.5-pro'));
895
+ modelSelect.add(new Option('Gemini 1.5 Flash', 'gemini-1.5-flash'));
896
+ } else if (provider === 'openai') {
897
+ modelSelect.add(new Option('GPT-4o', 'gpt-4o'));
898
+ modelSelect.add(new Option('GPT-4o Mini', 'gpt-4o-mini'));
899
+ modelSelect.add(new Option('GPT-3.5 Turbo', 'gpt-3.5-turbo'));
900
+ }
901
+ }
902
+
903
+ async function analyzeContext() {
904
+ const apiKey = document.getElementById('ai-api-key').value.trim();
905
+ const prompt = document.getElementById('ai-prompt').value.trim();
906
+ const provider = document.getElementById('ai-model-provider').value;
907
+ const modelName = document.getElementById('ai-model-name').value;
908
+
909
+ if (!apiKey) return alert("請輸入 API Key!");
910
+ if (!prompt) return alert("請輸入想要詢問的問題!");
911
+ if (!window.currentFundContext) return alert("找不到基金背景知識!");
912
+
913
+ const btn = document.getElementById('ai-submit-btn');
914
+ const resultBox = document.getElementById('ai-result-box');
915
+ const resultContent = document.getElementById('ai-result-content');
916
+
917
+ btn.disabled = true;
918
+ btn.innerText = "分析中...";
919
+ resultBox.style.display = 'block';
920
+ resultBox.classList.add('loading');
921
+ resultContent.innerHTML = '<div class="loader" style="width:20px;height:20px;border-width:3px;"></div> 正在請求 AI 分析,請稍候...';
922
+
923
+ try {
924
+ const response = await fetch('/api/analyze', {
925
+ method: 'POST',
926
+ headers: { 'Content-Type': 'application/json' },
927
+ body: JSON.stringify({
928
+ model_provider: provider,
929
+ model_name: modelName,
930
+ api_key: apiKey,
931
+ prompt: prompt,
932
+ context: window.currentFundContext
933
+ })
934
+ });
935
+
936
+ const data = await response.json();
937
+ resultBox.classList.remove('loading');
938
+
939
+ if (!response.ok) {
940
+ resultContent.innerHTML = `<span style="color:red;">錯誤: ${data.detail || '未知錯誤'}</span>`;
941
+ } else {
942
+ // 使用 marked.js 來渲染 Markdown
943
+ resultContent.innerHTML = marked.parse(data.result);
944
+ }
945
+ } catch (e) {
946
+ resultBox.classList.remove('loading');
947
+ resultContent.innerHTML = `<span style="color:red;">連線發生錯誤: ${e.message}</span>`;
948
+ } finally {
949
+ btn.disabled = false;
950
+ btn.innerText = "開始 AI 分析";
951
  }
952
  }
953
 
 
956
  document.querySelectorAll('.tab-content').forEach(t => t.style.display = 'none');
957
  document.querySelectorAll('.tab-button').forEach(b => b.classList.remove('active'));
958
  document.getElementById(tabId).style.display = 'block';
959
+ if (evt) evt.currentTarget.classList.add('active');
960
+
961
  if (tabId === 'tab-dashboard') renderDashboard(); // 切換到儀表板時繪圖
962
  if (tabId === 'tab2') { applyAnalyzedFilters(); }
963
  if (tabId === 'tab3') { displayFullArticles(); }
 
996
  });
997
  </script>
998
  </body>
999
+
1000
  </html>
requirements.txt CHANGED
@@ -1,3 +1,7 @@
1
  fastapi
2
  uvicorn
3
- requests
 
 
 
 
 
1
  fastapi
2
  uvicorn
3
+ requests
4
+ httpx
5
+ pydantic
6
+ openai
7
+ google-genai