chioujye1007 commited on
Commit
f79e549
·
verified ·
1 Parent(s): 452b617

Upload 3 files

Browse files
Files changed (3) hide show
  1. README.md +225 -7
  2. app.py +829 -0
  3. requirements.txt +4 -0
README.md CHANGED
@@ -1,14 +1,232 @@
1
  ---
2
- title: Engineering Solver
3
- emoji: 📊
4
- colorFrom: pink
5
- colorTo: gray
6
  sdk: gradio
7
- sdk_version: 6.14.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
  license: mit
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: 工程解題助手
3
+ emoji: 📐
4
+ colorFrom: blue
5
+ colorTo: yellow
6
  sdk: gradio
7
+ sdk_version: 4.44.0
 
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
  ---
12
 
13
+ # 📐 工程解題助手 (Engineering Problem Solver)
14
+
15
+ 讓學生用手機拍照上傳題目,由 Google Gemini AI 視覺模型逐步推導並給出最終答案的免費教學工具。
16
+
17
+ 支援科目:**電路學、靜力學、動力學、工程數學、材料力學、熱力學**
18
+
19
+ ## ✨ 功能特色
20
+
21
+ - **拍照解題**:手機 / 電腦上傳題目圖片即可
22
+ - **多圖支援**:題目跨頁時可同時上傳多張圖
23
+ - **LaTeX 渲染**:數學式、矩陣、積分自動排版
24
+ - **對話模式**:學生可追問「為什麼這一步要用 KCL?」
25
+ - **六步驟解題法**:題目辨識 → 已知條件 → 分析方法 → 逐步推導 → 數值驗算 → 最終答案
26
+ - **匯出存檔**:HTML(含 LaTeX 渲染)/PDF 兩種格式
27
+
28
+ ---
29
+
30
+ ## 🚀 部署到 Hugging Face Spaces(推薦,完全免費)
31
+
32
+ ### 步驟 1:申請 Google Gemini API 金鑰
33
+
34
+ 1. 用您的 Google 帳號登入 [Google AI Studio](https://aistudio.google.com/apikey)
35
+ 2. 點擊 **「Create API key」**(如顯示「Get API key」也一樣)
36
+ 3. 複製產生的金鑰字串(格式類似 `AIzaSy...`),**妥善保存**
37
+ 4. 免費額度:每分鐘 15 次請求、每日約 1,500 次、約 100 萬 tokens/天
38
+
39
+ ### 步驟 2:建立 Hugging Face 帳號與 Space
40
+
41
+ 1. 到 [huggingface.co](https://huggingface.co/join) 註冊免費帳號
42
+ 2. 登入後點右上角頭像 → **New Space**
43
+ 3. 填寫資訊:
44
+ - **Space name**:`engineering-solver`(或您喜歡的名稱)
45
+ - **License**:MIT
46
+ - **SDK**:選擇 **Gradio**
47
+ - **Hardware**:**CPU basic - free**(免費)
48
+ - **Visibility**:Public(建議公開,供學生使用)
49
+ 4. 點 **Create Space**
50
+
51
+ ### 步驟 3:上傳檔案
52
+
53
+ **方法 A:網頁上傳(最簡單)**
54
+
55
+ 1. 進入新建的 Space 頁面,點上方 **「Files」** 分頁
56
+ 2. 點 **「Add file」→「Upload files」**
57
+ 3. 把整個「電路學解題器」資料夾中的這三個檔案拖進去:
58
+ - `app.py`
59
+ - `requirements.txt`
60
+ - `README.md`
61
+ 4. 在下方 commit 訊息填寫「Initial upload」,點 **Commit changes to main**
62
+
63
+ **方法 B:用 Git(適合熟悉者)**
64
+
65
+ ```bash
66
+ git clone https://huggingface.co/spaces/您的帳號/engineering-solver
67
+ cd engineering-solver
68
+ # 複製本資料夾的所有檔案進來
69
+ git add .
70
+ git commit -m "Initial upload"
71
+ git push
72
+ ```
73
+
74
+ ### 步驟 4:設定 API 金鑰(必要)
75
+
76
+ 1. 在 Space 頁面點右上角 ⚙️ **Settings**
77
+ 2. 往下找到 **Variables and secrets** 區塊
78
+ 3. 點 **New secret**,填寫:
79
+ - **Name**:`GEMINI_API_KEY`
80
+ - **Value**:貼上步驟 1 取得的金鑰
81
+ 4. 點 **Save**
82
+
83
+ **⚠️ 重要**:請使用 *secret* 而非 *variable*,前者會被加密儲存。
84
+
85
+ ### 步驟 5:等待自動部署
86
+
87
+ 1. 回到 Space 主頁,您會看到 **「Building」** 狀態
88
+ 2. 約 2–4 分鐘完成(首次部署較久,要安裝套件)
89
+ 3. 完成後狀態變為 **「Running」**,網頁右側會顯示應用介面
90
+
91
+ ### 步驟 6:取得網址分享給學生
92
+
93
+ 您的網址會是:
94
+ ```
95
+ https://huggingface.co/spaces/您的帳號/engineering-solver
96
+ ```
97
+
98
+ 點右上角的 **「⋮」** 選單 → **Embed this Space** 也可以取得 iframe 嵌入碼,可放到課程網站。
99
+
100
+ ---
101
+
102
+ ## 💻 本地測試(在自己電腦執行)
103
+
104
+ 開課前若想先測試效果,可在自己的電腦執行:
105
+
106
+ ```bash
107
+ # 1. 安裝 Python 套件
108
+ pip install -r requirements.txt
109
+
110
+ # 2. 設定 API 金鑰
111
+ # Windows (PowerShell)
112
+ $env:GEMINI_API_KEY="您的金鑰"
113
+
114
+ # macOS / Linux
115
+ export GEMINI_API_KEY="您的金鑰"
116
+
117
+ # 3. 啟動
118
+ python app.py
119
+ ```
120
+
121
+ 啟動後瀏覽器開啟 `http://localhost:7860`
122
+
123
+ ---
124
+
125
+ ## 🔧 客製化指南
126
+
127
+ ### 修改解題科目
128
+
129
+ 開啟 `app.py`,找到 `SUBJECT_PROMPTS` 字典(約第 60 行起):
130
+
131
+ ```python
132
+ SUBJECT_PROMPTS: Dict[str, str] = {
133
+ "新科目名稱 (English Name)": f"""你是一位專精於 ... 的大學教授,
134
+ 熟悉 ... 等主題。
135
+
136
+ {BASE_INSTRUCTIONS}
137
+
138
+ **特別注意事項**:
139
+ - ...
140
+ """,
141
+ # ... 其他科目
142
+ }
143
+ ```
144
+
145
+ 新增、修改、刪除皆可。建議保留 `{BASE_INSTRUCTIONS}` 以維持六步驟解題法的一致性。
146
+
147
+ ### 切換 Gemini 模型版本
148
+
149
+ 在 Space 的 Settings → Variables 新增環境變數 `GEMINI_MODEL`,可選值:
150
+
151
+ - `gemini-2.0-flash-exp`(預設,速度快、視覺強)
152
+ - `gemini-2.0-flash`(穩定版)
153
+ - `gemini-1.5-pro`(推理較強,但免費額度較少)
154
+ - `gemini-2.5-flash`(若已釋出)
155
+
156
+ ### 調整答題溫度(保守 ↔ 創意)
157
+
158
+ `app.py` 中 `generation_config` 的 `temperature` 值:
159
+
160
+ - `0.0–0.3`:保守、一致,適合公式題(**目前��設 0.2**)
161
+ - `0.5–0.7`:較有彈性,適合解題策略討論
162
+ - `0.8–1.0`:較有創意但可能出錯
163
+
164
+ ---
165
+
166
+ ## 🐛 常見問題
167
+
168
+ ### Q1:學生開啟網頁時顯示「Sleeping」?
169
+
170
+ A:Hugging Face 免費 Space 閒置 48 小時會休眠。學生開啟後會自動喚醒(約 30 秒)。
171
+ 若要避免,可在 Space Settings 啟用付費保活,或寫一個排程腳本每天 ping 一次。
172
+
173
+ ### Q2:跳出「API key 錯誤」?
174
+
175
+ A:請檢查 Settings → Secrets 中的 `GEMINI_API_KEY` 是否正確貼上(不要有多餘空白),
176
+ 並重新啟動 Space(Settings → Factory reboot)。
177
+
178
+ ### Q3:超過免費額度怎麼辦?
179
+
180
+ A:免費 Gemini API 已相當寬鬆(1,500 req/day),單一班級足夠使用。若不足:
181
+ - 申請多個 Google 帳號的 API 金鑰輪流使用
182
+ - 升級到 Google AI Studio 付費版(仍便宜,每百萬 tokens 約 $0.10 美元)
183
+
184
+ ### Q4:解題正確率不理想?
185
+
186
+ A:建議:
187
+ 1. 學生上傳的照片要清晰、光線足夠
188
+ 2. 在補充說明中明確告知題目要求(例:「求節點電壓 V1」)
189
+ 3. 升級到 `gemini-2.0-flash`(穩定版)或 `gemini-1.5-pro`
190
+ 4. 修改 `SUBJECT_PROMPTS` 加入更具體的領域知識
191
+
192
+ ### Q5:能否禁止學生考試時使用?
193
+
194
+ A:可在 Space Settings 將 Visibility 改為 Private,並在考試期間關閉 Space。
195
+ 或設定時段性的密碼保護(需要修改程式碼新增 `auth` 參數)。
196
+
197
+ ### Q6:如何同時讓多班學生使用?
198
+
199
+ A:免費版的 Space 支援併發。但若同時上線超過 20–30 人,建議:
200
+ - 升級 Space 到 CPU upgrade(每月 $0.03/hr,約 $20/月)
201
+ - 或部署多個 Space 分流不同班級
202
+
203
+ ---
204
+
205
+ ## 📊 解題正確率提升建議
206
+
207
+ LLM 解工程題並非 100% 正確,請務必教育學生「**將 AI 答案視為參考,而非標準答案**」。
208
+
209
+ 提升正確率的方法:
210
+
211
+ 1. **拍照品質**:題目要完整、清晰、無遮蔽
212
+ 2. **加註中文題意**:在文字框補充「這是 RLC 串聯電路的暫態題目」
213
+ 3. **要求驗算**:本工具已內建驗算步驟
214
+ 4. **多輪追問**:學生可追問「請重新檢查第 3 步」
215
+ 5. **建立題庫對照**:教師可預先測試常見題型並記錄正確率
216
+
217
+ ---
218
+
219
+ ## 📜 授權
220
+
221
+ MIT License — 可自由用於教學、修改與再散布。
222
+
223
+ ## 🙏 致謝
224
+
225
+ - 模型:[Google Gemini](https://ai.google.dev/)
226
+ - 介面:[Gradio](https://gradio.app/)
227
+ - 託管:[Hugging Face Spaces](https://huggingface.co/spaces)
228
+ - 數學排版:[MathJax](https://www.mathjax.org/)
229
+
230
+ ---
231
+
232
+ 如有問題或建議,歡迎透過 Hugging Face Space 的 Community 分頁回報。
app.py ADDED
@@ -0,0 +1,829 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 工程解題助手 (Engineering Problem Solver)
3
+ ============================================
4
+ 功能:學生拍照上傳電路學、靜力學、動力學等工程題目,
5
+ 由 Google Gemini 視覺模型逐步推導並給出最終答案。
6
+
7
+ 部署:Hugging Face Spaces(Gradio SDK)
8
+ 作者:成功大學 教學工具
9
+ """
10
+
11
+ import os
12
+ import io
13
+ import base64
14
+ import html as html_lib
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+ from typing import List, Tuple, Dict, Any, Optional
18
+
19
+ import gradio as gr
20
+ from PIL import Image
21
+ import google.generativeai as genai
22
+
23
+
24
+ # ============================================================
25
+ # 1. 基本設定
26
+ # ============================================================
27
+ API_KEY = os.environ.get("GEMINI_API_KEY", "").strip()
28
+ MODEL_NAME = os.environ.get("GEMINI_MODEL", "gemini-2.0-flash-exp")
29
+
30
+ if API_KEY:
31
+ genai.configure(api_key=API_KEY)
32
+ else:
33
+ print("⚠️ 警告:尚未設定 GEMINI_API_KEY 環境變數。")
34
+ print(" 請至 Hugging Face Space → Settings → Repository secrets 新增。")
35
+
36
+
37
+ # ============================================================
38
+ # 2. 系統提示詞(Prompt Engineering)
39
+ # 依科目給予不同領域知識與解題框架
40
+ # ============================================================
41
+ BASE_INSTRUCTIONS = """請依照下列「六步驟解題法」回答:
42
+
43
+ **步驟 1:題目辨識**
44
+ 仔細描述你在圖片中看到的內容(元件、數值、符號、座標、受力等),
45
+ 確認沒有看錯。若圖片不清楚或資訊不足,請明確指出需要哪些補充資訊。
46
+
47
+ **步驟 2:已知與待求**
48
+ 條列已知條件、待求量,並標註單位與符號。
49
+
50
+ **步驟 3:分析方法**
51
+ 選擇適當的分析方法並說明為何使用該方法。
52
+
53
+ **步驟 4:逐步推導**
54
+ 列出每一步驟的方程式與計算過程。
55
+ **所有數學式請使用 LaTeX 語法**:
56
+ - 行內公式:用 `$ ... $` 包起來,例如 $V = IR$
57
+ - 獨立公式:用 `$$ ... $$` 包起來,例如 $$\\sum_{i=1}^{n} I_i = 0$$
58
+ - 矩陣:使用 `\\begin{bmatrix} ... \\end{bmatrix}`
59
+ - 分數:使用 `\\frac{分子}{分母}`
60
+
61
+ **步驟 5:數值驗算**
62
+ 將最終答案代回原方程式驗證合理性。
63
+
64
+ **步驟 6:最終答案**
65
+ 用 **粗體** 標示最終答案,並加上單位。
66
+
67
+ ---
68
+ **回答規範**:
69
+ - 一律使用繁體中文
70
+ - 使用標準工程符號(SI 單位制)
71
+ - 結構清楚,使用 Markdown 標題(## 與 ###)
72
+ - 若有多個小題,分別解答
73
+ """
74
+
75
+ SUBJECT_PROMPTS: Dict[str, str] = {
76
+ "電路學 (Circuit Analysis)": f"""你是一位專精於電路學的大學教授,
77
+ 熟悉直流/交流電路、節點分析 (KCL)、網目分析 (KVL)、戴維寧/諾頓等效電路、
78
+ 重疊定理、相量分析、頻率響應、共振、運算放大器、二階電路暫態等主題。
79
+
80
+ {BASE_INSTRUCTIONS}
81
+
82
+ **電路學特別注意事項**:
83
+ - 明確標示電流方向與電壓極性
84
+ - 區分直流穩態 (DC steady state) 與暫態 (transient) 分析
85
+ - 交流電路請使用相量 (phasor) 並標註角頻率 $\\omega$
86
+ - 若涉及 RC/RL/RLC 電路暫態,列出時間常數 $\\tau$
87
+ """,
88
+
89
+ "靜力學 (Statics)": f"""你是一位專精於靜力學的大學教授,
90
+ 熟悉力與力矩、自由體圖 (FBD)、平衡方程、桁架分析 (節點法/截面法)、
91
+ 構架與機器、摩擦、重心與形心、慣性矩、虛功原理等主題。
92
+
93
+ {BASE_INSTRUCTIONS}
94
+
95
+ **靜力學特別注意事項**:
96
+ - **必須先畫(或文字描述)自由體圖**,標示所有作用力
97
+ - 明確列出力的平衡 $\\sum F_x = 0$、$\\sum F_y = 0$ 與力矩平衡 $\\sum M = 0$
98
+ - 標註座標系統與正負方向慣例
99
+ - 桁架分析請說明是用節點法 (Method of Joints) 還是截面法 (Method of Sections)
100
+ """,
101
+
102
+ "動力學 (Dynamics)": f"""你是一位專精於動力學的大學教授,
103
+ 熟悉質點運動學、剛體運動學、牛頓第二定律、功能定理、衝量-動量定理、
104
+ 角動量、振動學等主題。
105
+
106
+ {BASE_INSTRUCTIONS}
107
+
108
+ **動力學特別注意事項**:
109
+ - 區分運動學 (kinematics) 與動力學 (kinetics)
110
+ - 明確說明所選之參考座標系(直角、極座標、法向/切向)
111
+ - 涉及向量者,標註各分量方向
112
+ - 若使用功能定理或動量定理,說明為何此法較佳
113
+ """,
114
+
115
+ "工程數學 (Engineering Math)": f"""你是一位專精於工程數學的大學教授,
116
+ 熟悉微積分、向量微積分、線性代數、常微分方程、偏微分方程、
117
+ 複變函數、傅立葉級數/轉換、拉普拉斯轉換等主題。
118
+
119
+ {BASE_INSTRUCTIONS}
120
+
121
+ **工程數學特別注意事項**:
122
+ - 明確標註定義域、值域與邊界條件
123
+ - 矩陣運算請逐列展開
124
+ - 微分方程請註明階數與線性/非線性、齊次/非齊次
125
+ """,
126
+
127
+ "材料力學 (Mechanics of Materials)": f"""你是一位專精於材料力學的大學教授,
128
+ 熟悉應力/應變、軸力、扭轉、彎曲、剪力/彎矩圖、
129
+ 變形、樑的撓度、應力轉換 (Mohr 圓)、破壞準則等主題。
130
+
131
+ {BASE_INSTRUCTIONS}
132
+
133
+ **材料力學特別注意事項**:
134
+ - 區分正交應力 $\\sigma$ 與剪應力 $\\tau$
135
+ - 樑問題請繪製(描述)剪力圖 (V) 與彎矩圖 (M)
136
+ - 標註正負號慣例(拉為正、壓為負等)
137
+ """,
138
+
139
+ "熱力學 (Thermodynamics)": f"""你是一位專精於熱力學的大學教授,
140
+ 熟悉熱力學第一/第二定律、理想氣體、熱機循環 (Carnot、Otto、Rankine)、
141
+ 熵、焓、可用能 (exergy)、熱傳導等主題。
142
+
143
+ {BASE_INSTRUCTIONS}
144
+
145
+ **熱力學特別注意事項**:
146
+ - 明確定義系統 (開放/封閉/孤立) 與邊界
147
+ - 標註過程種類 (等溫、絕熱、等壓、多變過程)
148
+ - 引用必要的熱力學表 (如水蒸氣表) 數值時請註明
149
+ """,
150
+ }
151
+
152
+
153
+ # ============================================================
154
+ # 3. Gemini API 呼叫核心
155
+ # ============================================================
156
+ def _extract_path(content: Any) -> Optional[str]:
157
+ """從 Gradio messages 格式的 content 抽出檔案路徑(如果是檔案)。"""
158
+ if isinstance(content, dict) and "path" in content:
159
+ return content["path"]
160
+ if isinstance(content, (list, tuple)) and len(content) >= 1:
161
+ first = content[0]
162
+ if isinstance(first, str) and Path(first).exists():
163
+ return first
164
+ return None
165
+
166
+
167
+ def build_gemini_history(history: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
168
+ """
169
+ 將 Gradio messages 格式轉換為 Gemini chat history 格式。
170
+ Gradio content 可能是:str / dict{"path":...} / tuple(path,)
171
+ Gemini: [{"role": "user"/"model", "parts": [...]}]
172
+ """
173
+ gemini_history = []
174
+ for msg in history:
175
+ role = "user" if msg["role"] == "user" else "model"
176
+ content = msg["content"]
177
+ parts: List[Any] = []
178
+
179
+ path = _extract_path(content)
180
+ if path:
181
+ try:
182
+ parts.append(Image.open(path))
183
+ except Exception as e:
184
+ parts.append(f"[圖片載入失敗: {e}]")
185
+ elif isinstance(content, (list, tuple)):
186
+ for item in content:
187
+ if isinstance(item, str) and Path(item).exists():
188
+ try:
189
+ parts.append(Image.open(item))
190
+ except Exception:
191
+ parts.append(str(item))
192
+ else:
193
+ parts.append(str(item))
194
+ else:
195
+ text = str(content).strip()
196
+ if text:
197
+ parts.append(text)
198
+
199
+ if parts:
200
+ gemini_history.append({"role": role, "parts": parts})
201
+ return gemini_history
202
+
203
+
204
+ def stream_gemini_response(
205
+ user_message: Dict[str, Any],
206
+ history: List[Dict[str, Any]],
207
+ subject: str,
208
+ ):
209
+ """
210
+ 呼叫 Gemini API 並串流回傳結果。
211
+ user_message: {"text": str, "files": [paths]}
212
+ """
213
+ if not API_KEY:
214
+ yield "❌ **錯誤**:尚未設定 `GEMINI_API_KEY`。\n\n請至 Hugging Face Space 的 Settings → Repository secrets 新增此金鑰。\n\n申請金鑰:https://aistudio.google.com/apikey"
215
+ return
216
+
217
+ system_prompt = SUBJECT_PROMPTS.get(subject, BASE_INSTRUCTIONS)
218
+
219
+ try:
220
+ model = genai.GenerativeModel(
221
+ MODEL_NAME,
222
+ system_instruction=system_prompt,
223
+ generation_config={
224
+ "temperature": 0.2, # 低溫度提高解題正確性
225
+ "top_p": 0.95,
226
+ "max_output_tokens": 8192,
227
+ },
228
+ )
229
+ except Exception as e:
230
+ yield f"❌ 模型初始化失敗:{e}"
231
+ return
232
+
233
+ # 把過去的對話轉換為 Gemini 格式
234
+ gemini_history = build_gemini_history(history)
235
+ chat = model.start_chat(history=gemini_history)
236
+
237
+ # 組合本次訊息的多模態內容
238
+ parts: List[Any] = []
239
+ files = user_message.get("files", []) or []
240
+ for f in files:
241
+ try:
242
+ parts.append(Image.open(f))
243
+ except Exception as e:
244
+ yield f"❌ 圖片載入失敗:{e}"
245
+ return
246
+
247
+ text = (user_message.get("text") or "").strip()
248
+ if text:
249
+ parts.append(text)
250
+ elif files:
251
+ # 若只有圖片無文字,預設提示
252
+ parts.append("請依照六步驟解題法逐步分析這道題目。")
253
+ else:
254
+ yield "請上傳題目圖片或輸入文字描述。"
255
+ return
256
+
257
+ # 串流回傳
258
+ try:
259
+ response = chat.send_message(parts, stream=True)
260
+ full_text = ""
261
+ for chunk in response:
262
+ if chunk.text:
263
+ full_text += chunk.text
264
+ yield full_text
265
+ except Exception as e:
266
+ yield f"❌ Gemini API 呼叫失敗:{e}\n\n可能原因:\n- API 金鑰錯誤或額度用盡\n- 圖片過大或格式不支援\n- 網路連線問題"
267
+
268
+
269
+ # ============================================================
270
+ # 4. 匯出功能(HTML 與 PDF)
271
+ # ============================================================
272
+ def history_to_markdown(history: List[Dict[str, Any]], subject: str) -> str:
273
+ """把對話歷史轉成 Markdown 字串。"""
274
+ lines = [
275
+ f"# 解題紀錄 — {subject}",
276
+ f"",
277
+ f"產生時間:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
278
+ f"",
279
+ f"---",
280
+ f"",
281
+ ]
282
+ for msg in history:
283
+ role = msg["role"]
284
+ content = msg["content"]
285
+ if role == "user":
286
+ lines.append("## 🧑‍🎓 學生提問")
287
+ path = _extract_path(content)
288
+ if path:
289
+ lines.append(f"*[圖片:{Path(path).name}]*")
290
+ elif isinstance(content, (list, tuple)):
291
+ for item in content:
292
+ if isinstance(item, str) and Path(item).exists():
293
+ lines.append(f"*[圖片:{Path(item).name}]*")
294
+ else:
295
+ lines.append(str(item))
296
+ else:
297
+ lines.append(str(content))
298
+ else:
299
+ lines.append("## 🎓 教授解答")
300
+ lines.append(str(content))
301
+ lines.append("")
302
+ return "\n".join(lines)
303
+
304
+
305
+ HTML_TEMPLATE = """<!DOCTYPE html>
306
+ <html lang="zh-Hant">
307
+ <head>
308
+ <meta charset="UTF-8">
309
+ <title>{title}</title>
310
+ <script>
311
+ window.MathJax = {{
312
+ tex: {{
313
+ inlineMath: [['$', '$'], ['\\\\(', '\\\\)']],
314
+ displayMath: [['$$', '$$'], ['\\\\[', '\\\\]']],
315
+ processEscapes: true
316
+ }},
317
+ options: {{
318
+ skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre']
319
+ }}
320
+ }};
321
+ </script>
322
+ <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
323
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
324
+ <style>
325
+ body {{
326
+ font-family: "Noto Sans TC", "Microsoft JhengHei", Arial, sans-serif;
327
+ max-width: 880px;
328
+ margin: 2em auto;
329
+ padding: 0 1em;
330
+ line-height: 1.7;
331
+ color: #222;
332
+ }}
333
+ h1 {{ color: #1a4d8f; border-bottom: 3px solid #1a4d8f; padding-bottom: 0.3em; }}
334
+ h2 {{ color: #2a6db5; margin-top: 1.8em; }}
335
+ h3 {{ color: #444; }}
336
+ .user {{ background: #f0f7ff; border-left: 4px solid #2a6db5; padding: 0.8em 1.2em; margin: 1em 0; border-radius: 4px; }}
337
+ .assistant {{ background: #fdfbf3; border-left: 4px solid #c79a3a; padding: 0.8em 1.2em; margin: 1em 0; border-radius: 4px; }}
338
+ .meta {{ color: #888; font-size: 0.9em; }}
339
+ img {{ max-width: 100%; border: 1px solid #ddd; border-radius: 4px; margin: 0.5em 0; }}
340
+ pre {{ background: #f6f6f6; padding: 0.8em; border-radius: 4px; overflow-x: auto; }}
341
+ code {{ background: #f0f0f0; padding: 0.1em 0.4em; border-radius: 3px; }}
342
+ hr {{ border: 0; border-top: 1px dashed #ccc; margin: 2em 0; }}
343
+ .print-btn {{
344
+ position: fixed; top: 1em; right: 1em;
345
+ padding: 0.6em 1.2em; background: #1a4d8f; color: white;
346
+ border: none; border-radius: 4px; cursor: pointer; font-size: 1em;
347
+ }}
348
+ @media print {{ .print-btn {{ display: none; }} }}
349
+ </style>
350
+ </head>
351
+ <body>
352
+ <button class="print-btn" onclick="window.print()">🖨️ 列印或存為 PDF</button>
353
+ <h1>{title}</h1>
354
+ <p class="meta">產生時間:{timestamp} | 科目:{subject}</p>
355
+ <hr>
356
+ {body}
357
+ <hr>
358
+ <p class="meta">此份解答由 AI 輔助生成,僅供學習參考。請務必自行驗證每一步推導。</p>
359
+ <script>
360
+ // 把 .markdown 元素的內容用 marked 轉成 HTML,再讓 MathJax 處理
361
+ document.querySelectorAll('.markdown').forEach(el => {{
362
+ const raw = el.textContent;
363
+ el.innerHTML = marked.parse(raw);
364
+ }});
365
+ // 等 MathJax 載入後重新排版
366
+ window.addEventListener('load', () => {{
367
+ if (window.MathJax) MathJax.typesetPromise();
368
+ }});
369
+ </script>
370
+ </body>
371
+ </html>
372
+ """
373
+
374
+
375
+ def history_to_html(history: List[Dict[str, Any]], subject: str) -> str:
376
+ """產生帶 MathJax 渲染的獨立 HTML 檔(可在瀏覽器中列印為 PDF)。"""
377
+ body_parts = []
378
+ def _embed_image(path: str) -> str:
379
+ try:
380
+ with open(path, "rb") as f:
381
+ b64 = base64.b64encode(f.read()).decode()
382
+ ext = Path(path).suffix.lstrip(".").lower() or "png"
383
+ if ext == "jpg":
384
+ ext = "jpeg"
385
+ return f'<img src="data:image/{ext};base64,{b64}" alt="題目圖片">'
386
+ except Exception:
387
+ return f"<p>[圖片:{html_lib.escape(Path(path).name)}]</p>"
388
+
389
+ for msg in history:
390
+ role = msg["role"]
391
+ content = msg["content"]
392
+ cls = "user" if role == "user" else "assistant"
393
+ label = "🧑‍🎓 學生提問" if role == "user" else "🎓 教授解答"
394
+
395
+ path = _extract_path(content)
396
+ if path:
397
+ body_parts.append(
398
+ f'<div class="{cls}"><h3>{label}</h3>{_embed_image(path)}</div>'
399
+ )
400
+ elif isinstance(content, (list, tuple)):
401
+ inner_parts = [f"<h3>{label}</h3>"]
402
+ for item in content:
403
+ if isinstance(item, str) and Path(item).exists():
404
+ inner_parts.append(_embed_image(item))
405
+ else:
406
+ inner_parts.append(
407
+ f'<div class="markdown">{html_lib.escape(str(item))}</div>'
408
+ )
409
+ body_parts.append(f'<div class="{cls}">{"".join(inner_parts)}</div>')
410
+ else:
411
+ body_parts.append(
412
+ f'<div class="{cls}"><h3>{label}</h3>'
413
+ f'<div class="markdown">{html_lib.escape(str(content))}</div></div>'
414
+ )
415
+
416
+ return HTML_TEMPLATE.format(
417
+ title=f"解題紀錄 — {subject}",
418
+ timestamp=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
419
+ subject=html_lib.escape(subject),
420
+ body="\n".join(body_parts),
421
+ )
422
+
423
+
424
+ def export_html(history: List[Dict[str, Any]], subject: str) -> Optional[str]:
425
+ """匯出為 HTML 檔案(含 MathJax 渲染 LaTeX)。"""
426
+ if not history:
427
+ return None
428
+ html_text = history_to_html(history, subject)
429
+ out_dir = Path("/tmp") if Path("/tmp").exists() else Path(".")
430
+ filename = f"solution_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
431
+ out_path = out_dir / filename
432
+ out_path.write_text(html_text, encoding="utf-8")
433
+ return str(out_path)
434
+
435
+
436
+ def export_pdf(history: List[Dict[str, Any]], subject: str) -> Optional[str]:
437
+ """
438
+ 匯出為 PDF 檔案。
439
+ 使用 reportlab + CJK 字體;LaTeX 數學式以原文呈現。
440
+ 若需完美的 LaTeX 渲染,建議改用「下載 HTML → 在瀏覽器列印為 PDF」。
441
+ """
442
+ if not history:
443
+ return None
444
+ try:
445
+ from reportlab.lib.pagesizes import A4
446
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
447
+ from reportlab.lib.units import cm
448
+ from reportlab.lib.enums import TA_LEFT
449
+ from reportlab.pdfbase import pdfmetrics
450
+ from reportlab.pdfbase.cidfonts import UnicodeCIDFont
451
+ from reportlab.platypus import (
452
+ SimpleDocTemplate, Paragraph, Spacer, Image as RLImage, PageBreak
453
+ )
454
+ except ImportError:
455
+ return None
456
+
457
+ # 註冊中文字體(reportlab 內建 CID 字體,無需下載)
458
+ try:
459
+ pdfmetrics.registerFont(UnicodeCIDFont("STSong-Light"))
460
+ cjk_font = "STSong-Light"
461
+ except Exception:
462
+ cjk_font = "Helvetica"
463
+
464
+ out_dir = Path("/tmp") if Path("/tmp").exists() else Path(".")
465
+ filename = f"solution_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pdf"
466
+ out_path = out_dir / filename
467
+
468
+ doc = SimpleDocTemplate(
469
+ str(out_path), pagesize=A4,
470
+ leftMargin=2*cm, rightMargin=2*cm,
471
+ topMargin=2*cm, bottomMargin=2*cm,
472
+ )
473
+ styles = getSampleStyleSheet()
474
+ title_style = ParagraphStyle(
475
+ "TitleCJK", parent=styles["Title"],
476
+ fontName=cjk_font, fontSize=20, leading=26, alignment=TA_LEFT,
477
+ )
478
+ h2_style = ParagraphStyle(
479
+ "H2CJK", parent=styles["Heading2"],
480
+ fontName=cjk_font, fontSize=14, leading=20, textColor="#1a4d8f",
481
+ )
482
+ body_style = ParagraphStyle(
483
+ "BodyCJK", parent=styles["BodyText"],
484
+ fontName=cjk_font, fontSize=11, leading=17,
485
+ )
486
+ meta_style = ParagraphStyle(
487
+ "MetaCJK", parent=styles["BodyText"],
488
+ fontName=cjk_font, fontSize=9, textColor="#888888",
489
+ )
490
+
491
+ story = []
492
+ story.append(Paragraph(f"解題紀錄 — {html_lib.escape(subject)}", title_style))
493
+ story.append(Paragraph(
494
+ f"產生時間:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
495
+ meta_style,
496
+ ))
497
+ story.append(Spacer(1, 0.5*cm))
498
+
499
+ for msg in history:
500
+ role = msg["role"]
501
+ content = msg["content"]
502
+ label = "🧑‍🎓 學生提問" if role == "user" else "🎓 教授解答"
503
+ story.append(Paragraph(label, h2_style))
504
+
505
+ path = _extract_path(content)
506
+ if path:
507
+ try:
508
+ img = RLImage(path, width=14*cm, height=10*cm, kind="proportional")
509
+ story.append(img)
510
+ story.append(Spacer(1, 0.2*cm))
511
+ except Exception:
512
+ story.append(Paragraph(f"[圖片:{Path(path).name}]", body_style))
513
+ elif isinstance(content, (list, tuple)):
514
+ for item in content:
515
+ if isinstance(item, str) and Path(item).exists():
516
+ try:
517
+ img = RLImage(item, width=14*cm, height=10*cm, kind="proportional")
518
+ story.append(img)
519
+ story.append(Spacer(1, 0.2*cm))
520
+ except Exception:
521
+ story.append(Paragraph(f"[圖片:{Path(item).name}]", body_style))
522
+ else:
523
+ text = html_lib.escape(str(item)).replace("\n", "<br/>")
524
+ story.append(Paragraph(text, body_style))
525
+ else:
526
+ text = html_lib.escape(str(content)).replace("\n", "<br/>")
527
+ story.append(Paragraph(text, body_style))
528
+ story.append(Spacer(1, 0.4*cm))
529
+
530
+ story.append(Spacer(1, 0.5*cm))
531
+ story.append(Paragraph(
532
+ "此份解答由 AI 輔助生成,僅供學習參考。請務必自行驗證每一步推導。",
533
+ meta_style,
534
+ ))
535
+
536
+ try:
537
+ doc.build(story)
538
+ return str(out_path)
539
+ except Exception as e:
540
+ print(f"PDF 生成失敗:{e}")
541
+ return None
542
+
543
+
544
+ # ============================================================
545
+ # 5. Gradio 介面
546
+ # ============================================================
547
+ THEME = gr.themes.Soft(
548
+ primary_hue="blue",
549
+ secondary_hue="amber",
550
+ font=[gr.themes.GoogleFont("Noto Sans TC"), "ui-sans-serif", "system-ui"],
551
+ )
552
+
553
+ CUSTOM_CSS = """
554
+ .gradio-container { max-width: 1100px !important; }
555
+ footer { display: none !important; }
556
+ .message-row img { max-height: 320px; }
557
+ """
558
+
559
+ LATEX_DELIMS = [
560
+ {"left": "$$", "right": "$$", "display": True},
561
+ {"left": "$", "right": "$", "display": False},
562
+ {"left": "\\[", "right": "\\]", "display": True},
563
+ {"left": "\\(", "right": "\\)", "display": False},
564
+ ]
565
+
566
+
567
+ def build_app() -> gr.Blocks:
568
+ with gr.Blocks(theme=THEME, css=CUSTOM_CSS, title="工程解題助手") as demo:
569
+ gr.Markdown(
570
+ """
571
+ # 📐 工程解題助手 — AI Engineering Problem Solver
572
+ 上傳題目照片,AI 教授會逐步推導並給出最終答案。
573
+ 支援 **電路學、靜力學、動力學、工程數學、材料力學、熱力學**。
574
+
575
+ *使用方式*:選擇科目 → 拍照/上傳圖片 → (可選)輸入補充說明 → 送出。
576
+ 學生可以追問例如「為什麼這一步要用 KCL?」,AI 會延續上下文回答。
577
+ """
578
+ )
579
+
580
+ with gr.Row():
581
+ subject_dd = gr.Dropdown(
582
+ choices=list(SUBJECT_PROMPTS.keys()),
583
+ value="電路學 (Circuit Analysis)",
584
+ label="📚 選擇科目",
585
+ interactive=True,
586
+ scale=3,
587
+ )
588
+ clear_btn = gr.Button("🗑️ 清除對話", variant="secondary", scale=1)
589
+
590
+ chatbot = gr.Chatbot(
591
+ label="解題對話",
592
+ type="messages",
593
+ height=520,
594
+ show_copy_button=True,
595
+ latex_delimiters=LATEX_DELIMS,
596
+ avatar_images=(None, None),
597
+ placeholder=(
598
+ "📷 請拍照或上傳題目圖片開始解題。\n\n"
599
+ "支援單張或多張圖片(題目跨頁時)。\n"
600
+ "可在下方文字框補充說明,例如「請特別解釋第二步」。"
601
+ ),
602
+ )
603
+
604
+ chat_input = gr.MultimodalTextbox(
605
+ interactive=True,
606
+ file_count="multiple",
607
+ file_types=["image"],
608
+ placeholder="輸入文字(可選),或點左方迴紋針上傳題目照片,然後按 Enter 送出…",
609
+ show_label=False,
610
+ sources=["upload", "clipboard"],
611
+ )
612
+
613
+ with gr.Row():
614
+ export_html_btn = gr.Button("📄 匯出 HTML(含 LaTeX 渲染)", variant="secondary")
615
+ export_pdf_btn = gr.Button("📑 匯出 PDF", variant="secondary")
616
+ export_file = gr.File(label="下載解答檔案", interactive=False)
617
+
618
+ gr.Examples(
619
+ examples=[
620
+ {"text": "請以節點分析法解此電路,求節點電壓 V1、V2。", "files": []},
621
+ {"text": "繪製自由體圖並求 A、B 兩支點的反作用力。", "files": []},
622
+ {"text": "求此樑的最大彎矩位置與大小。", "files": []},
623
+ ],
624
+ inputs=chat_input,
625
+ label="💡 範例提問",
626
+ )
627
+
628
+ gr.Markdown(
629
+ """
630
+ ---
631
+ **📌 提示**:
632
+ - LaTeX 數學式會在對話視窗中自動渲染。
633
+ - 匯出 HTML 後可在瀏覽器中按「列印或存為 PDF」獲得完美排版的 PDF(含數學式)。
634
+ - 直接匯出 PDF 則以純文字呈現公式(適合純文字存檔)。
635
+ - 本工具僅為學習輔助,所有解答請務必自行驗證。
636
+ """
637
+ )
638
+
639
+ # ===== 事件繫結 =====
640
+ def add_user_message(user_input: Dict[str, Any], history: List[Dict[str, Any]]):
641
+ """先把使用者訊息加入對話,再清空輸入框。"""
642
+ history = history or []
643
+ files = user_input.get("files", []) or []
644
+ text = (user_input.get("text") or "").strip()
645
+
646
+ # 圖片以 tuple 加入(Gradio multimodal 格式)
647
+ for f in files:
648
+ history.append({"role": "user", "content": {"path": f}})
649
+ if text:
650
+ history.append({"role": "user", "content": text})
651
+ elif not files:
652
+ # 沒有任何內容
653
+ return history, gr.MultimodalTextbox(value=None, interactive=False)
654
+
655
+ return history, gr.MultimodalTextbox(value=None, interactive=False)
656
+
657
+ def bot_respond(history: List[Dict[str, Any]], subject: str):
658
+ """讓 Gemini 對最新的使用者訊息回覆。"""
659
+ if not history:
660
+ yield history
661
+ return
662
+
663
+ # 找出���輪所有「最後連續的 user 訊息」做為當前輸入
664
+ last_user_idx = len(history) - 1
665
+ while last_user_idx >= 0 and history[last_user_idx]["role"] == "user":
666
+ last_user_idx -= 1
667
+ current_user_msgs = history[last_user_idx + 1:]
668
+
669
+ # 組合 user_message 結構
670
+ text_parts = []
671
+ file_parts = []
672
+ for m in current_user_msgs:
673
+ c = m["content"]
674
+ path = _extract_path(c)
675
+ if path:
676
+ file_parts.append(path)
677
+ elif isinstance(c, (list, tuple)):
678
+ for x in c:
679
+ if isinstance(x, str) and Path(x).exists():
680
+ file_parts.append(x)
681
+ else:
682
+ text_parts.append(str(x))
683
+ else:
684
+ text_parts.append(str(c))
685
+
686
+ user_msg = {
687
+ "text": "\n".join(text_parts),
688
+ "files": file_parts,
689
+ }
690
+ past_history = history[: last_user_idx + 1]
691
+
692
+ history.append({"role": "assistant", "content": ""})
693
+ for partial in stream_gemini_response(user_msg, past_history, subject):
694
+ history[-1]["content"] = partial
695
+ yield history
696
+
697
+ def enable_input():
698
+ return gr.MultimodalTextbox(interactive=True)
699
+
700
+ def clear_history():
701
+ return [], None
702
+
703
+ # 送出流程:加 user → 生成回覆 → 重新啟用輸入框
704
+ submit_event = chat_input.submit(
705
+ add_user_message,
706
+ [chat_input, chatbot],
707
+ [chatbot, chat_input],
708
+ queue=False,
709
+ ).then(
710
+ bot_respond,
711
+ [chatbot, subject_dd],
712
+ [chatbot],
713
+ ).then(
714
+ enable_input,
715
+ None,
716
+ [chat_input],
717
+ queue=False,
718
+ )
719
+
720
+ clear_btn.click(clear_history, None, [chatbot, export_file], queue=False)
721
+
722
+ export_html_btn.click(
723
+ lambda h, s: export_html(h, s),
724
+ [chatbot, subject_dd],
725
+ [export_file],
726
+ )
727
+ export_pdf_btn.click(
728
+ lambda h, s: export_pdf(h, s),
729
+ [chatbot, subject_dd],
730
+ [export_file],
731
+ )
732
+
733
+ return demo
734
+
735
+
736
+ # ============================================================
737
+ # 6. 啟動
738
+ # ============================================================
739
+ if __name__ == "__main__":
740
+ app = build_app()
741
+ app.queue(default_concurrency_limit=4).launch(
742
+ server_name="0.0.0.0",
743
+ server_port=int(os.environ.get("PORT", 7860)),
744
+ show_api=False,
745
+ )
746
+ chat_input.submit(
747
+ add_user_message,
748
+ [chat_input, chatbot],
749
+ [chatbot, chat_input],
750
+ queue=False,
751
+ ).then(
752
+ bot_respond,
753
+ [chatbot, subject_dd],
754
+ [chatbot],
755
+ ).then(
756
+ enable_input,
757
+ None,
758
+ [chat_input],
759
+ queue=False,
760
+ )
761
+
762
+ clear_btn.click(clear_history, None, [chatbot, export_file], queue=False)
763
+
764
+ export_html_btn.click(
765
+ lambda h, s: export_html(h, s),
766
+ [chatbot, subject_dd],
767
+ [export_file],
768
+ )
769
+ export_pdf_btn.click(
770
+ lambda h, s: export_pdf(h, s),
771
+ [chatbot, subject_dd],
772
+ [export_file],
773
+ )
774
+
775
+ return demo
776
+
777
+
778
+ # ============================================================
779
+ # 6. 啟動
780
+ # ============================================================
781
+ if __name__ == "__main__":
782
+ app = build_app()
783
+ app.queue(default_concurrency_limit=4).launch(
784
+ server_name="0.0.0.0",
785
+ server_port=int(os.environ.get("PORT", 7860)),
786
+ show_api=False,
787
+ )
788
+ chat_input.submit(
789
+ add_user_message,
790
+ [chat_input, chatbot],
791
+ [chatbot, chat_input],
792
+ queue=False,
793
+ ).then(
794
+ bot_respond,
795
+ [chatbot, subject_dd],
796
+ [chatbot],
797
+ ).then(
798
+ enable_input,
799
+ None,
800
+ [chat_input],
801
+ queue=False,
802
+ )
803
+
804
+ clear_btn.click(clear_history, None, [chatbot, export_file], queue=False)
805
+
806
+ export_html_btn.click(
807
+ lambda h, s: export_html(h, s),
808
+ [chatbot, subject_dd],
809
+ [export_file],
810
+ )
811
+ export_pdf_btn.click(
812
+ lambda h, s: export_pdf(h, s),
813
+ [chatbot, subject_dd],
814
+ [export_file],
815
+ )
816
+
817
+ return demo
818
+
819
+
820
+ # ============================================================
821
+ # 6. 啟動
822
+ # ============================================================
823
+ if __name__ == "__main__":
824
+ app = build_app()
825
+ app.queue(default_concurrency_limit=4).launch(
826
+ server_name="0.0.0.0",
827
+ server_port=int(os.environ.get("PORT", 7860)),
828
+ show_api=False,
829
+ )
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ google-generativeai>=0.8.3
3
+ Pillow>=10.0.0
4
+ reportlab>=4.0.0