Spaces:
Running
Running
ark945 commited on
Commit ·
4bd2f4a
0
Parent(s):
feat: init review progress template with admin panel
Browse filesFiles changed (21)
- .gitignoreAdded+38
- DockerfileAdded+20
- README.mdAdded+12
- config_sample.jsonAdded+14
- deploy_guide.mdAdded+136
- final_solution.mdAdded+47
- get_gmail_token.pyAdded+46
- github_guide.mdAdded+95
- requirements.txtAdded+9
- static/style.cssAdded+431
- supabase_init.sqlAdded+68
- templates/admin.htmlAdded+420
- templates/import.htmlAdded+292
- templates/index.htmlAdded+444
- templates/list.htmlAdded+58
- templates/login.htmlAdded+83
- templates/manage_users.htmlAdded+93
- templates/quiz.htmlAdded+288
- templates/study.htmlAdded+97
- wordApp_web.pyAdded+930
- wordApp_web_localAdded+418
1234567891011121314151617181920212223242526272829303132333435363738# Python__pycache__/*.py[cod]*$py.class.venv/venv/ENV/env/
# Sensitive dataconfig.jsonmemo.txt.envtest_supabase.py
# Legacy / Large filesvocab.dbdata/*.pdf*.zip*.rar*.exe*.spec
# TTS temp filesstatic/tts_*.mp3voice_*.mp3
# IDE.vscode/.idea/.gemini/brain/
# Gmail API Credentialscredentials.jsontoken.json
1234567891011121314151617181920# 使用 Python 3.9 作為基礎鏡像FROM python:3.9-slim
# 設定工作目錄WORKDIR /app
# 複製依賴文件並安裝COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt
# 複製專案原始碼COPY . .
# 暴露 Flask 預設端口 (Hugging Face Spaces 要求 7860)EXPOSE 7860
# 使用 Gunicorn 啟動應用程式 (適合雲端生產環境)CMD ["gunicorn", "--bind", "0.0.0.0:7860", "--timeout", "300", "wordApp_web:app"]123456789101112---title: Word App On Webemoji: 📚colorFrom: bluecolorTo: indigosdk: dockerpinned: false---
# Word App on Web
A simple web-based vocabulary learning application.1234567891011121314{ "supabase_settings": { "url": "https://your-project.supabase.co", "key": "your-anon-or-service-key" }, "email_settings": { "enable": true, "sender_email": "your-email@gmail.com", "app_password": "your-16-char-app-password", "receivers": [ "receiver-email@gmail.com" ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136# 複習進度表系統 (模板版) 從無到有佈署指南
這份指南將引導您如何**從零開始**在 Supabase 建立新的資料庫實例 (Instance),並在 Hugging Face (HF) Spaces 上建立獨立且可自訂網址的系統。
---
## 🛠️ 第一階段:Supabase 資料庫初始化 (全新實例)
如果您想與現行版本完全分離,請在 Supabase 建立一個全新的 Project:
### 1. 建立新專案1. 登入 [Supabase Dashboard](https://supabase.com/dashboard/)。2. 點擊 **"New Project"**,選擇您的 Organization,並填寫專案名稱 (例如:`WordApp-Basic`)、設定資料庫密碼與區域。3. 建立後,請稍等 1-2 分鐘讓資料庫實例配置完畢。Database password:YOUR_DATABASE_PASSWORD
### 2. 執行 SQL 結構初始化1. 在左側選單點擊 **"SQL Editor"**。2. 點擊 **"New query"** (新建查詢)。3. 複製並貼上專案根目錄下的 [`supabase_init.sql`](supabase_init.sql) 完整內容,然後點擊 **"Run"**。4. 看到 **"Success"** 即代表以下四個資料表與 RLS 政策已成功建立: * `words`:儲存單元單字。 * `users`:儲存學生名單。 * `quiz_results`:儲存學生測驗分數與正確率。 * `system_config`:儲存後台配置(複習起迄日期、規定天數、信箱設定等)。
### 3. 建立儲存空間 (Bucket) 用以存放單字 PDF1. 點擊左側選單的 **"Storage"**。2. 點擊 **"New Bucket"**。3. **Bucket Name** 欄位輸入:`pdfs` (務必全小寫)。4. 開啟 **"Public bucket"** 選項(此選項方便前台取得 PDF 資料)。5. 點擊 **"Save"**。
---
## 🚀 第二階段:Hugging Face Spaces 建立與自訂網址
Hugging Face Spaces 提供免費的 Docker 託管服務,您可以自由命名您的 Space 來獲得自訂的網址。
### 0. (選擇性) 建立組織以獲得自訂網址前綴 (避免使用個人帳號名稱)如果您不希望網址開頭顯示您的個人 Hugging Face 帳號名稱 (例如 `ark945`),可以免費建立一個組織:1. 點選 Hugging Face 右上角頭像,選擇 **"New Organization"**。2. **Organization Username**:填入您想要的網址前綴(例如:`easy-english`)。3. 建立後,您就可以在下一步建立 Space 時,將擁有者 (Owner) 設為該組織,網址將會自動變為:`https://easy-english-Space名稱.hf.space`。
### 1. 建立新 Space1. 前往 [Hugging Face Spaces](https://huggingface.co/spaces) 頁面。2. 點擊右上角的 **"Create new Space"**。3. **Owner (擁有者)**: * 預設為您的個人帳號。如果您在「步驟 0」建立了組織,請在下拉選單中**切換成該組織**。4. **Space name (重要 - 自訂網址名稱)**: * 這會決定您的最終網址。例如:若 Owner 為 `easy-english` 且名稱輸入 `word-app`,您的網址將會是: `https://huggingface.co/spaces/easy-english/word-app` 其獨立全螢幕網址將會是: `https://easy-english-word-app.hf.space/` MyClass5. **License**:留空或輸入 `mit`。6. **SDK**:務必選擇 **"Docker"**。7. **Template**:選擇 **"Blank"**。8. **Space hardware**:選擇預設的 **"Cpu basic • 2 vCPU • 16 GB • Free"**。9. **Visibility**:選擇 **"Public"** (若需要隱私保護,本專案已自帶後台密碼鎖,所以 Public 即可)。10. 點擊底部的 **"Create Space"**。
### 2. 在 Hugging Face 設定環境變數 (Secrets)1. 進入您剛建立 the Space 頁面,點擊上方的 **"Settings"** 頁籤。2. 在左側選單點選 **"Variables and secrets"**。3. 點選 **"New secret"** 依次新增以下環境變數:
| Secret Key (名字) | Value (填寫內容) | 說明 || :--- | :--- | :--- || `SUPABASE_URL` | 您的新 Supabase API 網址 | 於左側選單 **INTEGRATIONS -> Data API** 最上方的 `API URL` 取得(只需複製到 `.supabase.co` 即可,例如:`https://xxxx.supabase.co`) |https://YOUR_SUPABASE_PROJECT_ID.supabase.co| `SUPABASE_KEY` | 您的新 Supabase `service_role` 金鑰 | 於左側選單 **Project Settings (齒輪) -> API Keys -> Secret keys** 下的 **default**(點擊 Reveal 顯示後複製以 `sb_secret_` 開頭的金鑰) |YOUR_SUPABASE_SERVICE_ROLE_KEY| `ADMIN_USERNAME` | 您的自訂後台登入帳號 | 例如:`teacher` (若不設定,預設為 `admin`) || `ADMIN_PASSWORD` | 您的自訂後台登入密碼 | 例如:`mysecurepwd123` (若不設定,預設為 `admin123`) |
---
## 💻 第三階段:Git 本地推送與佈署
請在您的本機電腦上,開啟終端機(PowerShell 或 Command Prompt)將模板專案推送至新建立的 HF Space。
### 1. 初始化本地 Git 倉庫並進行首次提交如果您尚未在此資料夾進行 git 初始化,請執行:```bash# 1. 進入您的模板專案目錄cd d:\MyLab\wordAppTemplate
# 2. 初始化 Git 倉庫git init
# 3. 將所有修改與檔案加入暫存區git add .
# 4. 進行本地 Commit 提交git commit -m "feat: init review progress template with admin panel"```
### 2. 連接 Hugging Face 並推送1. 在您建立的 Hugging Face Space 頁面中,點擊右上角 **"Use via Git"** 或 **"Clone this Space"** 可看見專屬的 git 位址。2. 在終端機執行以下指令連接並強制推送:```bash# 連接您的新 Space(請將下方的用戶名與 Space 名稱替換為您實際的內容)git remote add hf https://huggingface.co/spaces/您的HF帳號/您的Space名稱
# 推送代碼至 Hugging Face (通常預設分支為 main)git push -f hf main```3. 推送後,HF 網頁上的 App 狀態會轉為 **"Building"**,編譯約需 2-3 分鐘。4. 狀態變為綠色的 **"Running"** 時,即代表網頁建置完成!您可以點擊網址進入系統。
---
## ⚙️ 第四階段:後台設定與使用指引 (免動代碼)
網頁成功執行後,您不需要修改任何程式碼,只要在瀏覽器上操作後台即可:
### 1. 登入後台1. 打開您的網頁(例如 `https://您的帳號-Space名稱.hf.space/`)。2. 點選右上角的 **"🔐 後台管理"** 按鈕。3. 輸入您在 HF Secrets 中設定的 `ADMIN_USERNAME` 與 `ADMIN_PASSWORD`。
### 2. 進行首次設定在後台主控台中,您可以設定以下三大項目,儲存後會立即寫入 Supabase 中:1. **複習進度表設定**: * **複習起迄時間**:選擇本次進度表的開始與結束日期。 * **規定複習次數**:設定學生需要達到幾天 (例如 1 天或 2 天)。 * **複習單元列表**:系統會自動抓取您匯入的單字單元,點選 **"全選"** 或 **"全不選"**,並勾選本次要納入計分的單元。(*注意:未勾選的單元不會出現在進度表上*)。2. **郵件通知設定 (SMTP 簡單設定)**: * 勾選 **"啟用測驗完成 Email 通知"**。 * 輸入 **"寄件者信箱"** (例如您的 Gmail 地址)。 * 輸入 **"郵件授權密碼 (App Password)"**(至 Google 帳號安全性設定中產生 16 位元應用程式密碼)。 * 輸入 **"收件者信箱"**(多位家長/老師請用逗號隔開)。3. **儲存設定**: * 點選 **"💾 儲存所有設定"**,即刻完成部署!1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# wordAppOnWeb 現代化轉型方案總結
這份文件總結了將您的單字 App 從「本地開發版」轉型為「雲端穩定版」的最佳做法。
## 1. 雲端網站 (Website Hosting)* **推薦平台**:**Hugging Face Spaces** (或 Render)。* **做法**:將程式碼打包成 Docker 容器佈署。* **優勢**: * Hugging Face 提供免費 16GB RAM,資源多。 * 休眠時間長 (48小時),不像 Render 15分鐘就關機,發信背景作業更穩定。
## 2. 雲端資料庫 (Database & Storage)* **服務商**:**Supabase**。* **資料庫 (DB)**:使用 Supabase PostgreSQL。 * **改善點**:取代原本的 SQLite `vocab.db`。資料永久儲存,重啟伺服器不會消失。* **檔案儲存 (Storage)**:使用 Supabase Storage (Bucket 名稱為 `pdfs`)。 * **改善點**:取代 GitHub 或本地資料夾。PDF 統一存在雲端,並有專屬網址。
## 3. 寄送 Email (Gmail SMTP)* **服務商**:**Gmail**。* **必要設定**:**Google 應用程式密碼 (App Password)**。 * 您必須開啟 Google 帳號的「兩階段驗證」,然後生成一個 16 位元的「應用程式密碼」供程式連線使用。* **實作改進**: * 使用 `threading` 背景發信。 * 加入更強的錯誤捕捉運算 (Retry Logic),解決雲端 IP 偶爾連不上 Gmail 的問題。
## 4. 設定檔與安全 (Configuration)* **做法**:**環境變數 (Environment Variables)**。* **說明**:為了安全,我們**不會**把秘密金鑰寫在 `wordApp_web.py` 裡面。* **需要存放的變數**: * `SUPABASE_URL`: (您已取得) * `SUPABASE_KEY`: (您已取得,即 Secret Key) * `GMAIL_USER`: 您的 Gmail 地址。 * `GMAIL_PASSWORD`: 您的 16 位元應用程式密碼。 * `RECEIVERS`: 收件人清單。
## ⚙️ 接下來的開發順序1. **[變更資料庫層]**:把 `DatabaseManager` 從 SQL 語法改為 Supabase SDK 呼叫。2. **[接入儲存空間]**:改寫上傳邏輯,將 PDF 推送到 Supabase Storage。3. **[改進郵件邏輯]**:封裝一個標準的發信類別,支援 Gmail 的穩定連線。4. **[產生佈署檔案]**:撰寫 `Dockerfile` 與 `requirements.txt`。
---
> [!TIP]> **為什麼不去買網域?**> 因為您的需求是「穩定且免費且發給別人」。在沒有網域的情況下,用 Gmail SMTP 配合「應用程式密碼」雖然稍微傳統,但對於非商業、輕量級的小工具來說,這依然是最具成本效益且能寄信給任何人的方式。12345678910111213141516171819202122232425262728293031323334353637383940414243444546import osimport jsonfrom google_auth_oauthlib.flow import InstalledAppFlowfrom google.oauth2.credentials import Credentialsfrom google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.json.SCOPES = ['https://www.googleapis.com/auth/gmail.send']
def main(): creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: if not os.path.exists('credentials.json'): print("❌ 錯誤: 找不到 'credentials.json' (GCP Client Secret File)。") print("請先前往 Google Cloud Console 下載憑證,並將其重新命名為 'credentials.json' 放置於此目錄。") return
flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.json', 'w') as token: token.write(creds.to_json()) print("\n✅ OAuth 認證成功!") print("----------------------------------------------------------------") print("請複製以下 JSON 內容 (包含大括號),並貼到 Hugging Face 的 Secrets 中:") print("Key: GMAIL_CREDENTIALS") print("Value:") print("----------------------------------------------------------------") print(creds.to_json()) print("----------------------------------------------------------------")
if __name__ == '__main__': main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# 程式碼修改與推送指南
這份文件說明當您修改了任何檔案後,如何將變更推送到 **GitHub** 與 **Hugging Face**。
---
## 快速版(複製貼上即可)
當您改完程式碼,在終端機依序貼入以下指令:
```powershellcd d:\MyProject\wordApp_web
git add .git commit -m "簡短描述您改了什麼"git push origin mastergit push hf master:main```
> 推送到 `hf` 後,Hugging Face Space 會**自動重新建置並部署**。
---
## 詳細說明
### Step 1:查看哪些檔案被修改了
```powershellgit status```
會列出所有被新增、修改、刪除的檔案,方便您確認。
### Step 2:將變更加入暫存區
```powershell# 加入所有變更git add .
# 或只加入特定檔案git add wordApp_web.pygit add templates/quiz.html```
### Step 3:建立提交(Commit)
```powershellgit commit -m "描述您的改動內容"```
**提交訊息範例:**- `"fix: 修正 Email 發送失敗的問題"`- `"feat: 新增使用者管理頁面"`- `"style: 調整首頁排版"`
### Step 4:推送到遠端
```powershell# 推送到 GitHub(原始碼備份)git push origin master
# 推送到 Hugging Face(正式部署)git push hf master:main```
> **注意**:GitHub 的分支名是 `master`,Hugging Face 的分支名是 `main`,所以推送到 HF 時要寫 `master:main`。
---
## 常見問題
### Q: 推送時要求輸入帳號密碼?- **GitHub**:使用 Personal Access Token 當作密碼(不是 GitHub 登入密碼)。- **Hugging Face**:使用 HF Access Token 當作密碼。
### Q: 推送失敗顯示 "rejected"?代表遠端有您本地沒有的變更,先拉取再推送:```powershellgit pull origin master --rebasegit push origin master```
### Q: 不小心 commit 了不該提交的檔案?```powershell# 撤銷最近一次 commit(保留檔案變更)git reset --soft HEAD~1```
---
## 安全注意事項
- **`.gitignore` 已設定**:`config.json`、`token.json`、`.env` 等敏感檔案會被自動排除,不會被推送。- **絕對不要**手動移除 `.gitignore` 裡的限制,否則您的秘密金鑰會被公開。- 若要在其他電腦開發,請參考 `config_sample.json` 手動建立您自己的 `config.json`。123456789flaskedge-ttspdfplumbersupabaserequestsgunicorngoogle-api-python-clientgoogle-auth-httplib2google-auth-oauthlib123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431/* static/style.css */:root { --primary-color: #6366f1; /* Indigo 500 */ --primary-hover: #4f46e5; /* Indigo 600 */ --accent-color: #ec4899; /* Pink 500 */ --bg-color: #f1f5f9; /* Slate 100 */ --card-bg: #ffffff; --text-main: #1e293b; /* Slate 800 */ --text-muted: #64748b; /* Slate 500 */ --border-color: #cbd5e1; /* Slate 300 */ --success: #22c55e; --error: #ef4444;}
body { font-family: 'Segoe UI', 'Inter', system-ui, -apple-system, sans-serif; background-color: var(--bg-color); color: var(--text-main); margin: 0; padding: 20px; line-height: 1.6;}
.container { max-width: 900px; margin: 0 auto;}
.card { background: var(--card-bg); border-radius: 16px; padding: 32px; box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); margin-bottom: 24px; transition: transform 0.2s;}
/* Header Specifics */header.card { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; background: linear-gradient(to right, #ffffff, #f8fafc);}
h1 { color: var(--primary-color); font-size: 1.8rem; margin: 0; display: flex; align-items: center; gap: 10px;}
h2 { color: var(--text-main); font-size: 1.5rem; margin-top: 0; margin-bottom: 20px; border-bottom: 2px solid var(--bg-color); padding-bottom: 10px;}
/* Controls & Buttons */.controls { display: flex; align-items: center; gap: 15px;}
.user-select-wrapper { display: flex; align-items: center; background: var(--bg-color); padding: 5px 15px; border-radius: 50px; border: 1px solid var(--border-color);}
select { border: none; background: transparent; font-size: 1rem; padding: 5px; outline: none; cursor: pointer; color: var(--text-main); font-weight: 600;}
.btn { display: inline-flex; align-items: center; justify-content: center; padding: 10px 24px; border-radius: 12px; border: none; cursor: pointer; font-weight: 600; transition: all 0.2s ease; text-decoration: none; font-size: 0.95rem; box-shadow: 0 2px 4px rgb(0 0 0 / 0.05);}
.btn:hover { transform: translateY(-2px); box-shadow: 0 4px 6px rgb(0 0 0 / 0.1);}
.btn:active { transform: translateY(0);}
.btn-primary { background-color: var(--primary-color); color: white;}
.btn-primary:hover { background-color: var(--primary-hover);}
.btn-secondary { background-color: white; color: var(--text-main); border: 1px solid var(--border-color);}
.btn-secondary:hover { background-color: var(--bg-color); color: var(--primary-color);}
/* Unit List */.unit-item { display: flex; justify-content: space-between; align-items: center; padding: 20px; border: 1px solid var(--bg-color); border-radius: 12px; margin-bottom: 15px; transition: all 0.2s;}
.unit-item:hover { border-color: var(--primary-color); background-color: #f8fafc;}
.unit-name { font-size: 1.1rem; font-weight: 700; color: var(--text-main);}
/* Quiz Styles */.word-card { text-align: center; padding: 60px 20px;}
.word-main { font-size: 3.5rem; font-weight: 800; color: var(--text-main); letter-spacing: -1px; margin-bottom: 20px;}
.options { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-top: 30px;}
.quiz-btn { padding: 25px; font-size: 1.1rem; background: white; border: 2px solid var(--bg-color); border-radius: 16px; cursor: pointer; transition: all 0.2s; color: var(--text-main);}
.quiz-btn:hover { border-color: var(--primary-color); background: #e0e7ff;}
.correct { background: #dcfce7 !important; border-color: #22c55e !important; color: #14532d;}
.wrong { background: #fee2e2 !important; border-color: #ef4444 !important; color: #7f1d1d;}
/* ========================================== 4. Tab Switcher & Progress Table Styles ========================================== */.tabs-container { display: flex; gap: 8px; margin-bottom: 20px; border-bottom: 2px solid var(--border-color); padding-bottom: 1px;}
.tab-btn { padding: 12px 24px; background: transparent; border: none; cursor: pointer; font-size: 1rem; font-weight: 700; color: var(--text-muted); border-bottom: 3px solid transparent; transition: all 0.2s ease; outline: none;}
.tab-btn:hover { color: var(--primary-color); background-color: rgba(99, 102, 241, 0.05); border-radius: 8px 8px 0 0;}
.tab-btn.active { color: var(--primary-color); border-bottom-color: var(--primary-color);}
.tab-content { display: none;}
.tab-content.active-content { display: block; animation: tabFadeIn 0.3s ease;}
@keyframes tabFadeIn { from { opacity: 0; transform: translateY(5px); } to { opacity: 1; transform: translateY(0); }}
/* Table styles & responsive wrapper */.table-responsive { overflow-x: auto; width: 100%; border-radius: 12px; border: 1px solid var(--border-color); box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.05);}
.progress-table { width: 100%; border-collapse: separate; border-spacing: 0; text-align: center; font-size: 0.9rem; background: white;}
.progress-table th, .progress-table td { border-right: 1px solid var(--border-color); border-bottom: 1px solid var(--border-color); padding: 10px 8px; vertical-align: middle;}
.progress-table th:last-child, .progress-table td:last-child { border-right: none;}
.progress-table th { background-color: #f8fafc; font-weight: 700; color: var(--text-main);}
/* ========================================== 4. 大表格矩陣滾動與 Sticky 樣式 ========================================== */.matrix-scroll-container { max-height: 650px; overflow: auto;}
.matrix-table { table-layout: auto;}
/* Sticky 表頭 (縱向滾動固定在最上方) */.matrix-table thead th { position: sticky; top: 0; background-color: #f8fafc; z-index: 15; box-shadow: 0 2px 2px -1px rgba(0,0,0,0.1);}
/* Sticky 首欄日期 (橫向滾動固定在最左邊) */.matrix-table td.sticky-col-header, .matrix-table th.sticky-col-header { position: sticky; left: 0; background-color: #f8fafc; z-index: 10; box-shadow: 2px 0 5px -2px rgba(0,0,0,0.15); border-right: 2px solid var(--border-color) !important;}
/* 雙重 Sticky (左上角交角) */.matrix-table th.sticky-col-header { z-index: 30; top: 0; background-color: #f1f5f9;}
/* Sticky 最下方 Summary (縱向滾動固定在最下方) */.matrix-summary-row td { position: sticky; bottom: 0; background-color: #f1f5f9; z-index: 15; box-shadow: 0 -2px 5px -2px rgba(0,0,0,0.15); font-weight: bold; border-top: 2px solid var(--border-color) !important;}
/* 交角左下角的 Summary */.matrix-summary-row td.sticky-col-header { z-index: 25; left: 0; background-color: #e2e8f0 !important;}
/* 週末列高亮 */.weekend-row td { background-color: #fafbfc;}
.weekend-row td.date-col { background-color: #f1f5f9 !important; color: var(--primary-color);}
/* 矩陣交叉格最小寬度與排列 */.matrix-cell { min-width: 130px; padding: 6px 8px !important;}
.matrix-cell div { margin: 3px auto;}
/* 測驗小標籤 */.progress-badge { font-size: 0.72rem; padding: 3px 6px; border-radius: 6px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; font-weight: 700; line-height: 1.3; display: inline-block; max-width: 120px; margin: 2px;}
.badge-quiz { background-color: #e0e7ff; color: #3730a3; border: 1px solid #c7d2fe;}
.badge-reverse { background-color: #f3e8ff; color: #6b21a8; border: 1px solid #e9d5ff;}
.badge-spelling { background-color: #fce7f3; color: #9d174d; border: 1px solid #fbcfe8;}
/* Summary 欄格 */.matrix-footer-cell { padding: 10px 6px !important;}
/* 個人彙總狀態標籤 */.unit-status-pill { display: inline-block; padding: 2px 8px; border-radius: 50px; font-size: 0.7rem; font-weight: 700;}
.unit-status-pill.completed { background-color: #dcfce7; color: #15803d;}
.unit-status-pill.in-progress { background-color: #fef3c7; color: #d97706;}
.unit-status-pill.not-started { background-color: #f1f5f9; color: #64748b;}
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768-- 1. 建立單字資料表CREATE TABLE IF NOT EXISTS words ( id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, unit TEXT, word TEXT, pos TEXT, definition TEXT, sentence TEXT, correct_count INTEGER DEFAULT 0, wrong_count INTEGER DEFAULT 0, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), UNIQUE(unit, word, pos));
-- 2. 建立使用者資料表CREATE TABLE IF NOT EXISTS users ( id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, name TEXT UNIQUE, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW());
-- 3. 啟用 RLS(只有持有 Secret Key 的後端才能存取)ALTER TABLE words ENABLE ROW LEVEL SECURITY;ALTER TABLE users ENABLE ROW LEVEL SECURITY;
-- 4. 建立存取政策(允許 service_role 完全存取)CREATE POLICY "Allow all for service_role" ON words FOR ALL USING (true) WITH CHECK (true);
CREATE POLICY "Allow all for service_role" ON users FOR ALL USING (true) WITH CHECK (true);
-- 5. 建立測驗結果紀錄表CREATE TABLE IF NOT EXISTS quiz_results ( id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY, user_name TEXT NOT NULL, unit TEXT NOT NULL, mode TEXT NOT NULL, -- 'quiz' (選中文), 'reverse' (選英文), 'spelling' (拼字) score INTEGER NOT NULL, total INTEGER NOT NULL, accuracy FLOAT NOT NULL, -- 正確率 (0 ~ 100) created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW());
-- 6. 啟用 RLSALTER TABLE quiz_results ENABLE ROW LEVEL SECURITY;
-- 7. 建立存取政策(允許 service_role 完全存取)DROP POLICY IF EXISTS "Allow all for service_role" ON quiz_results;CREATE POLICY "Allow all for service_role" ON quiz_results FOR ALL USING (true) WITH CHECK (true);
-- 8. 建立系統設定資料表CREATE TABLE IF NOT EXISTS system_config ( key TEXT PRIMARY KEY, value JSONB NOT NULL, updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW());
-- 9. 啟用 RLSALTER TABLE system_config ENABLE ROW LEVEL SECURITY;
-- 10. 建立系統設定存取政策DROP POLICY IF EXISTS "Allow all for service_role" ON system_config;CREATE POLICY "Allow all for service_role" ON system_config FOR ALL USING (true) WITH CHECK (true);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420<!DOCTYPE html><html lang="zh-TW"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>系統後台管理 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <style> .admin-header { display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--border-color); padding-bottom: 15px; margin-bottom: 30px; } .form-section { margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid var(--border-color); } .form-section:last-child { border-bottom: none; } .form-section h3 { margin-top: 0; color: var(--primary-color); margin-bottom: 15px; display: flex; align-items: center; gap: 8px; } .form-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 15px; } .form-group { display: flex; flex-direction: column; } .form-group label { margin-bottom: 8px; font-weight: 600; font-size: 0.95rem; } .form-control { padding: 10px 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 1rem; outline: none; transition: border-color 0.2s; } .form-control:focus { border-color: var(--primary-color); } .unit-checkbox-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; max-height: 200px; overflow-y: auto; padding: 15px; border: 1px solid var(--border-color); border-radius: 8px; background-color: var(--bg-color); } .unit-checkbox-label { display: flex; align-items: center; gap: 8px; cursor: pointer; font-size: 0.95rem; user-select: none; } .checkbox-input { width: 16px; height: 16px; cursor: pointer; } .switch-container { display: flex; align-items: center; gap: 10px; margin-bottom: 15px; } .switch { position: relative; display: inline-block; width: 50px; height: 26px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e1; transition: .3s; border-radius: 34px; } .slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 4px; bottom: 4px; background-color: white; transition: .3s; border-radius: 50%; } input:checked + .slider { background-color: var(--primary-color); } input:checked + .slider:before { transform: translateX(24px); } .msg-toast { position: fixed; top: 20px; right: 20px; padding: 15px 25px; border-radius: 8px; color: white; font-weight: 600; box-shadow: 0 4px 12px rgba(0,0,0,0.15); z-index: 9999; transform: translateY(-20px); opacity: 0; transition: all 0.3s ease; } .msg-toast.show { transform: translateY(0); opacity: 1; } .msg-toast.success { background-color: var(--success); } .msg-toast.error { background-color: var(--error); } </style></head><body> <div class="container"> <!-- Toast Notification --> <div id="toast" class="msg-toast"></div>
<header class="card"> <div> <h1>⚙️ 系統後台管理</h1> <p style="color: var(--text-muted); margin-top: 5px;">配置單字系統、複習進度表與發信設定</p> </div> <div class="controls"> <a href="/" class="btn btn-secondary">🏠 首頁</a> <a href="{{ url_for('admin_logout') }}" class="btn btn-secondary" style="border-color: var(--error); color: var(--error);">登出</a> </div> </header>
<div class="card" style="padding: 32px;"> <div class="admin-header"> <h2 style="margin: 0; border: none; padding: 0;">🔧 系統參數設定</h2> <button onclick="saveAllSettings()" class="btn btn-primary">💾 儲存所有設定</button> </div>
<!-- 1. 複習表設定 --> <div class="form-section"> <h3>📅 複習進度表設定</h3> <div class="form-row"> <div class="form-group"> <label for="startDate">複習開始日期</label> <input type="date" id="startDate" class="form-control" required> </div> <div class="form-group"> <label for="endDate">複習結束日期</label> <input type="date" id="endDate" class="form-control" required> </div> <div class="form-group"> <label for="requiredDays">規定複習次數 (天數)</label> <input type="number" id="requiredDays" class="form-control" min="1" max="60" value="2" required> </div> </div>
<div class="form-group" style="margin-top: 15px;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;"> <label style="margin: 0;">要納入複習的單元</label> <div style="display: flex; gap: 8px;"> <button type="button" onclick="selectAllUnits(true)" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.8rem; border-radius: 6px;">全選</button> <button type="button" onclick="selectAllUnits(false)" class="btn btn-secondary" style="padding: 4px 10px; font-size: 0.8rem; border-radius: 6px;">全不選</button> </div> </div> <div class="unit-checkbox-container" id="unitCheckboxes"> <!-- JS 動態插入單元 --> </div> </div> </div>
<!-- 2. Email 設定 --> <div class="form-section"> <h3>✉️ 郵件通知設定</h3> <div class="switch-container"> <label class="switch"> <input type="checkbox" id="emailEnable"> <span class="slider"></span> </label> <span style="font-weight: 600; font-size: 1rem;">啟用測驗完成 Email 通知</span> </div>
<div class="form-row"> <div class="form-group"> <label for="senderEmail">寄件者信箱 (Sender Email)</label> <input type="email" id="senderEmail" class="form-control" placeholder="example@gmail.com"> </div> <div class="form-group"> <label for="appPassword">郵件授權密碼 (App Password)</label> <input type="password" id="appPassword" class="form-control" placeholder="若使用環境變數設定則留空"> </div> </div> <div class="form-group" style="margin-top: 10px;"> <label for="receivers">收件者信箱 (多個請用逗號隔開)</label> <input type="text" id="receivers" class="form-control" placeholder="parent1@example.com, parent2@example.com"> </div> </div>
<!-- 3. 密碼修改設定 --> <div class="form-section"> <h3>🔐 修改管理員密碼</h3> <p style="color: var(--text-muted); font-size: 0.85rem; margin-top: -5px; margin-bottom: 15px;"> 注意:若您有設定環境變數 `ADMIN_PASSWORD`,系統密碼將被強制寫死在環境變數中,後台密碼修改將不生效。 </p> <div class="form-row"> <div class="form-group"> <label for="oldPassword">舊密碼</label> <input type="password" id="oldPassword" class="form-control" placeholder="請輸入原密碼"> </div> <div class="form-group"> <label for="newPassword">新密碼</label> <input type="password" id="newPassword" class="form-control" placeholder="請輸入新密碼"> </div> <div class="form-group"> <label for="confirmPassword">確認新密碼</label> <input type="password" id="confirmPassword" class="form-control" placeholder="請再次輸入新密碼"> </div> </div> <button onclick="updatePassword()" class="btn btn-secondary" style="align-self: flex-start; margin-top: 5px;">🔑 變更密碼</button> </div>
<div style="display: flex; justify-content: flex-end; margin-top: 30px; border-top: 2px solid var(--border-color); padding-top: 20px;"> <button onclick="saveAllSettings()" class="btn btn-primary" style="padding: 12px 30px; font-size: 1rem;">💾 儲存所有設定</button> </div> </div> </div>
<script> let availableUnits = [];
function showToast(message, type = 'success') { const toast = document.getElementById('toast'); toast.innerText = message; toast.className = `msg-toast ${type} show`; setTimeout(() => { toast.classList.remove('show'); }, 3000); }
function selectAllUnits(status) { document.querySelectorAll('.unit-check').forEach(cb => { cb.checked = status; }); }
async function loadSettings() { try { const res = await fetch('/api/admin/config'); const data = await res.json();
if (!data.success) { showToast(data.message || '讀取設定失敗', 'error'); return; }
const config = data.config; availableUnits = data.available_units || [];
// 填入複習設定 const rSettings = config.review_settings || {}; document.getElementById('startDate').value = rSettings.start_date || '2026-07-01'; document.getElementById('endDate').value = rSettings.end_date || '2026-08-31'; document.getElementById('requiredDays').value = rSettings.required_days || 2;
// 填入單元選單 const selectedUnits = rSettings.selected_units || []; const container = document.getElementById('unitCheckboxes'); container.innerHTML = ''; if (availableUnits.length === 0) { container.innerHTML = '<span style="color: var(--text-muted);">系統中尚無單元單字</span>'; } else { availableUnits.forEach(unit => { const isChecked = selectedUnits.includes(unit); const label = document.createElement('label'); label.className = 'unit-checkbox-label'; label.innerHTML = ` <input type="checkbox" class="checkbox-input unit-check" value="${unit}" ${isChecked ? 'checked' : ''}> <span>${unit}</span> `; container.appendChild(label); }); }
// 填入 Email 設定 const eSettings = config.email_settings || {}; document.getElementById('emailEnable').checked = eSettings.enable || false; document.getElementById('senderEmail').value = eSettings.sender_email || ''; document.getElementById('receivers').value = (eSettings.receivers || []).join(', '); document.getElementById('appPassword').value = ''; // 密碼欄位只供寫入,讀取時維持空白
} catch (e) { console.error(e); showToast('伺服器連接錯誤,請稍後再試', 'error'); } }
async function saveAllSettings() { // 收集單元勾選結果 const checkedUnits = []; document.querySelectorAll('.unit-check:checked').forEach(cb => { checkedUnits.push(cb.value); });
const review_settings = { start_date: document.getElementById('startDate').value, end_date: document.getElementById('endDate').value, required_days: parseInt(document.getElementById('requiredDays').value) || 2, selected_units: checkedUnits };
const receiversRaw = document.getElementById('receivers').value; const receivers = receiversRaw.split(',') .map(r => r.trim()) .filter(r => r !== '');
const email_settings = { enable: document.getElementById('emailEnable').checked, sender_email: document.getElementById('senderEmail').value.trim(), receivers: receivers };
const appPwd = document.getElementById('appPassword').value.trim(); if (appPwd) { email_settings.app_password = appPwd; }
try { const res = await fetch('/api/admin/config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ review_settings, email_settings }) }); const result = await res.json();
if (result.success) { showToast('設定已成功儲存至 Supabase 雲端!'); loadSettings(); // 重新載入以維持一致性 } else { showToast(result.message || '儲存失敗', 'error'); } } catch (e) { console.error(e); showToast('儲存失敗,請檢查網路連線', 'error'); } }
async function updatePassword() { const oldPassword = document.getElementById('oldPassword').value; const newPassword = document.getElementById('newPassword').value; const confirmPassword = document.getElementById('confirmPassword').value;
if (!oldPassword || !newPassword) { showToast('請填寫完整密碼欄位', 'error'); return; }
if (newPassword !== confirmPassword) { showToast('新密碼與確認新密碼不符', 'error'); return; }
try { const res = await fetch('/api/admin/password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }) }); const result = await res.json();
if (result.success) { showToast('密碼已成功更新!'); document.getElementById('oldPassword').value = ''; document.getElementById('newPassword').value = ''; document.getElementById('confirmPassword').value = ''; } else { showToast(result.message || '更變密碼失敗', 'error'); } } catch (e) { console.error(e); showToast('變更密碼發生錯誤', 'error'); } }
// 頁面初始化 loadSettings(); </script></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292<!DOCTYPE html><html lang="zh-TW">
<head> <meta charset="UTF-8"> <title>匯入單字 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head>
<body> <div class="container"> <div class="card"> <a href="{{ url_for('index') }}">← 返回主頁</a> <h1>📄 匯入 PDF 單字</h1> <p>請上傳包含單字表的 PDF 檔案。</p>
<section style="margin-top: 20px;"> <h3>Step 1: 上傳到雲端儲存</h3> <input type="file" id="fileInput" accept=".pdf" multiple> <button onclick="uploadFile()" id="uploadBtn" class="btn btn-primary">上傳檔案</button> </section>
<section style="margin-top: 40px; border-top: 1px solid #eee; padding-top: 20px;"> <h3>Step 2: 從雲端同步到資料庫</h3> <p>上傳多個檔案後,點擊下方按鈕開始解析內容。</p> <button onclick="reimport()" id="importBtn" class="btn">同步資料庫</button> </section>
<div id="status" style="margin-top: 20px; font-weight: bold; white-space: pre-line;"></div>
<section style="margin-top: 40px; border-top: 1px solid #eee; padding-top: 20px;"> <h3>☁️ 雲端 PDF 檔案</h3> <p style="color:var(--text-muted); font-size:0.85rem;">這些是 Supabase Storage 中的 PDF,同步時會從這裡讀取。</p> <div id="storageList" style="margin-top: 10px;">載入中...</div> </section>
<section style="margin-top: 40px; border-top: 1px solid #eee; padding-top: 20px;"> <h3>📋 已匯入的單元</h3> <div id="unitList" style="margin-top: 10px;">載入中...</div> </section> </div> </div>
<script> async function uploadFile() { const input = document.getElementById('fileInput'); if (input.files.length === 0) return alert('請選擇檔案');
const formData = new FormData(); for (let i = 0; i < input.files.length; i++) { formData.append('file', input.files[i]); }
document.getElementById('status').innerText = `上傳中(${input.files.length} 個檔案)...`; try { const res = await fetch('/api/upload', { method: 'POST', body: formData }); const data = await res.json(); document.getElementById('status').innerText = data.message; input.value = ''; loadStorage(); } catch (e) { document.getElementById('status').innerText = "上傳失敗: " + e; } }
async function reimport() { document.getElementById('status').innerText = "正在解析雲端 PDF,請稍候(可能需要 1-2 分鐘)..."; try { const res = await fetch('/api/reimport', { method: 'POST' }); const contentType = res.headers.get('content-type') || ''; if (!res.ok || !contentType.includes('application/json')) { document.getElementById('status').innerText = `同步失敗: 伺服器回應異常 (HTTP ${res.status})。可能是超時,請稍後再試一次。`; return; } const data = await res.json(); document.getElementById('status').innerText = data.message; if (data.success) { loadUnits(); loadStorage(); } } catch (e) { document.getElementById('status').innerText = "同步失敗: " + e; } }
// ===== 雲端 Storage 管理 ===== async function loadStorage() { const container = document.getElementById('storageList'); try { const res = await fetch('/api/storage'); const files = await res.json(); if (files.error) { container.innerHTML = `<p style="color:var(--error);">載入失敗: ${files.error}</p>`; return; } if (files.length === 0) { container.innerHTML = '<p style="color: var(--text-muted);">雲端沒有任何 PDF 檔案。</p>'; return; } container.innerHTML = files.map(f => { const safeName = f.name.replace(/'/g, "\\'").replace(/"/g, '"'); const baseName = f.name.replace(/\.pdf$/i, ''); const sizeKB = f.size ? (f.size / 1024).toFixed(1) + ' KB' : ''; return ` <div id="sf-${safeName}" style="display:flex; justify-content:space-between; align-items:center; padding:10px 16px; border:1px solid var(--border-color); border-radius:10px; margin-bottom:6px; background: var(--card-bg, #f9fafb);"> <span class="sf-label">📎 <strong>${f.name}</strong> <span style="color:var(--text-muted); font-size:0.85rem;">${sizeKB}</span> <br><span style="color:var(--text-muted); font-size:0.8rem;">→ 同步後產生:${baseName.toUpperCase()}</span> </span> <span class="sf-edit" style="display:none;"> <input type="text" value="${baseName}" style="padding:4px 8px; border:1px solid var(--border-color); border-radius:6px; font-size:0.9rem; width:160px;"> <span style="color:var(--text-muted); font-size:0.85rem;">.pdf</span> <button onclick="confirmStorageRename('${safeName}', this)" class="btn" style="background:#dcfce7; color:#16a34a; padding:5px 10px; font-size:0.8rem; margin-left:4px;">✓</button> <button onclick="cancelStorageRename('${safeName}')" class="btn" style="background:#f3f4f6; color:#6b7280; padding:5px 10px; font-size:0.8rem; margin-left:2px;">✕</button> </span> <span class="sf-actions"> <button onclick="startStorageRename('${safeName}')" class="btn" style="background:#dbeafe; color:#2563eb; padding:5px 12px; font-size:0.8rem; margin-right:4px;">✏️ 更名</button> <button onclick="deleteStorageFile('${safeName}')" class="btn" style="background:#fee2e2; color:#dc2626; padding:5px 12px; font-size:0.8rem;">🗑 刪除</button> </span> </div>`; }).join(''); } catch (e) { container.innerHTML = '<p style="color:var(--error);">載入失敗: ' + e + '</p>'; } }
function startStorageRename(filename) { const row = document.getElementById('sf-' + filename); if (!row) return; row.querySelector('.sf-label').style.display = 'none'; row.querySelector('.sf-actions').style.display = 'none'; row.querySelector('.sf-edit').style.display = 'inline-flex'; const input = row.querySelector('.sf-edit input'); input.focus(); input.select(); }
function cancelStorageRename(filename) { const row = document.getElementById('sf-' + filename); if (!row) return; row.querySelector('.sf-label').style.display = ''; row.querySelector('.sf-actions').style.display = ''; row.querySelector('.sf-edit').style.display = 'none'; }
async function confirmStorageRename(filename, btn) { const row = document.getElementById('sf-' + filename); if (!row) return; const input = row.querySelector('.sf-edit input'); let newName = input.value.trim(); if (!newName) return alert('檔名不能為空'); if (!newName.toLowerCase().endsWith('.pdf')) newName += '.pdf'; if (newName === filename) { cancelStorageRename(filename); return; }
document.getElementById('status').innerText = `正在更名...`; try { const res = await fetch('/api/storage/' + encodeURIComponent(filename), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ new_name: newName }) }); const data = await res.json(); document.getElementById('status').innerText = data.message; if (data.success) loadStorage(); } catch (e) { document.getElementById('status').innerText = "更名失敗: " + e; } }
async function deleteStorageFile(filename) { if (!confirm(`確定要從雲端刪除「${filename}」嗎?\n(僅刪除 PDF 檔案,不影響已匯入的單元資料)`)) return; document.getElementById('status').innerText = `正在刪除 ${filename}...`; try { const res = await fetch('/api/storage/' + encodeURIComponent(filename), { method: 'DELETE' }); const data = await res.json(); document.getElementById('status').innerText = data.message; loadStorage(); } catch (e) { document.getElementById('status').innerText = "刪除失敗: " + e; } }
// ===== 已匯入單元管理 ===== async function loadUnits() { const container = document.getElementById('unitList'); try { const res = await fetch('/api/all_words'); const words = await res.json(); const unitMap = {}; words.forEach(w => { if (!unitMap[w.unit]) unitMap[w.unit] = 0; unitMap[w.unit]++; }); const units = Object.keys(unitMap).sort(); if (units.length === 0) { container.innerHTML = '<p style="color: var(--text-muted);">尚未匯入任何單元。</p>'; return; } container.innerHTML = units.map(u => { const safeU = u.replace(/'/g, "\\'").replace(/"/g, '"'); return ` <div id="unit-row-${safeU}" style="display:flex; justify-content:space-between; align-items:center; padding:12px 16px; border:1px solid var(--border-color); border-radius:10px; margin-bottom:8px;"> <span class="unit-label"><strong>${u}</strong> <span style="color:var(--text-muted); font-size:0.9rem;">(${unitMap[u]} 個單字)</span></span> <span class="unit-edit" style="display:none;"> <input type="text" value="${u}" style="padding:4px 8px; border:1px solid var(--border-color); border-radius:6px; font-size:0.95rem; width:200px;"> <button onclick="confirmRename('${safeU}', this)" class="btn" style="background:#dcfce7; color:#16a34a; padding:6px 10px; font-size:0.85rem; margin-left:4px;">✓</button> <button onclick="cancelRename('${safeU}')" class="btn" style="background:#f3f4f6; color:#6b7280; padding:6px 10px; font-size:0.85rem; margin-left:2px;">✕</button> </span> <span class="unit-actions"> <button onclick="startRename('${safeU}')" class="btn" style="background:#dbeafe; color:#2563eb; padding:6px 14px; font-size:0.85rem; margin-right:4px;">✏️ 更名</button> <button onclick="deleteUnit('${safeU}')" class="btn" style="background:#fee2e2; color:#dc2626; padding:6px 14px; font-size:0.85rem;">🗑 刪除</button> </span> </div>`; }).join(''); } catch (e) { container.innerHTML = '<p style="color:var(--error);">載入失敗: ' + e + '</p>'; } }
function startRename(unitName) { const row = document.getElementById('unit-row-' + unitName); if (!row) return; row.querySelector('.unit-label').style.display = 'none'; row.querySelector('.unit-actions').style.display = 'none'; row.querySelector('.unit-edit').style.display = 'inline-flex'; const input = row.querySelector('.unit-edit input'); input.focus(); input.select(); }
function cancelRename(unitName) { const row = document.getElementById('unit-row-' + unitName); if (!row) return; row.querySelector('.unit-label').style.display = ''; row.querySelector('.unit-actions').style.display = ''; row.querySelector('.unit-edit').style.display = 'none'; }
async function confirmRename(unitName, btn) { const row = document.getElementById('unit-row-' + unitName); if (!row) return; const input = row.querySelector('.unit-edit input'); const newName = input.value.trim(); if (!newName) return alert('名稱不能為空'); if (newName === unitName) { cancelRename(unitName); return; }
document.getElementById('status').innerText = `正在更名...`; try { const res = await fetch('/api/units/' + encodeURIComponent(unitName), { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ new_name: newName }) }); const data = await res.json(); document.getElementById('status').innerText = data.message; if (data.success) loadUnits(); } catch (e) { document.getElementById('status').innerText = "更名失敗: " + e; } }
async function deleteUnit(unitName) { if (!confirm(`確定要刪除「${unitName}」嗎?(僅刪除資料庫中的單字資料)`)) return; document.getElementById('status').innerText = `正在刪除 ${unitName}...`; try { const res = await fetch('/api/units/' + encodeURIComponent(unitName), { method: 'DELETE' }); const data = await res.json(); document.getElementById('status').innerText = data.message; loadUnits(); } catch (e) { document.getElementById('status').innerText = "刪除失敗: " + e; } }
// 頁面載入時同時載入兩個區塊 loadStorage(); loadUnits(); </script></body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444<!DOCTYPE html><html lang="zh-TW">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>英文單字小學堂 Web</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head>
<body> <div class="container"> <header class="card"> <div> <h1>📚 單字小學堂</h1> <p style="color: var(--text-muted); margin-top: 5px;">您的專屬雲端學習助手</p> </div>
<div class="controls"> <div class="user-select-wrapper"> <span style="font-size: 1.2rem; margin-right: 5px;">👤</span> <select id="currentUser" onchange="updateLinks()"> <option value="訪客">訪客</option> </select> </div> <a href="{{ url_for('import_page') }}" class="btn btn-primary">匯入單字</a> <a href="{{ url_for('manage_users_page') }}" class="btn btn-secondary">⚙️ 設定</a> <a href="{{ url_for('admin_panel') }}" class="btn btn-secondary">🔐 後台管理</a> </div> </header>
<!-- 頁籤導覽列 --> <div class="tabs-container"> <button class="tab-btn active" onclick="switchTab('units-tab')">📖 學習單元</button> <button class="tab-btn" onclick="switchTab('progress-tab')">📅 複習進度表</button> </div>
<!-- 學習單元分頁 --> <div id="units-tab" class="tab-content active-content"> <section class="card"> <h2 style="display: flex; justify-content: space-between; align-items: center;"> 📖 學習單元 <span style="font-size: 0.9rem; font-weight: normal; color: var(--text-muted);"> 共 {{ units|length }} 個單元 </span> </h2>
<div id="unit-list"> {% if units %} {% for unit in units %} <div class="unit-item" style="flex-direction: column; align-items: start; gap: 15px;"> <div class="unit-name" style="border-bottom: 1px solid var(--border-color); width: 100%; padding-bottom: 10px; margin-bottom: 5px;"> {{ unit }}</div> <div style="display: flex; gap: 8px; flex-wrap: wrap;"> <a href="#" onclick="goStudy('{{ unit }}')" class="btn btn-secondary">📖 單字卡</a> <a href="#" onclick="goQuiz('{{ unit }}', 'quiz')" class="btn btn-primary" style="background-color: #6366f1;">選中文</a> <a href="#" onclick="goQuiz('{{ unit }}', 'reverse')" class="btn btn-primary" style="background-color: #8b5cf6;">選英文</a> <a href="#" onclick="goQuiz('{{ unit }}', 'spelling')" class="btn btn-primary" style="background-color: #ec4899;">拼字</a> </div> </div> {% endfor %} {% else %} <div style="text-align: center; padding: 40px; color: var(--text-muted);"> <p style="font-size: 4rem; margin: 0;">📭</p> <p>目前還沒有單字資料庫</p> <a href="{{ url_for('import_page') }}" class="btn btn-primary" style="margin-top: 10px;">立即匯入 PDF</a> </div> {% endif %} </div> </section> </div>
<!-- 暑期複習進度分頁 --> <div id="progress-tab" class="tab-content"> <section class="card" style="padding: 24px;"> <div style="display: flex; justify-content: space-between; align-items: center; border-bottom: 2px solid var(--border-color); padding-bottom: 10px; margin-bottom: 20px; flex-wrap: wrap; gap: 15px;"> <h2 style="margin: 0; border: none; padding: 0;" id="review-table-title">📅 複習進度表</h2> <div class="controls" style="margin: 0;"> <span style="font-weight: 600; color: var(--text-muted); font-size: 0.95rem;">學生篩選:</span> <div class="user-select-wrapper" style="padding: 2px 10px;"> <span style="font-size: 1.1rem; margin-right: 5px;">👤</span> <select id="progressUserFilter" onchange="renderMatrixProgress()"> <option value="">👤 載入中...</option> </select> </div> </div> </div>
<div class="progress-legend" style="margin-bottom: 20px;"> <div class="legend-item"><span class="legend-box badge-quiz" style="border-radius: 4px; border: none; width: 14px; height: 14px;"></span>選中文</div> <div class="legend-item"><span class="legend-box badge-reverse" style="border-radius: 4px; border: none; width: 14px; height: 14px;"></span>選英文</div> <div class="legend-item"><span class="legend-box badge-spelling" style="border-radius: 4px; border: none; width: 14px; height: 14px;"></span>拼字</div> <div class="legend-item" style="margin-left: auto; font-size: 0.9rem;"> <span style="color: var(--primary-color); font-weight: bold;">⭐ 達標標準:正確率 >= 90%</span> </div> </div>
<!-- 大表格矩陣滾動容器 --> <div class="table-responsive matrix-scroll-container"> <table class="progress-table matrix-table"> <thead> <tr id="matrix-header-row"> <th class="sticky-col-header">日期 \ 單元</th> <!-- JS 動態插入單元名稱 --> </tr> </thead> <tbody id="matrix-table-body"> <tr> <td colspan="100%" style="text-align: center; padding: 60px; color: var(--text-muted);"> ⏳ 正在載入進度數據並生成複習表,請稍候... </td> </tr> </tbody> <tfoot> <tr id="matrix-footer-row" class="matrix-summary-row"> <td class="sticky-col-header" style="font-weight: 700; background-color: #f1f5f9;">Summary</td> <!-- JS 動態插入各單元 Summary 統計 --> </tr> </tfoot> </table> </div> </section> </div> </div>
<script> // Load users on startup async function loadUsers() { try { const res = await fetch('/api/users'); const users = await res.json(); const select = document.getElementById('currentUser');
users.forEach(u => { const opt = document.createElement('option'); opt.value = u.name; opt.innerText = u.name; select.appendChild(opt); });
// Restore previous selection if exists const lastUser = localStorage.getItem('lastUser'); if (lastUser) { // Check if user still exists if (users.some(u => u.name === lastUser) || lastUser === "訪客") { select.value = lastUser; } } } catch (e) { console.error(e); } }
function updateLinks() { const user = document.getElementById('currentUser').value; localStorage.setItem('lastUser', user); }
function goStudy(unit) { const user = document.getElementById('currentUser').value; window.location.href = `/study/${unit}?user=${encodeURIComponent(user)}`; }
function goQuiz(unit, mode) { const user = document.getElementById('currentUser').value; window.location.href = `/quiz/${mode}/${unit}?user=${encodeURIComponent(user)}`; }
// Tab 切換與進度表資料拉取邏輯 function switchTab(tabId) { const btns = document.querySelectorAll('.tab-btn'); btns.forEach(btn => { if (btn.getAttribute('onclick').includes(tabId)) { btn.classList.add('active'); } else { btn.classList.remove('active'); } });
const contents = document.querySelectorAll('.tab-content'); contents.forEach(content => { if (content.id === tabId) { content.classList.add('active-content'); } else { content.classList.remove('active-content'); } });
if (tabId === 'progress-tab') { loadProgressData(); } }
let progressRawData = null;
async function loadProgressData() { const body = document.getElementById('matrix-table-body'); try { body.innerHTML = ` <tr> <td colspan="100%" style="text-align: center; padding: 60px; color: var(--text-muted);"> ⏳ 正在從 Supabase 讀取最新進度資料,請稍候... </td> </tr> `;
const res = await fetch('/api/review_progress'); const data = await res.json();
if (!data.success) { throw new Error(data.message || '無法取得複習進度'); }
progressRawData = data;
// 填入學生篩選下拉式選單 (僅包含單一學生,無 all) const filterSelect = document.getElementById('progressUserFilter'); filterSelect.innerHTML = ''; if (data.users.length === 0) { filterSelect.innerHTML = '<option value="">無學生</option>'; } else { data.users.forEach(user => { const opt = document.createElement('option'); opt.value = user; opt.innerText = `👤 ${user}`; filterSelect.appendChild(opt); }); }
// 預設篩選切換為目前登入的使用者 const currentUser = document.getElementById('currentUser').value; if (currentUser && currentUser !== "訪客" && data.users.includes(currentUser)) { filterSelect.value = currentUser; } else if (data.users.length > 0) { filterSelect.value = data.users[0]; }
renderMatrixProgress();
} catch (e) { console.error(e); body.innerHTML = ` <tr> <td colspan="100%" style="text-align: center; padding: 40px; color: var(--error);"> ❌ 載入失敗: ${e.message}。請確認 Supabase 中 \`quiz_results\` 表格是否已成功建立。 </td> </tr> `; } }
// 產生日期清單 (包含星期幾) function generateDateRange(startStr, endStr) { if (!startStr || !endStr) return []; const dates = []; const [sY, sM, sD] = startStr.split('-').map(Number); const [eY, eM, eD] = endStr.split('-').map(Number);
const start = new Date(sY, sM - 1, sD); const end = new Date(eY, eM - 1, eD); const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
for (let d = new Date(start); d <= end; d.setDate(d.getDate() + 1)) { const month = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); const ymd = `${d.getFullYear()}-${month}-${day}`; const wDay = weekDays[d.getDay()]; const isWeekend = d.getDay() === 0 || d.getDay() === 6; dates.push({ ymd: ymd, label: `${month}-${day} (${wDay})`, isWeekend: isWeekend }); } return dates; }
function renderMatrixProgress() { if (!progressRawData) return;
const selectedUser = document.getElementById('progressUserFilter').value; const { records, units, users, required_days, start_date, end_date } = progressRawData;
// 動態更新標題區間 const formatMDate = (dStr) => { if (!dStr) return ''; const parts = dStr.split('-'); if (parts.length >= 3) return `${parseInt(parts[1])}/${parseInt(parts[2])}`; return dStr; }; document.getElementById('review-table-title').innerText = `📅 複習進度表 (${formatMDate(start_date)} - ${formatMDate(end_date)})`;
const headerRow = document.getElementById('matrix-header-row'); const tbody = document.getElementById('matrix-table-body'); const footerRow = document.getElementById('matrix-footer-row');
// 1. 繪製表頭 (橫列是單元數) headerRow.innerHTML = '<th class="sticky-col-header" style="z-index: 20;">日期 \\ 單元</th>'; if (units.length === 0) { headerRow.innerHTML += '<th>無單元資料</th>'; tbody.innerHTML = `<tr><td colspan="2" style="text-align: center; padding: 40px; color: var(--text-muted);">目前系統中沒有符合條件的複習單元。</td></tr>`; footerRow.innerHTML = '<td class="sticky-col-header" style="font-weight: 700; background-color: #f1f5f9;">Summary</td><td>-</td>'; return; }
if (!selectedUser || selectedUser === "") { tbody.innerHTML = `<tr><td colspan="${units.length + 1}" style="text-align: center; padding: 40px; color: var(--text-muted);">請先在系統中新增學生。</td></tr>`; footerRow.innerHTML = '<td class="sticky-col-header" style="font-weight: 700; background-color: #f1f5f9;">Summary</td>' + '<td>-</td>'.repeat(units.length); return; }
units.forEach(unit => { const th = document.createElement('th'); th.innerText = unit; headerRow.appendChild(th); });
// 2. 初始化統計變數 const completedDaysMap = {}; const daysMap = {}; units.forEach(unit => { completedDaysMap[unit] = 0; daysMap[unit] = {}; });
// 建立 records 快取並過濾該學生合格記錄 const recordsMap = {}; records.forEach(r => { if (r.user_name !== selectedUser) { return; }
const uUnit = r.unit; const uDate = r.date; const uMode = r.mode;
if (daysMap[uUnit]) { if (!daysMap[uUnit][uDate]) { daysMap[uUnit][uDate] = { quiz: false, reverse: false, spelling: false }; } daysMap[uUnit][uDate][uMode] = true; }
if (!recordsMap[r.date]) recordsMap[r.date] = {}; if (!recordsMap[r.date][r.unit]) recordsMap[r.date][r.unit] = []; recordsMap[r.date][r.unit].push(r); });
// 計算該學生在每個單元完成複習的天數 units.forEach(unit => { let completedDays = 0; for (const dKey in daysMap[unit]) { const day = daysMap[unit][dKey]; if (day.quiz && day.reverse && day.spelling) { completedDays++; } } completedDaysMap[unit] = completedDays; });
// 3. 生成日期行 const dateRange = generateDateRange(start_date, end_date); tbody.innerHTML = '';
if (dateRange.length === 0) { tbody.innerHTML = `<tr><td colspan="${units.length + 1}" style="text-align: center; padding: 40px; color: var(--text-muted);">設定的日期區間無效。</td></tr>`; } else { dateRange.forEach(d => { const tr = document.createElement('tr'); if (d.isWeekend) { tr.className = 'weekend-row'; }
// 日期列 const tdDate = document.createElement('td'); tdDate.className = 'sticky-col-header date-col'; tdDate.innerText = d.label; tr.appendChild(tdDate);
// 各單元格 units.forEach(unit => { const tdUnit = document.createElement('td'); tdUnit.className = 'matrix-cell'; const dayRecords = (recordsMap[d.ymd] && recordsMap[d.ymd][unit]) ? recordsMap[d.ymd][unit] : []; if (dayRecords.length > 0) { dayRecords.forEach(r => { const modeMap = { "quiz": "中", "reverse": "英", "spelling": "拼" }; const modeText = modeMap[r.mode] || r.mode; const badgeClass = `badge-${r.mode}`; const badge = document.createElement('div'); badge.className = `progress-badge ${badgeClass}`; badge.innerText = modeText; badge.title = `${r.unit} (${r.mode}) - 正確率 ${r.accuracy}%`; badge.style.textAlign = 'center'; tdUnit.appendChild(badge); }); } tr.appendChild(tdUnit); });
tbody.appendChild(tr); }); }
// 4. 繪製最底下的 Summary 橫列 footerRow.innerHTML = '<td class="sticky-col-header" style="font-weight: 700; background-color: #f1f5f9; position: sticky; left:0; z-index: 10;">Summary</td>'; units.forEach(unit => { const tdSummary = document.createElement('td'); const daysCount = completedDaysMap[unit] || 0; const displayDays = Math.min(daysCount, required_days); const isCompleted = daysCount >= required_days; tdSummary.className = 'matrix-footer-cell'; let statusBadge = ''; if (isCompleted) { statusBadge = '<span class="unit-status-pill completed" style="padding: 2px 6px; font-size: 0.7rem; margin-top: 4px; display: inline-block;">🎉 達標</span>'; tdSummary.style.backgroundColor = 'rgba(34, 197, 94, 0.08)'; } else if (daysCount > 0) { statusBadge = '<span class="unit-status-pill in-progress" style="padding: 2px 6px; font-size: 0.7rem; margin-top: 4px; display: inline-block;">⏳ 進行中</span>'; } else { statusBadge = '<span class="unit-status-pill not-started" style="padding: 2px 6px; font-size: 0.7rem; margin-top: 4px; display: inline-block;">未開始</span>'; }
tdSummary.innerHTML = ` <div style="font-size: 0.85rem; font-weight: bold; color: ${isCompleted ? 'var(--success)' : 'var(--text-main)'};">${displayDays} / ${required_days} 天</div> ${statusBadge} `; footerRow.appendChild(tdSummary); }); }
loadUsers(); </script></body>
</html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758<!DOCTYPE html><html lang="zh-TW">
<head> <meta charset="UTF-8"> <title>單字列表 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <style> table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { text-align: left; padding: 12px; border-bottom: 1px solid var(--border-color); }
tr:hover { background-color: #f8fafc; } </style></head>
<body> <div class="container" style="max-width: 1000px;"> <div class="card"> <a href="{{ url_for('index') }}">← 返回主頁</a> <h1>📋 單字總覽:{{ unit }}</h1>
<table> <thead> <tr> <th>單字</th> <th>詞性</th> <th>中文解釋</th> <th>例句</th> </tr> </thead> <tbody> {% for w in words %} <tr> <td><strong>{{ w.word }}</strong></td> <td><i>{{ w.pos }}</i></td> <td>{{ w.definition }}</td> <td style="font-size: 0.9rem; color: var(--text-muted);">{{ w.sentence }}</td> </tr> {% endfor %} </tbody> </table> </div> </div></body>
</html>1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283<!DOCTYPE html><html lang="zh-TW"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>管理員登入 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <style> .login-container { display: flex; justify-content: center; align-items: center; min-height: 80vh; } .login-card { width: 100%; max-width: 400px; padding: 40px; } .form-group { margin-bottom: 20px; } .form-group label { display: block; margin-bottom: 8px; font-weight: 600; color: var(--text-main); } .form-control { width: 100%; padding: 12px; border: 1px solid var(--border-color); border-radius: 8px; font-size: 1rem; box-sizing: border-box; outline: none; transition: border-color 0.2s; } .form-control:focus { border-color: var(--primary-color); } .error-message { background-color: #fee2e2; color: #ef4444; padding: 12px; border-radius: 8px; margin-bottom: 20px; font-size: 0.9rem; font-weight: 600; border: 1px solid #fca5a5; } </style></head><body> <div class="container login-container"> <div class="card login-card"> <h1 style="text-align: center; margin-bottom: 30px;">🔐 管理員登入</h1> {% if error %} <div class="error-message"> ❌ {{ error }} </div> {% endif %}
<form method="POST" action="{{ url_for('admin_login') }}"> <div class="form-group"> <label for="username">管理員帳號</label> <input type="text" id="username" name="username" class="form-control" placeholder="請輸入帳號" required autocomplete="username"> </div> <div class="form-group"> <label for="password">管理員密碼</label> <input type="password" id="password" name="password" class="form-control" placeholder="請輸入密碼" required autocomplete="current-password"> </div> <button type="submit" class="btn btn-primary" style="width: 100%; padding: 12px; margin-top: 10px;">登入</button> </form> <div style="text-align: center; margin-top: 20px;"> <a href="/" style="color: var(--text-muted); text-decoration: none; font-size: 0.9rem;">← 返回首頁</a> </div> </div> </div></body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293<!DOCTYPE html><html lang="zh-TW">
<head> <meta charset="UTF-8"> <title>管理使用者 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head>
<body> <div class="container"> <div class="card"> <a href="{{ url_for('index') }}">← 返回主頁</a> <h1>👥 管理使用者</h1>
<div style="margin-bottom: 30px; display: flex; gap: 10px;"> <input type="text" id="userName" placeholder="輸入姓名" class="card" style="margin:0; flex:1; padding:10px;"> <button onclick="addUser()" class="btn btn-primary">新增使用者</button> </div>
<div id="userList"> <!-- Users will be loaded here --> </div> <hr style="margin: 20px 0;">
<div style="background-color: #f8f9fa; padding: 15px; border-radius: 8px;"> <h3>📧 Email 偵錯工具</h3> <p>點擊下方按鈕,系統將嘗試向設定的收件人發送一封測試信件。</p> <button onclick="sendTestEmail()" class="btn" style="background-color: #28a745; color: white;">發送測試 Email</button> <p id="emailResult" style="margin-top: 10px; font-weight: bold;"></p> </div> </div> </div>
<script> async function sendTestEmail() { const resultP = document.getElementById('emailResult'); resultP.innerText = "發送中..."; resultP.style.color = "blue"; try { const res = await fetch('/api/test_email', { method: 'POST' }); const data = await res.json(); if (data.success) { resultP.innerText = "✅ 發送成功! " + (data.message || ""); resultP.style.color = "green"; } else { resultP.innerText = "❌ 發送失敗: " + data.message; resultP.style.color = "red"; } } catch (e) { resultP.innerText = "❌ 請求錯誤: " + e; resultP.style.color = "red"; } }
async function loadUsers() { const res = await fetch('/api/users'); const users = await res.json(); const list = document.getElementById('userList'); list.innerHTML = users.map(u => ` <div class="card" style="display: flex; justify-content: space-between; align-items: center; padding: 10px 20px;"> <span>${u.name}</span> <button onclick="deleteUser(${u.id})" class="btn" style="color:red">刪除</button> </div> `).join(''); }
async function addUser() { const name = document.getElementById('userName').value; if (!name) return; await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }) }); document.getElementById('userName').value = ""; loadUsers(); }
async function deleteUser(id) { if (!confirm('確定刪除?')) return; await fetch(`/api/users/${id}`, { method: 'DELETE' }); loadUsers(); }
loadUsers(); </script></body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288<!DOCTYPE html><html lang="zh-TW">
<head> <meta charset="UTF-8"> <title>測試模式 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <style> .options { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-top: 20px; }
.quiz-btn { padding: 20px; font-size: 1.2rem; background: #f1f5f9; border: 2px solid #e2e8f0; border-radius: 8px; cursor: pointer; }
.quiz-btn:hover { background: #e2e8f0; }
.correct { background: #dcfce7 !important; border-color: #22c55e !important; }
.wrong { background: #fee2e2 !important; border-color: #ef4444 !important; } </style></head>
<body> <div class="container"> <div class="card" id="quiz-container"> <h2 id="unit-title">正在載入試題...</h2> <div id="progress" style="margin-bottom: 10px;"></div>
<div id="question-box" class="word-card"> <div id="target-word" class="word-main">---</div> <button onclick="playAudio()" class="btn">🔊 發音</button> </div>
<div class="options" id="options-box"></div>
<div id="feedback" style="margin-top: 20px; font-weight: bold; text-align: center;"></div> </div>
<div id="result-container" class="card" style="display: none; text-align: center;"> <h1>🎉 測驗完成!</h1> <h2 id="final-score">得分:0 / 0</h2> <p id="email-status">正在發送成績單至您的信箱...</p> <a href="/" class="btn btn-primary">回首頁</a> </div> </div>
<script> const unit = "{{ unit }}"; // Parse user from URL const urlParams = new URLSearchParams(window.location.search); const currentUser = urlParams.get('user') || "訪客";
let words = []; let currentIndex = 0; let score = 0; let wrongWords = [];
async function init() { const res = await fetch(`/api/words/${unit}`); words = await res.json(); shuffle(words); renderQuestion(); }
function shuffle(array) { array.sort(() => Math.random() - 0.5); }
const mode = "{{ mode }}"; // 'quiz', 'reverse', 'spelling'
// Define mode logic const isSpelling = mode === 'spelling'; const isReverse = mode === 'reverse';
function renderQuestion() { if (currentIndex >= words.length) return finishQuiz();
const target = words[currentIndex]; document.getElementById('unit-title').innerText = `正在測試 (${modeText(mode)}):${unit}`; document.getElementById('progress').innerText = `進度:${currentIndex + 1} / ${words.length}`;
// 1. Setup Question Display const targetEl = document.getElementById('target-word');
if (isSpelling) { targetEl.innerText = "請聽音拼寫..."; targetEl.style.fontSize = "2rem";
// Explicitly re-render the spelling box to update the hint const qBox = document.getElementById('question-box'); qBox.innerHTML = ` <div id="target-word" class="word-main" style="font-size: 2rem; margin-bottom: 20px;">請聽音拼寫...</div> <div class="word-card" style="padding: 0;"> <button onclick="playAudio()" class="btn btn-primary" style="margin-bottom:15px;">🔊 播放發音</button> <div style="font-size: 1.5rem; margin-bottom: 20px; color: #666;">提示:${target.definition}</div> <input type="text" id="spellingInput" value="" style="font-size: 2rem; padding: 10px; width: 80%; text-align: center; border: 2px solid #ccc; border-radius: 8px;" placeholder="輸入英文單字" autocomplete="off" onkeypress="handleSpellingEnter(event)"> <button onclick="checkSpelling()" class="btn btn-success" style="margin-top: 10px; display: block; margin: 10px auto;">送出答案</button> </div> `;
// Focus input setTimeout(() => document.getElementById('spellingInput').focus(), 100); playAudio(); // Auto play } else { // Restore standard question box if coming from spelling mode or ensuring structure if (document.getElementById('spellingInput') || !document.getElementById('audio-btn')) { document.getElementById('question-box').innerHTML = ` <div id="target-word" class="word-main">---</div> <button id="audio-btn" onclick="playAudio()" class="btn">🔊 發音</button> `; }
// Re-select elements after potential innerHTML rewrite const tEl = document.getElementById('target-word'); const audioBtn = document.getElementById('audio-btn');
if (isReverse) { // Reverse: Show Chinese, Select English tEl.innerText = target.definition; if (audioBtn) audioBtn.style.display = 'none'; // Hide audio } else { // Standard: Show English, Select Chinese tEl.innerText = target.word; if (audioBtn) audioBtn.style.display = 'inline-block'; // Show audio } }
document.getElementById('feedback').innerText = "";
// 2. Setup Options (Skip for spelling) if (!isSpelling) { // Reset Options Box const box = document.getElementById('options-box'); box.innerHTML = ""; box.style.display = "grid";
let options = [target]; while (options.length < 4 && words.length >= 4) { const rand = words[Math.floor(Math.random() * words.length)]; if (!options.find(o => o.word === rand.word)) options.push(rand); } shuffle(options);
options.forEach(opt => { const btn = document.createElement('button'); btn.className = 'quiz-btn'; // Reverse: Show Word. Standard: Show Def btn.innerText = isReverse ? opt.word : opt.definition; btn.onclick = () => checkAnswer(opt, target, btn); box.appendChild(btn); }); } else { document.getElementById('options-box').style.display = "none"; } }
function handleSpellingEnter(e) { if (e.key === "Enter") checkSpelling(); }
async function checkSpelling() { const input = document.getElementById('spellingInput'); const userVal = input.value.trim(); if (!userVal) return;
input.disabled = true; const target = words[currentIndex];
if (userVal.toLowerCase() === target.word.toLowerCase()) { score++; input.style.borderColor = "green"; input.style.backgroundColor = "#dcfce7"; document.getElementById('feedback').innerHTML = "<span style='color:green'>正確! Excellent!</span>"; } else { wrongWords.push(target); input.style.borderColor = "red"; input.style.backgroundColor = "#fee2e2"; document.getElementById('feedback').innerHTML = `<span style='color:red'>答錯了,正確是:<strong>${target.word}</strong></span>`; }
setTimeout(() => { currentIndex++; // Restore default structure for next question if needed if (!isSpelling) document.getElementById('question-box').innerHTML = `<div id="target-word" class="word-main">---</div><button onclick="playAudio()" class="btn">🔊 發音</button>`; renderQuestion(); }, 2000); }
async function checkAnswer(selected, correct, btn) { const btns = document.querySelectorAll('.quiz-btn'); btns.forEach(b => b.disabled = true);
if (selected.word === correct.word) { score++; btn.classList.add('correct'); document.getElementById('feedback').innerHTML = "<span style='color:green'>正確! Excellent!</span>"; } else { wrongWords.push(correct); btn.classList.add('wrong'); // Highlight correct one logic btns.forEach(b => { if (isReverse ? (b.innerText === correct.word) : (b.innerText === correct.definition)) { b.classList.add('correct'); } }); document.getElementById('feedback').innerHTML = `<span style='color:red'>答錯了!</span>`; }
setTimeout(() => { currentIndex++; renderQuestion(); }, 1500); }
function modeText(m) { if (m === 'reverse') return "選英文"; if (m === 'spelling') return "拼字"; return "選中文"; }
async function playAudio() { const word = words[currentIndex].word; try { const res = await fetch(`/api/tts?text=${encodeURIComponent(word)}`); const data = await res.json(); if (data.url) new Audio(data.url).play(); } catch (e) { console.error('TTS error:', e); } }
async function finishQuiz() { document.getElementById('quiz-container').style.display = 'none'; document.getElementById('result-container').style.display = 'block'; document.getElementById('final-score').innerText = `得分:${score} / ${words.length}`;
// Show who took the quiz const userDisplay = document.createElement('h3'); userDisplay.innerText = `受試者:${currentUser}`; document.getElementById('final-score').after(userDisplay);
// Send report try { await fetch('/api/send_report', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ unit: unit, score: score, total: words.length, mode: modeText(mode), user_name: currentUser, // Pass user name to backend wrong_words_list: wrongWords }) }); document.getElementById('email-status').innerText = "✅ 成績單已寄送!"; } catch (e) { document.getElementById('email-status').innerText = "❌ 郵件發送失敗"; } }
init(); </script></body>
</html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697<!DOCTYPE html><html lang="zh-TW">
<head> <meta charset="UTF-8"> <title>單字卡模式 - 英文單字小學堂</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head>
<body> <div class="container"> <div class="card"> <a href="{{ url_for('index') }}">← 返回主頁</a> <h2 id="unit-title">正在載入學習單元...</h2> <div id="progress" style="margin-bottom: 20px;"></div>
<div class="card word-card"> <div id="word" class="word-main">---</div> <div id="pos" class="pos">---</div> <div id="definition" class="definition">---</div> <div style="margin-top: 20px;"> <button onclick="playAudio('word')" class="btn">🔊 唸單字</button> </div> <hr style="margin: 30px 0; border: none; border-top: 1px solid #eee;"> <p id="sentence" style="font-weight: 500; min-height: 50px; font-size: 1.15rem; line-height: 1.8;">---</p> <button onclick="playAudio('sentence')" class="btn">🗣️ 唸例句</button> </div>
<div style="display: flex; justify-content: space-between; margin-top: 20px;"> <button onclick="prevWord()" class="btn">上一個</button> <button onclick="nextWord()" class="btn btn-primary">下一個</button> </div> </div> </div>
<script> const unit = "{{ unit }}"; let words = []; let currentIndex = 0;
async function init() { const res = await fetch(`/api/words/${unit}`); words = await res.json(); renderWord(); }
function renderWord() { if (words.length === 0) return; const w = words[currentIndex]; document.getElementById('unit-title').innerText = `學習單元:${unit}`; document.getElementById('progress').innerText = `進度:${currentIndex + 1} / ${words.length}`; document.getElementById('word').innerText = w.word; document.getElementById('pos').innerText = w.pos; document.getElementById('definition').innerText = w.definition; // 將中文部分換行顯示 const sentenceEl = document.getElementById('sentence'); const raw = w.sentence || ''; // 找到中文括號或第一個中文字的位置,插入換行 const match = raw.match(/[((][\u4e00-\u9fff]/); if (match) { const idx = raw.indexOf(match[0]); sentenceEl.innerHTML = raw.substring(0, idx) + '<br>' + raw.substring(idx); } else { sentenceEl.innerText = raw; } }
function nextWord() { if (currentIndex < words.length - 1) { currentIndex++; renderWord(); } }
function prevWord() { if (currentIndex > 0) { currentIndex--; renderWord(); } }
async function playAudio(type) { const text = type === 'word' ? words[currentIndex].word : words[currentIndex].sentence; try { const res = await fetch(`/api/tts?text=${encodeURIComponent(text)}`); const data = await res.json(); if (data.url) new Audio(data.url).play(); } catch (e) { console.error('TTS error:', e); } }
init(); </script></body>
</html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930import osimport sysimport reimport timeimport jsonimport socketimport threadingfrom datetime import datetimefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom flask import Flask, render_template, request, jsonify, send_file, Response, redirect, url_for, sessionfrom werkzeug.security import generate_password_hash, check_password_hashimport asyncioimport edge_ttsimport pdfplumberfrom supabase import create_client, Client
# ==========================================# 0. Global Config (Local vs Cloud)# ==========================================CONFIG_FILE = "config.json"
def load_config(): if not os.path.exists(CONFIG_FILE): return {} try: with open(CONFIG_FILE, 'r', encoding='utf-8') as f: return json.load(f) except: return {}
# 偵測是否在 Hugging Face Spaces 執行 (通常會有 SPACE_ID)IS_CLOUD = os.environ.get("SPACE_ID") is not Nonelocal_cfg = load_config()
# --- Supabase Config ---if IS_CLOUD: SUPABASE_URL = os.environ.get("SUPABASE_URL") SUPABASE_KEY = os.environ.get("SUPABASE_KEY")else: s_cfg = local_cfg.get("supabase_settings", {}) SUPABASE_URL = s_cfg.get("url", "") SUPABASE_KEY = s_cfg.get("key", "")
if not SUPABASE_URL or not SUPABASE_KEY: print("⚠️ 警告: 缺少 Supabase 設定資訊!")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
app = Flask(__name__, template_folder=resource_path('templates'), static_folder=resource_path('static'))app.secret_key = 'your_secret_key_here'
# ==========================================# 1. Database Manager (Supabase Version)# ==========================================class DatabaseManager: def __init__(self): # Tables should be manually created in Supabase Dashboard for best performance, # but we'll use the API for data operations. pass
def add_word(self, unit, word, pos, definition, sentence): try: data = { "unit": unit, "word": word, "pos": pos, "definition": definition, "sentence": sentence } # Use upsert based on (unit, word) unique constraint if defined in Supabase supabase.table("words").upsert(data, on_conflict="unit,word,pos").execute() except Exception as e: print(f"Supabase Add Word Error: {e}")
def clear_all_data(self): try: # Delete all rows (requires RLS policy or service role key) supabase.table("words").delete().neq("id", -1).execute() return True except Exception as e: print(f"Supabase Clear Data Error: {e}") return False
def delete_words_by_unit(self, unit_name): try: supabase.table("words").delete().eq("unit", unit_name).execute() return True except Exception as e: print(f"Supabase Delete Unit Error: {e}") return False
def rename_unit(self, old_name, new_name): try: supabase.table("words").update({"unit": new_name}).eq("unit", old_name).execute() return True except Exception as e: print(f"Supabase Rename Unit Error: {e}") return False
def get_units(self): try: response = supabase.table("words").select("unit").execute() units = sorted(list(set([row['unit'] for row in response.data]))) return units except Exception as e: print(f"Supabase Get Units Error: {e}") return []
def get_words_by_unit(self, unit_name): try: response = supabase.table("words").select("*").eq("unit", unit_name).order("id").execute() return response.data except Exception as e: print(f"Supabase Get Words Error: {e}") return []
def get_all_words(self): try: response = supabase.table("words").select("*").execute() return response.data except Exception as e: print(f"Supabase Get All Words Error: {e}") return []
# --- User APIs --- def add_user(self, name): try: supabase.table("users").insert({"name": name}).execute() return True except Exception as e: print(f"Supabase Add User Error: {e}") return False
def get_users(self): try: response = supabase.table("users").select("id, name").order("id").execute() return response.data except Exception as e: print(f"Supabase Get Users Error: {e}") return []
def delete_user(self, user_id): try: supabase.table("users").delete().eq("id", user_id).execute() except Exception as e: print(f"Supabase Delete User Error: {e}")
def add_quiz_result(self, user_name, unit, mode, score, total): try: accuracy = (score / total * 100.0) if total > 0 else 0.0 data = { "user_name": user_name, "unit": unit, "mode": mode, "score": score, "total": total, "accuracy": accuracy } supabase.table("quiz_results").insert(data).execute() return True except Exception as e: print(f"Supabase Add Quiz Result Error: {e}") return False
def get_review_progress_records(self, start_date, end_date): try: # 查詢符合日期區間的測驗結果 response = supabase.table("quiz_results") \ .select("*") \ .gte("created_at", start_date) \ .lte("created_at", end_date) \ .execute() return response.data except Exception as e: print(f"Supabase Get Review Progress Error: {e}") return []
def get_config(self, key): try: res = supabase.table("system_config").select("value").eq("key", key).execute() if res.data: return res.data[0]["value"] return None except Exception as e: print(f"Supabase Get Config Error: {e}") return None
def set_config(self, key, value): try: data = {"key": key, "value": value} supabase.table("system_config").upsert(data, on_conflict="key").execute() return True except Exception as e: print(f"Supabase Set Config Error: {e}") return False
db = DatabaseManager()
# ==========================================# 1.5. Admin Authentication & Config Helpers# ==========================================from functools import wraps
def get_admin_credentials(): env_user = os.environ.get("ADMIN_USERNAME") env_pass = os.environ.get("ADMIN_PASSWORD") if env_user and env_pass: return env_user, env_pass, True db_creds = db.get_config("admin_credentials") if db_creds: return db_creds.get("username", "admin"), db_creds.get("password", "admin123"), False default_creds = {"username": "admin", "password": "admin123"} db.set_config("admin_credentials", default_creds) return "admin", "admin123", False
def verify_admin(username, password): expected_user, expected_pass, is_env = get_admin_credentials() if username != expected_user: return False if expected_pass.startswith("pbkdf2:"): return check_password_hash(expected_pass, password) return password == expected_pass
def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not session.get('admin_logged_in'): return redirect(url_for('admin_login')) return f(*args, **kwargs) return decorated_function
@app.route('/login', methods=['GET', 'POST'])def admin_login(): if request.method == 'POST': username = request.form.get('username') password = request.form.get('password') if verify_admin(username, password): session['admin_logged_in'] = True return redirect(url_for('admin_panel')) else: return render_template('login.html', error='帳號或密碼錯誤') return render_template('login.html')
@app.route('/logout')def admin_logout(): session.pop('admin_logged_in', None) return redirect(url_for('index'))
@app.route('/admin')@login_requireddef admin_panel(): return render_template('admin.html')
@app.route('/api/admin/config', methods=['GET', 'POST'])@login_requireddef api_admin_config(): if request.method == 'GET': r_settings = db.get_config("review_settings") if not r_settings: r_settings = { "start_date": "2026-07-01", "end_date": "2026-08-31", "required_days": 2, "selected_units": [] } e_settings = db.get_config("email_settings") if not e_settings: e_settings = { "sender_email": "", "receivers": [], "enable": False } if "app_password" in e_settings: del e_settings["app_password"] config = { "review_settings": r_settings, "email_settings": e_settings } available_units = db.get_units() return jsonify({ "success": True, "config": config, "available_units": available_units }) elif request.method == 'POST': data = request.json review_settings = data.get("review_settings") email_settings = data.get("email_settings") if review_settings: db.set_config("review_settings", review_settings) if email_settings: existing_email = db.get_config("email_settings") or {} if "app_password" not in email_settings and "app_password" in existing_email: email_settings["app_password"] = existing_email["app_password"] db.set_config("email_settings", email_settings) return jsonify({"success": True})
@app.route('/api/admin/password', methods=['POST'])@login_requireddef api_admin_password(): data = request.json old_password = data.get("old_password") new_password = data.get("new_password") expected_user, expected_pass, is_env = get_admin_credentials() if is_env: return jsonify({"success": False, "message": "環境變數中已設定密碼,無法透過網頁修改"}) if not verify_admin(expected_user, old_password): return jsonify({"success": False, "message": "舊密碼不正確"}) db.set_config("admin_credentials", { "username": expected_user, "password": new_password }) return jsonify({"success": True})
# ==========================================# 2. Config & Helpers# ==========================================# ==========================================# 2. Helpers# ==========================================
def get_local_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip except: return "127.0.0.1"
# ==========================================# 3. Routes# ==========================================
@app.route('/')def index(): units = db.get_units() return render_template('index.html', units=units)
@app.route('/list/<unit>')def word_list(unit): words = db.get_words_by_unit(unit) return render_template('list.html', unit=unit, words=words)
@app.route('/study/<unit>')def study_mode(unit): return render_template('study.html', unit=unit)
@app.route('/quiz/<mode>/<unit>')def quiz_mode(mode, unit): return render_template('quiz.html', mode=mode, unit=unit)
@app.route('/import_page')def import_page(): return render_template('import.html')
@app.route('/manage_users')def manage_users_page(): return render_template('manage_users.html')
# --- API Endpoints ---
@app.route('/api/words/<unit>')def api_get_words(unit): words = db.get_words_by_unit(unit) # Fix sentence spacing for w in words: if w['sentence']: w['sentence'] = w['sentence'].replace('\n', ' ') return jsonify(words)
@app.route('/api/all_words')def api_get_all_words(): words = db.get_all_words() return jsonify(words)
@app.route('/api/tts')def api_tts(): text = request.args.get('text', '') if not text: return "No text provided", 400 # Remove Chinese characters for TTS clean_text = text if "(" in clean_text: clean_text = clean_text.split("(")[0] elif "(" in clean_text: clean_text = clean_text.split("(")[0] match = re.search(r'[\u4e00-\u9fff]', clean_text) if match: clean_text = clean_text[:match.start()] clean_text = clean_text.strip() try: # Use edge-tts (Microsoft neural voice) filename = f"tts_{int(time.time()*1000)}.mp3" filepath = os.path.join("static", filename) async def _generate(): communicate = edge_tts.Communicate(clean_text, voice="en-US-AriaNeural") await communicate.save(filepath) asyncio.run(_generate()) # Cleanup old files for f in os.listdir("static"): if f.startswith("tts_") and f.endswith(".mp3"): try: f_path = os.path.join("static", f) if time.time() - os.path.getmtime(f_path) > 60: os.remove(f_path) except: pass return jsonify({"url": f"/static/{filename}"}) except Exception as e: return jsonify({"error": str(e)}), 500
@app.route('/api/upload', methods=['POST'])def api_upload(): files = request.files.getlist('file') if not files or all(f.filename == '' for f in files): return jsonify({"success": False, "message": "No file selected"}) uploaded = [] errors = [] for file in files: if not file or file.filename == '': continue if not file.filename.lower().endswith('.pdf'): errors.append(f"{file.filename}: 非 PDF 檔案") continue try: file_content = file.read() supabase.storage.from_("pdfs").upload( path=file.filename, file=file_content, file_options={"upsert": "true"} ) uploaded.append(file.filename) except Exception as e: errors.append(f"{file.filename}: {e}") msg_parts = [] if uploaded: msg_parts.append(f"已上傳 {len(uploaded)} 個檔案: {', '.join(uploaded)}") if errors: msg_parts.append(f"失敗: {'; '.join(errors)}") return jsonify({"success": len(uploaded) > 0, "message": ' | '.join(msg_parts) or "No files processed"})
@app.route('/api/storage', methods=['GET'])def api_list_storage(): try: res = supabase.storage.from_("pdfs").list() files = [{"name": f['name'], "size": f.get('metadata', {}).get('size', 0)} for f in res if f['name'].lower().endswith('.pdf')] return jsonify(files) except Exception as e: return jsonify({"error": str(e)}), 500
@app.route('/api/storage/<path:filename>', methods=['DELETE'])def api_delete_storage(filename): try: supabase.storage.from_("pdfs").remove([filename]) return jsonify({"success": True, "message": f"已從雲端刪除 {filename}"}) except Exception as e: return jsonify({"success": False, "message": str(e)})
@app.route('/api/storage/<path:filename>', methods=['PUT'])def api_rename_storage(filename): try: data = request.json new_name = data.get('new_name', '').strip() if not new_name: return jsonify({"success": False, "message": "新檔名不能為空"}) if not new_name.lower().endswith('.pdf'): new_name += '.pdf' if new_name == filename: return jsonify({"success": True, "message": "檔名未變更"}) # Supabase Storage 沒有 rename API,需要下載→上傳新名→刪除舊檔 file_content = supabase.storage.from_("pdfs").download(filename) supabase.storage.from_("pdfs").upload( path=new_name, file=file_content, file_options={"upsert": "true"} ) supabase.storage.from_("pdfs").remove([filename]) return jsonify({"success": True, "message": f"已將「{filename}」更名為「{new_name}」"}) except Exception as e: return jsonify({"success": False, "message": str(e)})
@app.route('/api/reimport', methods=['POST'])def api_reimport(): try: count = 0 file_list = [] duplicates = []
# 1. Check Supabase Storage 'pdfs' bucket try: res = supabase.storage.from_("pdfs").list() for f in res: if f['name'].lower().endswith('.pdf'): file_list.append({"name": f['name'], "source": "supabase"}) except Exception as e: print(f"Supabase Storage List Error: {e}")
# 2. Check local 'data' folder (for local dev) data_dir = "data" if os.path.exists(data_dir): for f in os.listdir(data_dir): if f.lower().endswith(".pdf"): file_list.append({"name": f, "source": "local"})
if not file_list: return jsonify({"success": False, "message": "No PDF files found in Supabase Storage or local data folder."})
for item in file_list: filename = item['name'] base_name = os.path.splitext(filename)[0] unit_name = base_name.upper() # Delete only this unit's existing words before reimporting db.delete_words_by_unit(unit_name)
# Fetch PDF content if item['source'] == "supabase": file_content = supabase.storage.from_("pdfs").download(filename) # pdfplumber needs a file-like object import io pdf_file = io.BytesIO(file_content) else: pdf_file = os.path.join(data_dir, filename)
# Collect all words for batch upsert batch = [] with pdfplumber.open(pdf_file) as pdf: for page in pdf.pages: table = page.extract_table() if table: for row in table: if not row or len(row) < 5: continue # 跳過任一欄位為空的列(如標題列) if not all(cell and cell.strip() for cell in row[:5]): continue cell_text = row[1].strip() if cell_text == "Word" or "單字" in cell_text: continue batch.append({ "unit": unit_name, "word": row[1].strip(), "pos": row[2].strip() if row[2] else "", "definition": row[3].strip() if row[3] else "", "sentence": row[4].strip().replace("\n", " ") if row[4] else "" }) # Deduplicate by (unit, word) — keep last occurrence, track duplicates seen = {} for item_data in batch: key = (item_data["unit"], item_data["word"], item_data["pos"]) if key in seen: duplicates.append(f" • {item_data['word']} ({item_data['pos']}) [{item_data['unit']}]") seen[key] = item_data batch = list(seen.values()) # Batch upsert (one API call per unit instead of per word) if batch: supabase.table("words").upsert(batch, on_conflict="unit,word,pos").execute() count += len(batch) msg = f"已匯入 {count} 個單字,來自 {len(file_list)} 個檔案。" if duplicates: msg += f"\n⚠️ 發現 {len(duplicates)} 個重複單字(已自動去重):\n" + "\n".join(duplicates) return jsonify({"success": True, "message": msg}) except Exception as e: return jsonify({"success": False, "message": str(e)})
@app.route('/api/users', methods=['GET'])def api_get_users(): return jsonify(db.get_users())
@app.route('/api/users', methods=['POST'])def api_add_user(): data = request.json name = data.get("name", "").strip() if not name: return jsonify({"success": False, "message": "Empty name"}) if db.add_user(name): return jsonify({"success": True}) return jsonify({"success": False, "message": "Duplicate or error"})
@app.route('/api/users/<int:user_id>', methods=['DELETE'])def api_delete_user(user_id): db.delete_user(user_id) return jsonify({"success": True})
@app.route('/api/units/<path:unit_name>', methods=['DELETE'])def api_delete_unit(unit_name): try: db.delete_words_by_unit(unit_name) # Also try to remove the PDF from Supabase Storage # unit_name is now directly the uppercase filename, e.g. "WEEK58" -> "week58.pdf" pdf_name = unit_name.lower() + ".pdf" try: supabase.storage.from_("pdfs").remove([pdf_name]) except Exception as e: print(f"Storage delete note: {e}") return jsonify({"success": True, "message": f"已刪除 {unit_name}"}) except Exception as e: return jsonify({"success": False, "message": str(e)})
@app.route('/api/units/<path:unit_name>', methods=['PUT'])def api_rename_unit(unit_name): try: data = request.json new_name = data.get('new_name', '').strip() if not new_name: return jsonify({"success": False, "message": "新名稱不能為空"}) if new_name == unit_name: return jsonify({"success": True, "message": "名稱未變更"}) if db.rename_unit(unit_name, new_name): return jsonify({"success": True, "message": f"已將「{unit_name}」更名為「{new_name}」"}) else: return jsonify({"success": False, "message": "更名失敗"}) except Exception as e: return jsonify({"success": False, "message": str(e)})
# Gmail API Helper (Global)def get_gmail_service(): import base64 from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/gmail.send'] creds = None
# 1. Check for cloud environment variable (JSON string) creds_json = os.environ.get("GMAIL_CREDENTIALS") if creds_json: try: info = json.loads(creds_json) creds = Credentials.from_authorized_user_info(info, SCOPES) print(f"[Gmail] Loaded credentials from env. expired={creds.expired}, has_refresh={bool(creds.refresh_token)}") except Exception as e: print(f"[Gmail] Error loading credentials from env: {e}")
# 2. Check for local token.json if not creds and os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) print(f"[Gmail] Loaded credentials from token.json. expired={creds.expired}, has_refresh={bool(creds.refresh_token)}")
if not creds: print("[Gmail] No credentials found.") return None
# 3. Always refresh if we have a refresh_token (don't trust expired flag) if creds.refresh_token: try: print("[Gmail] Attempting token refresh...") creds.refresh(Request()) print("[Gmail] Token refreshed successfully.") # Save refreshed token locally if not IS_CLOUD and os.path.exists('token.json'): with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) except Exception as e: print(f"[Gmail] Token refresh failed: {e}") # If refresh fails but token might still be valid, try anyway if not creds.token: print("[Gmail] No valid token available after refresh failure.") return None print("[Gmail] Will attempt to use existing token despite refresh failure.")
if not creds.token: print("[Gmail] No token available.") return None
return build('gmail', 'v1', credentials=creds)
def get_email_config(): db_email = db.get_config("email_settings") or {} sender = db_email.get("sender_email") password = db_email.get("app_password") receivers = db_email.get("receivers", []) enable_email = db_email.get("enable", False) if not sender: settings = local_cfg.get("email_settings", {}) if IS_CLOUD: sender = os.environ.get("GMAIL_USER", "WordApp") password = "oauth-token-used" receivers_raw = os.environ.get("RECEIVERS", "") receivers = [r.strip() for r in receivers_raw.split(",")] if receivers_raw else [] enable_email = os.environ.get("ENABLE_EMAIL", "true").lower() == "true" else: sender = settings.get("sender_email") password = settings.get("app_password") receivers = settings.get("receivers", []) enable_email = settings.get("enable", False) return sender, password, receivers, enable_email
def send_email_message(sender, password, receivers, subject, body_html): import base64 from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart import smtplib service = get_gmail_service() if service: msg = MIMEMultipart() msg['From'] = sender msg['Subject'] = subject msg.attach(MIMEText(body_html, 'html')) target_receivers = receivers if isinstance(receivers, list) else [receivers] msg['To'] = ", ".join(target_receivers) raw_message = base64.urlsafe_b64encode(msg.as_bytes()).decode('utf-8') message = {'raw': raw_message} sent_message = service.users().messages().send(userId="me", body=message).execute() return f"Gmail API (ID: {sent_message['id']})" elif sender and password and password != "oauth-token-used": msg = MIMEMultipart() msg['From'] = sender msg['Subject'] = subject msg.attach(MIMEText(body_html, 'html')) target_receivers = receivers if isinstance(receivers, list) else [receivers] msg['To'] = ", ".join(target_receivers) server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() server.login(sender, password) server.sendmail(sender, target_receivers, msg.as_string()) server.quit() return "SMTP Server" else: raise Exception("未設定 Gmail API OAuth,且無 SMTP 密碼,無法寄信。")
@app.route('/api/test_email', methods=['POST'])def api_test_email(): import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__)
try: sender, password, receivers, enable_email = get_email_config() if not receivers: return jsonify({"success": False, "message": "未設定收件者信箱"}) subject = "[測試] Word App Email Debug" body_html = "<h1>🎉 Email 功能測試成功!</h1><p>這是一封來自 WordApp 的測試信。</p>" method = send_email_message(sender, password, receivers, subject, body_html) return jsonify({ "success": True, "message": f"測試郵件已成功經由 {method} 送出至:{', '.join(receivers)}" }) except Exception as e: logger.exception("Test Email Failed") return jsonify({"success": False, "message": str(e)})
@app.route('/api/send_report', methods=['POST'])def send_report(): data = request.json unit_name = data.get('unit') score = data.get('score') total = data.get('total') mode = data.get('mode') user_name = data.get('user_name', '訪客') wrong_words_list = data.get('wrong_words_list', [])
# 儲存測驗結果至資料庫 mode_mapping = { "選中文": "quiz", "選英文": "reverse", "拼字": "spelling" } db_mode = mode_mapping.get(mode, "quiz") db.add_quiz_result(user_name, unit_name, db_mode, score, total)
sender, password, receivers, enable_email = get_email_config() if not enable_email: return jsonify({"success": False, "message": "Email disabled"}) if not receivers: return jsonify({"success": False, "message": "No receivers configured"}) subject = f"[單字小學堂] 測驗完成通知 - {unit_name} ({user_name})" current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
wrong_words_html = "" if wrong_words_list: rows = "" for w in wrong_words_list: definition = w.get('def') or w.get('definition', '') rows += f"<tr><td style='border:1px solid #ddd;padding:5px;'>{w['word']}</td><td style='border:1px solid #ddd;padding:5px;'>{definition}</td></tr>" wrong_words_html = f""" <h3>⚠️ 錯題檢討</h3> <table style='border-collapse:collapse; width:100%; max-width:600px;'> <tr style='background-color:#f2f2f2;'> <th style='border:1px solid #ddd;padding:8px;'>單字</th> <th style='border:1px solid #ddd;padding:8px;'>中文解釋</th> </tr> {rows} </table> """ else: wrong_words_html = "<p style='color:green'>🎉 太棒了!本次測驗沒有答錯的題目!</p>" body = f""" <html> <body> <h2>🎉 測驗完成通知</h2> <p><strong>使用者:</strong> {user_name}</p> <p><strong>時間:</strong> {current_time}</p> <p><strong>單元:</strong> {unit_name}</p> <p><strong>模式:</strong> {mode}</p> <hr> <h3>📊 成績報告</h3> <ul> <li><strong>答對題數:</strong> <span style="color:green">{score}</span></li> <li><strong>總題數:</strong> {total}</li> <li><strong>正確率:</strong> {int((score/total)*100) if total > 0 else 0}%</li> </ul> <hr> {wrong_words_html} <p>繼續加油!💪</p> </body> </html> """ def _send(): import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) try: logger.info("Sending report email in background...") method = send_email_message(sender, password, receivers, subject, body) logger.info(f"Report email sent successfully via {method}") except Exception as e: logger.exception("Email API Critical Error")
threading.Thread(target=_send, daemon=True).start() return jsonify({"success": True})
@app.route('/api/review_progress', methods=['GET'])def api_review_progress(): try: r_settings = db.get_config("review_settings") or {} config_start = r_settings.get("start_date", "2026-07-01") config_end = r_settings.get("end_date", "2026-08-31") required_days = r_settings.get("required_days", 2) selected_units = r_settings.get("selected_units", [])
start_date = f"{config_start}T00:00:00+08:00" end_date = f"{config_end}T23:59:59+08:00"
records = db.get_review_progress_records(start_date, end_date) all_units = db.get_units() if selected_units: units = [u for u in all_units if u in selected_units] else: units = all_units
users = [u['name'] for u in db.get_users()]
valid_records = [] for r in records: u_name = r.get("user_name") u_unit = r.get("unit") u_mode = r.get("mode") u_accuracy = r.get("accuracy", 0.0) created_at_str = r.get("created_at")
if u_name in users and u_unit in units and u_accuracy >= 90.0: local_date = config_start try: from datetime import datetime, timezone, timedelta dt = datetime.fromisoformat(created_at_str.replace("Z", "+00:00")) local_dt = dt.astimezone(timezone(timedelta(hours=8))) local_date = local_dt.strftime("%Y-%m-%d") except Exception as ex: print(f"Date Parse Error: {ex}") if created_at_str and len(created_at_str) >= 10: local_date = created_at_str[:10]
valid_records.append({ "user_name": u_name, "unit": u_unit, "mode": u_mode, "accuracy": u_accuracy, "date": local_date })
return jsonify({ "success": True, "units": units, "users": users, "records": valid_records, "required_days": required_days, "start_date": config_start, "end_date": config_end }) except Exception as e: return jsonify({"success": False, "message": str(e)}), 500
if __name__ == '__main__': load_config() # Create config.json if not exists ip = get_local_ip() print(f"========================================") print(f" 網頁版已啟動!") print(f" 請在瀏覽器輸入以下網址 (本機): http://localhost:5001") print(f" 請在手機/其他電腦輸入 (Wi-Fi): http://{ip}:5001") print(f"========================================") app.run(host='0.0.0.0', port=5001, debug=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418import sys
import osimport sqlite3import randomimport reimport timeimport jsonimport socketimport threadingimport smtplibfrom datetime import datetimefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipart
from flask import Flask, render_template, request, jsonify, send_file, Response, redirect, url_forfrom gtts import gTTSimport pdfplumber
def resource_path(relative_path): """ Get absolute path to resource, works for dev and for PyInstaller """ try: # PyInstaller creates a temp folder and stores path in _MEIPASS base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
app = Flask(__name__, template_folder=resource_path('templates'), static_folder=resource_path('static'))app.secret_key = 'your_secret_key_here'
# ==========================================# 1. Database Manager# ==========================================class DatabaseManager: def __init__(self, db_name="vocab.db"): self.db_name = db_name self.create_tables()
def get_connection(self): conn = sqlite3.connect(self.db_name) conn.row_factory = sqlite3.Row return conn
def create_tables(self): conn = self.get_connection() cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS words ( id INTEGER PRIMARY KEY AUTOINCREMENT, unit TEXT, word TEXT, pos TEXT, definition TEXT, sentence TEXT, correct_count INTEGER DEFAULT 0, wrong_count INTEGER DEFAULT 0, UNIQUE(unit, word) ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') conn.commit() conn.close()
def add_word(self, unit, word, pos, definition, sentence): conn = self.get_connection() try: conn.execute(''' INSERT OR IGNORE INTO words (unit, word, pos, definition, sentence) VALUES (?, ?, ?, ?, ?) ''', (unit, word, pos, definition, sentence)) conn.commit() except Exception as e: print(f"DB Error: {e}") finally: conn.close()
def clear_all_data(self): conn = self.get_connection() try: conn.execute("DELETE FROM words") conn.execute("DELETE FROM sqlite_sequence WHERE name='words'") conn.commit() return True except Exception as e: print(f"Clear Data Error: {e}") return False finally: conn.close()
def get_units(self): conn = self.get_connection() cursor = conn.execute("SELECT DISTINCT unit FROM words ORDER BY unit") units = [row[0] for row in cursor.fetchall()] conn.close() return units
def get_words_by_unit(self, unit_name): conn = self.get_connection() cursor = conn.execute("SELECT * FROM words WHERE unit = ? ORDER BY id ASC", (unit_name,)) words = [dict(row) for row in cursor.fetchall()] conn.close() return words
def get_all_words(self): conn = self.get_connection() cursor = conn.execute("SELECT * FROM words") words = [dict(row) for row in cursor.fetchall()] conn.close() return words
# --- User APIs --- def add_user(self, name): conn = self.get_connection() try: conn.execute("INSERT INTO users (name) VALUES (?)", (name,)) conn.commit() return True except sqlite3.IntegrityError: return False except Exception as e: print(f"Add User Error: {e}") return False finally: conn.close()
def get_users(self): conn = self.get_connection() cursor = conn.execute("SELECT id, name FROM users ORDER BY id") users = [{"id": row[0], "name": row[1]} for row in cursor.fetchall()] conn.close() return users
def delete_user(self, user_id): conn = self.get_connection() try: conn.execute("DELETE FROM users WHERE id = ?", (user_id,)) conn.commit() except Exception as e: print(f"Delete User Error: {e}") finally: conn.close()
db = DatabaseManager()
# ==========================================# 2. Config & Helpers# ==========================================CONFIG_FILE = "config.json"
def load_config(): if not os.path.exists(CONFIG_FILE): default_config = { "email_settings": { "enable": False, "sender_email": "abc@gmail.com", "app_password": "", "receivers": ["abc@gmail.com"] } } with open(CONFIG_FILE, 'w', encoding='utf-8') as f: json.dump(default_config, f, indent=4, ensure_ascii=False) return default_config try: with open(CONFIG_FILE, 'r', encoding='utf-8') as f: return json.load(f) except: return {}
def get_local_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip = s.getsockname()[0] s.close() return ip except: return "127.0.0.1"
# ==========================================# 3. Routes# ==========================================
@app.route('/')def index(): units = db.get_units() return render_template('index.html', units=units)
@app.route('/list/<unit>')def word_list(unit): words = db.get_words_by_unit(unit) return render_template('list.html', unit=unit, words=words)
@app.route('/study/<unit>')def study_mode(unit): return render_template('study.html', unit=unit)
@app.route('/quiz/<mode>/<unit>')def quiz_mode(mode, unit): return render_template('quiz.html', mode=mode, unit=unit)
@app.route('/import_page')def import_page(): return render_template('import.html')
@app.route('/manage_users')def manage_users_page(): return render_template('manage_users.html')
# --- API Endpoints ---
@app.route('/api/words/<unit>')def api_get_words(unit): words = db.get_words_by_unit(unit) # Fix sentence spacing for w in words: if w['sentence']: w['sentence'] = w['sentence'].replace('\n', ' ') return jsonify(words)
@app.route('/api/all_words')def api_get_all_words(): words = db.get_all_words() return jsonify(words)
@app.route('/api/tts')def api_tts(): text = request.args.get('text', '') if not text: return "No text provided", 400 # Remove Chinese characters for TTS clean_text = text if "(" in clean_text: clean_text = clean_text.split("(")[0] elif "(" in clean_text: clean_text = clean_text.split("(")[0] match = re.search(r'[\u4e00-\u9fff]', clean_text) if match: clean_text = clean_text[:match.start()] clean_text = clean_text.strip() try: tts = gTTS(text=clean_text, lang='en', tld='com') # Save to a temporary file filename = f"tts_{int(time.time()*1000)}.mp3" filepath = os.path.join("static", filename) tts.save(filepath) # Cleanup old files for f in os.listdir("static"): if f.startswith("tts_") and f.endswith(".mp3"): try: f_path = os.path.join("static", f) if time.time() - os.path.getmtime(f_path) > 60: # Delete older than 60s os.remove(f_path) except: pass return jsonify({"url": f"/static/{filename}"}) except Exception as e: return jsonify({"error": str(e)}), 500
@app.route('/api/reimport', methods=['POST'])def api_reimport(): data_dir = "data" if not os.path.exists(data_dir): return jsonify({"success": False, "message": "No data directory found"}) try: db.clear_all_data() pdf_files = [f for f in os.listdir(data_dir) if f.lower().endswith(".pdf")] count = 0 for filename in pdf_files: base_name = os.path.splitext(filename)[0] unit_name = f"單元 {base_name.upper()}" pdf_path = os.path.join(data_dir, filename) with pdfplumber.open(pdf_path) as pdf: for page in pdf.pages: table = page.extract_table() if table: for row in table: if row and len(row) >= 5 and row[1] and row[1].strip(): cell_text = row[1].strip() if cell_text == "Word" or "單字" in cell_text: continue db.add_word( unit=unit_name, word=row[1].strip(), pos=row[2].strip() if row[2] else "", definition=row[3].strip() if row[3] else "", sentence=row[4].strip().replace("\n", " ") if row[4] else "" ) count += 1 return jsonify({"success": True, "message": f"Imported {count} words from {len(pdf_files)} files."}) except Exception as e: return jsonify({"success": False, "message": str(e)})
@app.route('/api/users', methods=['GET'])def api_get_users(): return jsonify(db.get_users())
@app.route('/api/users', methods=['POST'])def api_add_user(): data = request.json name = data.get("name", "").strip() if not name: return jsonify({"success": False, "message": "Empty name"}) if db.add_user(name): return jsonify({"success": True}) return jsonify({"success": False, "message": "Duplicate or error"})
@app.route('/api/users/<int:user_id>', methods=['DELETE'])def api_delete_user(user_id): db.delete_user(user_id) return jsonify({"success": True})
@app.route('/api/send_report', methods=['POST'])def send_report(): data = request.json unit_name = data.get('unit') score = data.get('score') total = data.get('total') mode = data.get('mode') user_name = data.get('user_name', '訪客') # New field wrong_words_list = data.get('wrong_words_list', []) # New field
cfg = load_config() settings = cfg.get("email_settings", {}) if not settings.get("enable"): return jsonify({"success": False, "message": "Email disabled"}) sender = settings.get("sender_email") password = settings.get("app_password") receivers = settings.get("receivers") if not password or len(password) < 10: return jsonify({"success": False, "message": "Invalid password"}) subject = f"[單字小學堂] 測驗完成通知 - {unit_name} ({user_name})" current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
wrong_words_html = "" if wrong_words_list: rows = "" for w in wrong_words_list: # handle if 'def' key is different or missing definition = w.get('def') or w.get('definition', '') rows += f"<tr><td style='border:1px solid #ddd;padding:5px;'>{w['word']}</td><td style='border:1px solid #ddd;padding:5px;'>{definition}</td></tr>" wrong_words_html = f""" <h3>⚠️ 錯題檢討</h3> <table style='border-collapse:collapse; width:100%; max-width:600px;'> <tr style='background-color:#f2f2f2;'> <th style='border:1px solid #ddd;padding:8px;'>單字</th> <th style='border:1px solid #ddd;padding:8px;'>中文解釋</th> </tr> {rows} </table> """ else: wrong_words_html = "<p style='color:green'>🎉 太棒了!本次測驗沒有答錯的題目!</p>" body = f""" <html> <body> <h2>🎉 測驗完成通知</h2> <p><strong>使用者:</strong> {user_name}</p> <p><strong>時間:</strong> {current_time}</p> <p><strong>單元:</strong> {unit_name}</p> <p><strong>模式:</strong> {mode}</p> <hr> <h3>📊 成績報告</h3> <ul> <li><strong>答對題數:</strong> <span style="color:green">{score}</span></li> <li><strong>總題數:</strong> {total}</li> <li><strong>正確率:</strong> {int((score/total)*100) if total > 0 else 0}%</li> </ul> <hr> {wrong_words_html} <p>繼續加油!💪</p> </body> </html> """ def _send(): try: msg = MIMEMultipart() msg['From'] = sender msg['Subject'] = subject msg.attach(MIMEText(body, 'html')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(sender, password) msg['To'] = ", ".join(receivers) server.sendmail(sender, receivers, msg.as_string()) server.quit() except Exception as e: print(f"Email error: {e}")
threading.Thread(target=_send, daemon=True).start() return jsonify({"success": True})
if __name__ == '__main__': load_config() # Create config.json if not exists ip = get_local_ip() print(f"========================================") print(f" 網頁版已啟動!") print(f" 請在瀏覽器輸入以下網址 (本機): http://localhost:5000") print(f" 請在手機/其他電腦輸入 (Wi-Fi): http://{ip}:5000") print(f"========================================") app.run(host='0.0.0.0', port=5000, debug=True).gitignoreAdded+38
DockerfileAdded+20
README.mdAdded+12
config_sample.jsonAdded+14
deploy_guide.mdAdded+136
final_solution.mdAdded+47
get_gmail_token.pyAdded+46
github_guide.mdAdded+95
requirements.txtAdded+9
static/style.cssAdded+431
supabase_init.sqlAdded+68
templates/admin.htmlAdded+420
templates/import.htmlAdded+292
templates/index.htmlAdded+444
templates/list.htmlAdded+58
templates/login.htmlAdded+83
templates/manage_users.htmlAdded+93
templates/quiz.htmlAdded+288
templates/study.htmlAdded+97
wordApp_web.pyAdded+930
wordApp_web_localAdded+418