Separate student and admin panels
Browse files- .gitignore +4 -0
- README.md +44 -7
- app.py +633 -327
- auth_store.py +224 -0
- pending_edits.py +126 -0
- tests/__init__.py +1 -0
- tests/test_auth_store.py +42 -0
- tests/test_pending_edits.py +43 -0
.gitignore
CHANGED
|
@@ -4,6 +4,10 @@ __pycache__/
|
|
| 4 |
.env.*
|
| 5 |
.teacher_auth.json
|
| 6 |
.teacher_auth.json.tmp
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
data/cached_embeddings.pt
|
| 8 |
data/cached_embeddings.download.pt
|
| 9 |
data/cached_embeddings.pt.tmp
|
|
|
|
| 4 |
.env.*
|
| 5 |
.teacher_auth.json
|
| 6 |
.teacher_auth.json.tmp
|
| 7 |
+
.auth_users.json
|
| 8 |
+
.auth_users.json.tmp
|
| 9 |
+
.pending_teacher_edits.jsonl
|
| 10 |
+
.pending_teacher_edits.jsonl.tmp
|
| 11 |
data/cached_embeddings.pt
|
| 12 |
data/cached_embeddings.download.pt
|
| 13 |
data/cached_embeddings.pt.tmp
|
README.md
CHANGED
|
@@ -75,28 +75,65 @@ python app.py
|
|
| 75 |
|
| 76 |
Tip: keep tokens only in environment variables, never hardcode them in source files.
|
| 77 |
|
| 78 |
-
##
|
| 79 |
|
| 80 |
-
The
|
| 81 |
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
|
| 88 |
-
|
| 89 |
|
| 90 |
```powershell
|
|
|
|
|
|
|
| 91 |
$env:TEACHER_PASSWORD="your_strong_teacher_password"
|
|
|
|
|
|
|
| 92 |
python app.py
|
| 93 |
```
|
| 94 |
|
| 95 |
Command Prompt or Anaconda Prompt:
|
| 96 |
|
| 97 |
```bat
|
|
|
|
|
|
|
| 98 |
set TEACHER_PASSWORD=your_strong_teacher_password
|
|
|
|
|
|
|
| 99 |
python app.py
|
| 100 |
```
|
| 101 |
|
| 102 |
-
For Hugging Face Spaces, add `TEACHER_PASSWORD`
|
|
|
|
| 75 |
|
| 76 |
Tip: keep tokens only in environment variables, never hardcode them in source files.
|
| 77 |
|
| 78 |
+
## Student and admin panels
|
| 79 |
|
| 80 |
+
The app has two separate panels:
|
| 81 |
|
| 82 |
+
- `APP_PANEL=student` (default): public student chatbot only. No admin login, teacher panel, approval table, or admin callbacks are created in the UI.
|
| 83 |
+
- `APP_PANEL=admin`: protected teacher/admin portal for Q&A submissions, Super Admin approval, and cache rebuilds.
|
| 84 |
|
| 85 |
+
Local student app:
|
| 86 |
|
| 87 |
+
```powershell
|
| 88 |
+
python app.py
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
Local admin portal:
|
| 92 |
+
|
| 93 |
+
```powershell
|
| 94 |
+
$env:APP_PANEL="admin"
|
| 95 |
+
python app.py
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
For deployment, run the public student app and admin portal as separate app/Space instances. Keep `APP_PANEL=student` for students and `APP_PANEL=admin` only for trusted staff.
|
| 99 |
+
|
| 100 |
+
## Role-based account setup
|
| 101 |
+
|
| 102 |
+
The Student panel is public. Teacher/Admin and Super Admin tools exist only in the Admin panel and require login.
|
| 103 |
+
|
| 104 |
+
Roles:
|
| 105 |
+
|
| 106 |
+
- `student`: public chat only.
|
| 107 |
+
- `teacher`: can submit Q&A add/update/delete/reorder requests for approval.
|
| 108 |
+
- `super_admin`: can approve/reject teacher requests, apply live Q&A changes, and rebuild/upload cache.
|
| 109 |
+
|
| 110 |
+
For local development, open the Teacher page and log in once with:
|
| 111 |
+
|
| 112 |
+
- teacher username: `teacher`
|
| 113 |
+
- super admin username: `superadmin`
|
| 114 |
+
|
| 115 |
+
If a role has no password yet, the first login password is saved as a PBKDF2 hash in `.auth_users.json`. To reset local role accounts, delete `.auth_users.json` and start again. Existing `.teacher_auth.json` teacher passwords still work as a migration fallback.
|
| 116 |
|
| 117 |
+
For Hugging Face Spaces or server deployments, use environment secrets instead of local setup:
|
| 118 |
|
| 119 |
```powershell
|
| 120 |
+
$env:APP_PANEL="admin"
|
| 121 |
+
$env:TEACHER_USERNAME="teacher"
|
| 122 |
$env:TEACHER_PASSWORD="your_strong_teacher_password"
|
| 123 |
+
$env:SUPER_ADMIN_USERNAME="superadmin"
|
| 124 |
+
$env:SUPER_ADMIN_PASSWORD="your_strong_super_admin_password"
|
| 125 |
python app.py
|
| 126 |
```
|
| 127 |
|
| 128 |
Command Prompt or Anaconda Prompt:
|
| 129 |
|
| 130 |
```bat
|
| 131 |
+
set APP_PANEL=admin
|
| 132 |
+
set TEACHER_USERNAME=teacher
|
| 133 |
set TEACHER_PASSWORD=your_strong_teacher_password
|
| 134 |
+
set SUPER_ADMIN_USERNAME=superadmin
|
| 135 |
+
set SUPER_ADMIN_PASSWORD=your_strong_super_admin_password
|
| 136 |
python app.py
|
| 137 |
```
|
| 138 |
|
| 139 |
+
For Hugging Face Spaces, add `TEACHER_PASSWORD` and `SUPER_ADMIN_PASSWORD` as Space secrets. Usernames are optional and default to `teacher` and `superadmin`.
|
app.py
CHANGED
|
@@ -1,17 +1,18 @@
|
|
| 1 |
# app.py
|
| 2 |
-
import
|
| 3 |
-
import hashlib
|
| 4 |
-
import hmac
|
| 5 |
-
import json
|
| 6 |
import os
|
| 7 |
-
import
|
| 8 |
-
from pathlib import Path
|
| 9 |
|
| 10 |
import gradio as gr
|
| 11 |
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
| 13 |
from model_utils import GUIDE_WELCOME_MESSAGE, laos_science_bot
|
|
|
|
| 14 |
from teacher_panel import (
|
|
|
|
| 15 |
teacher_delete_current,
|
| 16 |
teacher_move_current_down,
|
| 17 |
teacher_move_current_up,
|
|
@@ -25,74 +26,14 @@ from teacher_panel import (
|
|
| 25 |
)
|
| 26 |
|
| 27 |
APP_TITLE = "ແຊັດບອດວິທະຍາສາດທຳມະຊາດ"
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def _password_digest(password: str, salt: bytes, iterations: int) -> bytes:
|
| 38 |
-
return hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
def _load_local_teacher_auth() -> dict | None:
|
| 42 |
-
if not TEACHER_AUTH_PATH.exists():
|
| 43 |
-
return None
|
| 44 |
-
|
| 45 |
-
try:
|
| 46 |
-
payload = json.loads(TEACHER_AUTH_PATH.read_text(encoding="utf-8"))
|
| 47 |
-
if payload.get("algorithm") != "pbkdf2_sha256":
|
| 48 |
-
return None
|
| 49 |
-
|
| 50 |
-
return {
|
| 51 |
-
"iterations": int(payload["iterations"]),
|
| 52 |
-
"salt": base64.b64decode(payload["salt"]),
|
| 53 |
-
"hash": base64.b64decode(payload["hash"]),
|
| 54 |
-
}
|
| 55 |
-
except (OSError, ValueError, KeyError, TypeError):
|
| 56 |
-
return None
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
def _teacher_auth_configured() -> bool:
|
| 60 |
-
return bool(ENV_TEACHER_PASSWORD) or _load_local_teacher_auth() is not None
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def _save_local_teacher_password(password: str) -> None:
|
| 64 |
-
salt = secrets.token_bytes(16)
|
| 65 |
-
digest = _password_digest(password, salt, TEACHER_AUTH_ITERATIONS)
|
| 66 |
-
payload = {
|
| 67 |
-
"version": 1,
|
| 68 |
-
"algorithm": "pbkdf2_sha256",
|
| 69 |
-
"iterations": TEACHER_AUTH_ITERATIONS,
|
| 70 |
-
"salt": base64.b64encode(salt).decode("ascii"),
|
| 71 |
-
"hash": base64.b64encode(digest).decode("ascii"),
|
| 72 |
-
}
|
| 73 |
-
|
| 74 |
-
TEACHER_AUTH_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 75 |
-
tmp_path = TEACHER_AUTH_PATH.with_name(f"{TEACHER_AUTH_PATH.name}.tmp")
|
| 76 |
-
tmp_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
|
| 77 |
-
tmp_path.replace(TEACHER_AUTH_PATH)
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
def _verify_teacher_password(password: str) -> bool:
|
| 81 |
-
if ENV_TEACHER_PASSWORD:
|
| 82 |
-
return hmac.compare_digest(password, ENV_TEACHER_PASSWORD)
|
| 83 |
-
|
| 84 |
-
payload = _load_local_teacher_auth()
|
| 85 |
-
if payload is None:
|
| 86 |
-
return False
|
| 87 |
-
|
| 88 |
-
digest = _password_digest(password, payload["salt"], payload["iterations"])
|
| 89 |
-
return hmac.compare_digest(digest, payload["hash"])
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
TEACHER_LOGIN_HELP = (
|
| 93 |
-
"ປ້ອນລະຫັດຜ່ານອາຈານເພື່ອເຂົ້າໃຊ້ເຄື່ອງມືຈັດການ."
|
| 94 |
-
if _teacher_auth_configured()
|
| 95 |
-
else "ຍັງບໍ່ໄດ້ຕັ້ງລະຫັດຜ່ານອາຈານ. ປ້ອນລະຫັດໃໝ່ 1 ຄັ້ງ; ລະບົບຈະຈື່ໄວ້ໃນເຄື່ອງນີ້."
|
| 96 |
)
|
| 97 |
|
| 98 |
GLOBAL_FONT_CSS = """
|
|
@@ -105,11 +46,6 @@ GLOBAL_FONT_CSS = """
|
|
| 105 |
padding: 8px 0 4px;
|
| 106 |
}
|
| 107 |
|
| 108 |
-
.role-nav button {
|
| 109 |
-
min-height: 44px;
|
| 110 |
-
font-weight: 700;
|
| 111 |
-
}
|
| 112 |
-
|
| 113 |
.student-page,
|
| 114 |
.teacher-page {
|
| 115 |
padding-top: 8px;
|
|
@@ -198,19 +134,24 @@ TREE = discover_grade_unit_tree()
|
|
| 198 |
GRADE_CHOICES = list(TREE.keys())
|
| 199 |
DEFAULT_GRADE = GRADE_CHOICES[0] if GRADE_CHOICES else "M_1"
|
| 200 |
DEFAULT_UNIT = (TREE.get(DEFAULT_GRADE) or ["U_01"])[0]
|
| 201 |
-
LOCKED_STATUS = "
|
|
|
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
def show_student_page():
|
| 205 |
return gr.update(visible=True), gr.update(visible=False)
|
| 206 |
|
| 207 |
|
| 208 |
-
def show_teacher_page(
|
|
|
|
|
|
|
| 209 |
return (
|
| 210 |
gr.update(visible=False),
|
| 211 |
gr.update(visible=True),
|
| 212 |
-
gr.update(visible=not
|
| 213 |
-
gr.update(visible=
|
|
|
|
| 214 |
)
|
| 215 |
|
| 216 |
|
|
@@ -222,159 +163,447 @@ def _empty_teacher_table(status: str = ""):
|
|
| 222 |
return gr.update(), [], "", "", teacher_render_answer_preview(""), "", status
|
| 223 |
|
| 224 |
|
| 225 |
-
def
|
| 226 |
-
|
| 227 |
-
is_configured = _teacher_auth_configured()
|
| 228 |
|
| 229 |
-
if not password:
|
| 230 |
-
setup_status = (
|
| 231 |
-
"ກະລຸນາປ້ອນລະຫັດຜ່ານອາຈານກ່ອນ."
|
| 232 |
-
if is_configured
|
| 233 |
-
else "ກະລຸນາປ້ອນລະຫັດຜ່ານອາຈານໃໝ່ກ່ອນ. ລະບົບຈະບັນທຶກໄວ້ສຳລັບການເປີດໃຊ້ຄັ້ງຕໍ່ໄປ."
|
| 234 |
-
)
|
| 235 |
-
return (
|
| 236 |
-
gr.update(visible=True),
|
| 237 |
-
gr.update(visible=False),
|
| 238 |
-
gr.update(value=""),
|
| 239 |
-
False,
|
| 240 |
-
*_empty_teacher_editor(setup_status),
|
| 241 |
-
setup_status,
|
| 242 |
-
)
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
|
| 258 |
-
q_value, a_value, preview_value, current_id, table_value, status = teacher_on_unit_change(grade, unit)
|
| 259 |
-
return (
|
| 260 |
-
gr.update(visible=False),
|
| 261 |
-
gr.update(visible=True),
|
| 262 |
-
gr.update(value=""),
|
| 263 |
-
True,
|
| 264 |
-
q_value,
|
| 265 |
-
a_value,
|
| 266 |
-
preview_value,
|
| 267 |
-
current_id,
|
| 268 |
-
table_value,
|
| 269 |
-
status,
|
| 270 |
-
"ບັນທຶກລະຫັດຜ່ານອາຈານແລ້ວ. ເປີດໃຊ້ໜ້າອາຈານແລ້ວ.",
|
| 271 |
-
)
|
| 272 |
|
| 273 |
-
|
| 274 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
return (
|
| 276 |
-
gr.update(visible=False),
|
| 277 |
gr.update(visible=True),
|
|
|
|
|
|
|
| 278 |
gr.update(value=""),
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
a_value,
|
| 282 |
-
preview_value,
|
| 283 |
-
current_id,
|
| 284 |
-
table_value,
|
| 285 |
status,
|
| 286 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
)
|
| 288 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
return (
|
| 290 |
-
gr.update(visible=True),
|
| 291 |
gr.update(visible=False),
|
|
|
|
|
|
|
| 292 |
gr.update(value=""),
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
)
|
| 297 |
|
| 298 |
|
| 299 |
-
def
|
|
|
|
| 300 |
return (
|
| 301 |
gr.update(visible=True),
|
| 302 |
gr.update(visible=False),
|
|
|
|
| 303 |
gr.update(value=""),
|
| 304 |
-
|
| 305 |
-
*_empty_teacher_editor(
|
| 306 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
)
|
| 308 |
|
| 309 |
|
| 310 |
-
def guarded_teacher_on_grade_change(
|
| 311 |
-
if not
|
| 312 |
return _empty_teacher_table(LOCKED_STATUS)
|
| 313 |
return teacher_on_grade_change(grade)
|
| 314 |
|
| 315 |
|
| 316 |
-
def guarded_teacher_on_unit_change(
|
| 317 |
-
if not
|
| 318 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 319 |
return teacher_on_unit_change(grade, unit)
|
| 320 |
|
| 321 |
|
| 322 |
def guarded_teacher_save_add_overwrite(
|
| 323 |
-
|
| 324 |
grade: str,
|
| 325 |
unit: str,
|
| 326 |
question: str,
|
| 327 |
answer: str,
|
| 328 |
current_id: str,
|
| 329 |
):
|
| 330 |
-
if not
|
| 331 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 332 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 333 |
|
| 334 |
|
| 335 |
def guarded_teacher_update_current(
|
| 336 |
-
|
| 337 |
grade: str,
|
| 338 |
unit: str,
|
| 339 |
question: str,
|
| 340 |
answer: str,
|
| 341 |
current_id: str,
|
| 342 |
):
|
| 343 |
-
if not
|
| 344 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
|
| 347 |
|
| 348 |
-
def
|
| 349 |
-
if not
|
| 350 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 351 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
|
| 354 |
-
def
|
| 355 |
-
|
| 356 |
-
return _empty_teacher_editor(LOCKED_STATUS)
|
| 357 |
-
return teacher_move_current_up(grade, unit, current_id)
|
| 358 |
|
| 359 |
|
| 360 |
-
def
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
|
|
|
|
|
|
| 364 |
|
| 365 |
|
| 366 |
-
def guarded_teacher_rebuild_cache_click(
|
| 367 |
-
if not
|
| 368 |
-
return
|
| 369 |
return teacher_rebuild_cache_click()
|
| 370 |
|
| 371 |
|
| 372 |
-
def guarded_teacher_on_table_select(
|
| 373 |
-
if not
|
| 374 |
return "", "", teacher_render_answer_preview(""), "", LOCKED_STATUS
|
| 375 |
return teacher_on_table_select(evt)
|
| 376 |
|
| 377 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
def student_send_message(message, history):
|
| 379 |
cleaned_message = (message or "").strip()
|
| 380 |
current_history = list(history or [])
|
|
@@ -393,51 +622,34 @@ def student_send_message(message, history):
|
|
| 393 |
|
| 394 |
|
| 395 |
with gr.Blocks(title=APP_TITLE) as demo:
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
with gr.Row(elem_classes=["role-nav"]):
|
| 402 |
-
btn_student_page = gr.Button("ໜ້ານັກຮຽນ", variant="primary")
|
| 403 |
-
btn_teacher_page = gr.Button("ໜ້າອາຈານ", variant="secondary")
|
| 404 |
-
|
| 405 |
-
with gr.Column(visible=True, elem_classes=["student-page"]) as student_page:
|
| 406 |
-
gr.Markdown("### ຫ້ອງສົນທະນານັກຮຽນ")
|
| 407 |
-
gr.Markdown("ຖາມຄຳຖາມວິທະຍາສາດທຳມະຊາດເປັນພາສາລາວ.")
|
| 408 |
-
student_chatbot = gr.Chatbot(
|
| 409 |
-
value=[{"role": "assistant", "content": GUIDE_WELCOME_MESSAGE}],
|
| 410 |
-
label="ຜູ້ຊ່ວຍຕອບຄຳຖາມ",
|
| 411 |
)
|
| 412 |
-
|
| 413 |
-
student_message_box = gr.Textbox(
|
| 414 |
-
placeholder="ພິມຄຳຖາມຂອງເຈົ້າ...",
|
| 415 |
-
show_label=False,
|
| 416 |
-
container=False,
|
| 417 |
-
scale=9,
|
| 418 |
-
)
|
| 419 |
-
btn_student_send = gr.Button("ສົ່ງ", variant="primary", scale=1, min_width=96)
|
| 420 |
-
|
| 421 |
-
with gr.Column(visible=False, elem_classes=["teacher-page"]) as teacher_page:
|
| 422 |
-
teacher_auth_state = gr.State(False)
|
| 423 |
|
| 424 |
with gr.Column(visible=True, elem_classes=["teacher-lock"]) as teacher_login_box:
|
| 425 |
-
gr.Markdown("### ເຂົ້າສູ່ໜ້າຈັດການ
|
| 426 |
-
gr.Markdown(
|
| 427 |
-
|
| 428 |
-
label="
|
|
|
|
|
|
|
|
|
|
|
|
|
| 429 |
type="password",
|
| 430 |
placeholder="ປ້ອນລະຫັດຜ່ານ",
|
| 431 |
)
|
| 432 |
-
btn_teacher_login = gr.Button("ເຂົ້າສູ່ລະບົບ
|
| 433 |
teacher_login_status = gr.Markdown("")
|
| 434 |
|
| 435 |
-
with gr.Column(visible=False) as teacher_workspace:
|
| 436 |
with gr.Row():
|
| 437 |
gr.Markdown("### ໜ້າຈັດການຂອງອາຈານ")
|
| 438 |
-
btn_teacher_logout = gr.Button("ອອກຈາກລະບົບ
|
| 439 |
|
| 440 |
-
gr.Markdown("
|
| 441 |
|
| 442 |
with gr.Row():
|
| 443 |
grade_dd = gr.Dropdown(
|
|
@@ -476,7 +688,7 @@ with gr.Blocks(title=APP_TITLE) as demo:
|
|
| 476 |
|
| 477 |
gr.Markdown("---")
|
| 478 |
with gr.Row():
|
| 479 |
-
btn_rebuild = gr.Button("
|
| 480 |
|
| 481 |
status_md = gr.Markdown("")
|
| 482 |
|
|
@@ -488,143 +700,237 @@ with gr.Blocks(title=APP_TITLE) as demo:
|
|
| 488 |
row_count=(0, "dynamic"),
|
| 489 |
)
|
| 490 |
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
)
|
| 496 |
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
|
|
|
|
|
|
| 501 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 502 |
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 628 |
|
| 629 |
if __name__ == "__main__":
|
| 630 |
demo.launch(css=GLOBAL_FONT_CSS)
|
|
|
|
| 1 |
# app.py
|
| 2 |
+
import html
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
+
from typing import Any, Dict
|
|
|
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
|
| 8 |
+
import auth_store
|
| 9 |
+
import pending_edits
|
| 10 |
+
import qa_store
|
| 11 |
+
from loader import discover_grade_unit_tree, manual_qa_table_data
|
| 12 |
from model_utils import GUIDE_WELCOME_MESSAGE, laos_science_bot
|
| 13 |
+
from qa_store import normalize_question
|
| 14 |
from teacher_panel import (
|
| 15 |
+
_validate_manual_question,
|
| 16 |
teacher_delete_current,
|
| 17 |
teacher_move_current_down,
|
| 18 |
teacher_move_current_up,
|
|
|
|
| 26 |
)
|
| 27 |
|
| 28 |
APP_TITLE = "ແຊັດບອດວິທະຍາສາດທຳມະຊາດ"
|
| 29 |
+
APP_PANEL = (os.getenv("APP_PANEL", "student").strip().lower() or "student")
|
| 30 |
+
if APP_PANEL not in {"student", "admin"}:
|
| 31 |
+
APP_PANEL = "student"
|
| 32 |
+
ACCOUNT_LOGIN_HELP = (
|
| 33 |
+
"ປ້ອນຊື່ຜູ້ໃຊ້ ແລະ ລະຫັດຜ່ານ. "
|
| 34 |
+
f"ບັນຊີທ້ອງຖິ່ນເລີ່ມຕົ້ນໃຊ້ `{auth_store.teacher_username()}` "
|
| 35 |
+
f"ສຳລັບອາຈານ ແລະ `{auth_store.super_admin_username()}` ສຳລັບ Super Admin. "
|
| 36 |
+
"ຖ້າບັນຊີຍັງບໍ່ຖືກຕັ້ງ, ການລັອກອິນຄັ້ງທຳອິດຈະບັນທຶກລະຫັດໄວ້ໃນເຄື່ອງນີ້."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
)
|
| 38 |
|
| 39 |
GLOBAL_FONT_CSS = """
|
|
|
|
| 46 |
padding: 8px 0 4px;
|
| 47 |
}
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
.student-page,
|
| 50 |
.teacher-page {
|
| 51 |
padding-top: 8px;
|
|
|
|
| 134 |
GRADE_CHOICES = list(TREE.keys())
|
| 135 |
DEFAULT_GRADE = GRADE_CHOICES[0] if GRADE_CHOICES else "M_1"
|
| 136 |
DEFAULT_UNIT = (TREE.get(DEFAULT_GRADE) or ["U_01"])[0]
|
| 137 |
+
LOCKED_STATUS = "ບໍ່ມີສິດໃຊ້ງານໜ້ານີ້. ກະລຸນາລັອກອິນກ່ອນ."
|
| 138 |
+
SUPER_ADMIN_ONLY_STATUS = "ສິດນີ້ສຳລັບ Super Admin ເທົ່ານັ້ນ."
|
| 139 |
+
PENDING_HEADERS = ["ເວລາ", "ID", "ປະເພດ", "ຊັ້ນ", "ບົດ", "Target", "ຂໍ້ຄວາມ", "ຜູ້ສົ່ງ"]
|
| 140 |
|
| 141 |
|
| 142 |
def show_student_page():
|
| 143 |
return gr.update(visible=True), gr.update(visible=False)
|
| 144 |
|
| 145 |
|
| 146 |
+
def show_teacher_page(session: Dict[str, Any] | None):
|
| 147 |
+
can_manage = auth_store.can_manage_qa(session)
|
| 148 |
+
can_approve = auth_store.can_approve_edits(session)
|
| 149 |
return (
|
| 150 |
gr.update(visible=False),
|
| 151 |
gr.update(visible=True),
|
| 152 |
+
gr.update(visible=not can_manage),
|
| 153 |
+
gr.update(visible=can_manage),
|
| 154 |
+
gr.update(visible=can_approve),
|
| 155 |
)
|
| 156 |
|
| 157 |
|
|
|
|
| 163 |
return gr.update(), [], "", "", teacher_render_answer_preview(""), "", status
|
| 164 |
|
| 165 |
|
| 166 |
+
def _teacher_table(grade: str, unit: str):
|
| 167 |
+
return manual_qa_table_data(grade, unit)
|
|
|
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
def _unit_entries(grade: str, unit: str):
|
| 171 |
+
return [
|
| 172 |
+
entry
|
| 173 |
+
for entry in qa_store.MANUAL_QA_LIST
|
| 174 |
+
if entry.get("grade") == grade and entry.get("unit") == unit
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _entry_by_id(grade: str, unit: str, entry_id: str):
|
| 179 |
+
return next(
|
| 180 |
+
(
|
| 181 |
+
entry
|
| 182 |
+
for entry in qa_store.MANUAL_QA_LIST
|
| 183 |
+
if entry.get("grade") == grade and entry.get("unit") == unit and str(entry.get("id", "")) == entry_id
|
| 184 |
+
),
|
| 185 |
+
None,
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _empty_pending_preview(message: str = ""):
|
| 190 |
+
message = message or "ເລືອກລາຍການທີ່ລໍຖ້າການອະນຸມັດ."
|
| 191 |
+
return f'<div class="teacher-answer-preview teacher-answer-preview--empty">{html.escape(message)}</div>'
|
| 192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
|
| 194 |
+
def _short_text(value: str, limit: int = 90) -> str:
|
| 195 |
+
value = " ".join((value or "").split())
|
| 196 |
+
if len(value) <= limit:
|
| 197 |
+
return value
|
| 198 |
+
return value[: limit - 3] + "..."
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _pending_table_data():
|
| 202 |
+
rows = pending_edits.list_edits(status=pending_edits.STATUS_PENDING)
|
| 203 |
+
return [
|
| 204 |
+
[
|
| 205 |
+
row.get("created_at", ""),
|
| 206 |
+
row.get("id", ""),
|
| 207 |
+
row.get("action", ""),
|
| 208 |
+
row.get("grade", ""),
|
| 209 |
+
row.get("unit", ""),
|
| 210 |
+
row.get("target_id", ""),
|
| 211 |
+
_short_text(row.get("question") or row.get("answer") or row.get("review_note") or ""),
|
| 212 |
+
row.get("submitted_by", ""),
|
| 213 |
+
]
|
| 214 |
+
for row in rows
|
| 215 |
+
]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _pending_preview_html(edit: Dict[str, Any] | None):
|
| 219 |
+
if not edit:
|
| 220 |
+
return _empty_pending_preview()
|
| 221 |
+
|
| 222 |
+
action = html.escape(str(edit.get("action", "")))
|
| 223 |
+
grade = html.escape(str(edit.get("grade", "")))
|
| 224 |
+
unit = html.escape(str(edit.get("unit", "")))
|
| 225 |
+
target_id = html.escape(str(edit.get("target_id", "")))
|
| 226 |
+
question = html.escape(str(edit.get("question", ""))).replace("\n", "<br>")
|
| 227 |
+
answer = html.escape(str(edit.get("answer", ""))).replace("\n", "<br>")
|
| 228 |
+
submitted_by = html.escape(str(edit.get("submitted_by", "")))
|
| 229 |
+
created_at = html.escape(str(edit.get("created_at", "")))
|
| 230 |
+
direction = html.escape(str(edit.get("move_direction", "")))
|
| 231 |
+
|
| 232 |
+
return (
|
| 233 |
+
'<div class="teacher-answer-preview teacher-answer-preview--text">'
|
| 234 |
+
f"<strong>{action}</strong> | {grade}/{unit}<br>"
|
| 235 |
+
f"ID: {html.escape(str(edit.get('id', '')))}<br>"
|
| 236 |
+
f"Target: {target_id or '-'} | Direction: {direction or '-'}<br>"
|
| 237 |
+
f"Submitted by: {submitted_by or '-'} | {created_at}<br><br>"
|
| 238 |
+
f"<strong>ຄຳຖາມ</strong><br>{question or '-'}<br><br>"
|
| 239 |
+
f"<strong>ຄຳຕອບ</strong><br>{answer or '-'}"
|
| 240 |
+
"</div>"
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def _validate_question_answer(question: str, answer: str) -> str:
|
| 245 |
+
if not question or not answer:
|
| 246 |
+
return "ກະລຸນາປ້ອນທັງຄຳຖາມ ແລະ ຄຳຕອບ."
|
| 247 |
+
|
| 248 |
+
quality_err = _validate_manual_question(normalize_question(question))
|
| 249 |
+
return quality_err or ""
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _pending_submitter(session: Dict[str, Any] | None):
|
| 253 |
+
return (
|
| 254 |
+
str((session or {}).get("username") or auth_store.role_label((session or {}).get("role"))),
|
| 255 |
+
str((session or {}).get("role") or auth_store.ROLE_STUDENT),
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def login_account(username: str, password: str, grade: str, unit: str):
|
| 260 |
+
result = auth_store.authenticate_or_setup(username, password)
|
| 261 |
+
if not result.ok:
|
| 262 |
+
status = "ຊື່ຜູ້ໃຊ້ ຫຼື ລະຫັດຜ່ານບໍ່ຖືກ. ລອງອີກຄັ້ງ."
|
| 263 |
+
if result.reason == "missing_credentials":
|
| 264 |
+
status = "ກະລຸນາປ້ອນຊື່ຜູ້ໃຊ້ ແລະ ລະຫັດຜ່ານ."
|
| 265 |
return (
|
|
|
|
| 266 |
gr.update(visible=True),
|
| 267 |
+
gr.update(visible=False),
|
| 268 |
+
gr.update(visible=False),
|
| 269 |
gr.update(value=""),
|
| 270 |
+
auth_store.student_session(),
|
| 271 |
+
*_empty_teacher_editor(LOCKED_STATUS),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
status,
|
| 273 |
+
[],
|
| 274 |
+
"",
|
| 275 |
+
_empty_pending_preview(),
|
| 276 |
+
"",
|
| 277 |
+
"",
|
| 278 |
)
|
| 279 |
|
| 280 |
+
session = result.session
|
| 281 |
+
q_value, a_value, preview_value, current_id, table_value, status = teacher_on_unit_change(grade, unit)
|
| 282 |
+
role_text = auth_store.role_label(session.get("role"))
|
| 283 |
+
login_status = f"ລັອກອິນສຳເລັດ: {session.get('username')} ({role_text})."
|
| 284 |
+
if result.created:
|
| 285 |
+
login_status = f"ສ້າງບັນຊີທ້ອງຖິ່ນແລ້ວ ແລະ ລັອກອິນສຳເລັດ: {role_text}."
|
| 286 |
+
|
| 287 |
return (
|
|
|
|
| 288 |
gr.update(visible=False),
|
| 289 |
+
gr.update(visible=True),
|
| 290 |
+
gr.update(visible=auth_store.can_approve_edits(session)),
|
| 291 |
gr.update(value=""),
|
| 292 |
+
session,
|
| 293 |
+
q_value,
|
| 294 |
+
a_value,
|
| 295 |
+
preview_value,
|
| 296 |
+
current_id,
|
| 297 |
+
table_value,
|
| 298 |
+
status,
|
| 299 |
+
login_status,
|
| 300 |
+
_pending_table_data() if auth_store.can_approve_edits(session) else [],
|
| 301 |
+
"",
|
| 302 |
+
_empty_pending_preview(),
|
| 303 |
+
"",
|
| 304 |
+
"",
|
| 305 |
)
|
| 306 |
|
| 307 |
|
| 308 |
+
def logout_account():
|
| 309 |
+
status = "ອອກຈາກລະບົບແລ້ວ."
|
| 310 |
return (
|
| 311 |
gr.update(visible=True),
|
| 312 |
gr.update(visible=False),
|
| 313 |
+
gr.update(visible=False),
|
| 314 |
gr.update(value=""),
|
| 315 |
+
auth_store.student_session(),
|
| 316 |
+
*_empty_teacher_editor(status),
|
| 317 |
+
status,
|
| 318 |
+
[],
|
| 319 |
+
"",
|
| 320 |
+
_empty_pending_preview(),
|
| 321 |
+
"",
|
| 322 |
+
"",
|
| 323 |
)
|
| 324 |
|
| 325 |
|
| 326 |
+
def guarded_teacher_on_grade_change(session: Dict[str, Any] | None, grade: str):
|
| 327 |
+
if not auth_store.can_manage_qa(session):
|
| 328 |
return _empty_teacher_table(LOCKED_STATUS)
|
| 329 |
return teacher_on_grade_change(grade)
|
| 330 |
|
| 331 |
|
| 332 |
+
def guarded_teacher_on_unit_change(session: Dict[str, Any] | None, grade: str, unit: str):
|
| 333 |
+
if not auth_store.can_manage_qa(session):
|
| 334 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 335 |
return teacher_on_unit_change(grade, unit)
|
| 336 |
|
| 337 |
|
| 338 |
def guarded_teacher_save_add_overwrite(
|
| 339 |
+
session: Dict[str, Any] | None,
|
| 340 |
grade: str,
|
| 341 |
unit: str,
|
| 342 |
question: str,
|
| 343 |
answer: str,
|
| 344 |
current_id: str,
|
| 345 |
):
|
| 346 |
+
if not auth_store.can_manage_qa(session):
|
| 347 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 348 |
+
if auth_store.can_approve_edits(session):
|
| 349 |
+
return teacher_save_add_overwrite(grade, unit, question, answer, current_id)
|
| 350 |
+
|
| 351 |
+
question = (question or "").strip()
|
| 352 |
+
answer = (answer or "").strip()
|
| 353 |
+
current_id = current_id or ""
|
| 354 |
+
validation_msg = _validate_question_answer(question, answer)
|
| 355 |
+
if validation_msg:
|
| 356 |
+
return question, answer, teacher_render_answer_preview(answer), current_id, _teacher_table(grade, unit), validation_msg
|
| 357 |
+
|
| 358 |
+
submitted_by, submitted_role = _pending_submitter(session)
|
| 359 |
+
edit = pending_edits.append_pending_edit(
|
| 360 |
+
action="save_add_overwrite",
|
| 361 |
+
grade=grade,
|
| 362 |
+
unit=unit,
|
| 363 |
+
question=question,
|
| 364 |
+
answer=answer,
|
| 365 |
+
target_id=current_id,
|
| 366 |
+
submitted_by=submitted_by,
|
| 367 |
+
submitted_role=submitted_role,
|
| 368 |
+
)
|
| 369 |
+
status = f"ສົ່ງຄຳຂໍແກ້ໄຂໄປໃຫ້ Super Admin ອະນຸມັດແລ້ວ (ID: {edit['id']})."
|
| 370 |
+
return question, answer, teacher_render_answer_preview(answer), current_id, _teacher_table(grade, unit), status
|
| 371 |
|
| 372 |
|
| 373 |
def guarded_teacher_update_current(
|
| 374 |
+
session: Dict[str, Any] | None,
|
| 375 |
grade: str,
|
| 376 |
unit: str,
|
| 377 |
question: str,
|
| 378 |
answer: str,
|
| 379 |
current_id: str,
|
| 380 |
):
|
| 381 |
+
if not auth_store.can_manage_qa(session):
|
| 382 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 383 |
+
if auth_store.can_approve_edits(session):
|
| 384 |
+
return teacher_update_current(grade, unit, question, answer, current_id)
|
| 385 |
+
|
| 386 |
+
question = (question or "").strip()
|
| 387 |
+
answer = (answer or "").strip()
|
| 388 |
+
current_id = current_id or ""
|
| 389 |
+
if not current_id:
|
| 390 |
+
msg = "ກະລຸນາເລືອກແຖວຄຳຖາມ-ຄຳຕອບກ່ອນສົ່ງຄຳຂໍອັບເດດ."
|
| 391 |
+
return question, answer, teacher_render_answer_preview(answer), current_id, _teacher_table(grade, unit), msg
|
| 392 |
+
if _entry_by_id(grade, unit, current_id) is None:
|
| 393 |
+
msg = "ບໍ່ພົບລາຍການທີ່ເລືອກໃນບົດຮຽນນີ້."
|
| 394 |
+
return question, answer, teacher_render_answer_preview(answer), "", _teacher_table(grade, unit), msg
|
| 395 |
+
|
| 396 |
+
validation_msg = _validate_question_answer(question, answer)
|
| 397 |
+
if validation_msg:
|
| 398 |
+
return question, answer, teacher_render_answer_preview(answer), current_id, _teacher_table(grade, unit), validation_msg
|
| 399 |
+
|
| 400 |
+
submitted_by, submitted_role = _pending_submitter(session)
|
| 401 |
+
edit = pending_edits.append_pending_edit(
|
| 402 |
+
action="update",
|
| 403 |
+
grade=grade,
|
| 404 |
+
unit=unit,
|
| 405 |
+
question=question,
|
| 406 |
+
answer=answer,
|
| 407 |
+
target_id=current_id,
|
| 408 |
+
submitted_by=submitted_by,
|
| 409 |
+
submitted_role=submitted_role,
|
| 410 |
+
)
|
| 411 |
+
status = f"ສົ່ງຄຳຂໍອັບເດດໄປໃຫ້ Super Admin ອະນຸມັດແລ້ວ (ID: {edit['id']})."
|
| 412 |
+
return question, answer, teacher_render_answer_preview(answer), current_id, _teacher_table(grade, unit), status
|
| 413 |
|
| 414 |
|
| 415 |
+
def _pending_target_action(session, grade: str, unit: str, current_id: str, action: str, direction: int = 0):
|
| 416 |
+
if not auth_store.can_manage_qa(session):
|
| 417 |
return _empty_teacher_editor(LOCKED_STATUS)
|
| 418 |
+
|
| 419 |
+
current_id = current_id or ""
|
| 420 |
+
entry = _entry_by_id(grade, unit, current_id)
|
| 421 |
+
if not current_id or entry is None:
|
| 422 |
+
msg = "ກະລຸນາເລືອກແຖວຄຳຖາມ-ຄຳຕອບກ່ອນ."
|
| 423 |
+
return "", "", teacher_render_answer_preview(""), current_id, _teacher_table(grade, unit), msg
|
| 424 |
+
|
| 425 |
+
if auth_store.can_approve_edits(session):
|
| 426 |
+
if action == "delete":
|
| 427 |
+
return teacher_delete_current(grade, unit, current_id)
|
| 428 |
+
if direction < 0:
|
| 429 |
+
return teacher_move_current_up(grade, unit, current_id)
|
| 430 |
+
return teacher_move_current_down(grade, unit, current_id)
|
| 431 |
+
|
| 432 |
+
submitted_by, submitted_role = _pending_submitter(session)
|
| 433 |
+
edit = pending_edits.append_pending_edit(
|
| 434 |
+
action=action,
|
| 435 |
+
grade=grade,
|
| 436 |
+
unit=unit,
|
| 437 |
+
question=str(entry.get("q", "")),
|
| 438 |
+
answer=str(entry.get("a", "")),
|
| 439 |
+
target_id=current_id,
|
| 440 |
+
move_direction=direction,
|
| 441 |
+
submitted_by=submitted_by,
|
| 442 |
+
submitted_role=submitted_role,
|
| 443 |
+
)
|
| 444 |
+
action_text = "ລຶບ" if action == "delete" else "ປ່ຽນລຳດັບ"
|
| 445 |
+
status = f"ສົ່ງຄຳຂໍ{action_text}ໄປໃຫ້ Super Admin ອະນຸມັດແລ້ວ (ID: {edit['id']})."
|
| 446 |
+
return (
|
| 447 |
+
str(entry.get("q", "")),
|
| 448 |
+
str(entry.get("a", "")),
|
| 449 |
+
teacher_render_answer_preview(str(entry.get("a", ""))),
|
| 450 |
+
current_id,
|
| 451 |
+
_teacher_table(grade, unit),
|
| 452 |
+
status,
|
| 453 |
+
)
|
| 454 |
|
| 455 |
|
| 456 |
+
def guarded_teacher_delete_current(session: Dict[str, Any] | None, grade: str, unit: str, current_id: str):
|
| 457 |
+
return _pending_target_action(session, grade, unit, current_id, "delete")
|
|
|
|
|
|
|
| 458 |
|
| 459 |
|
| 460 |
+
def guarded_teacher_move_current_up(session: Dict[str, Any] | None, grade: str, unit: str, current_id: str):
|
| 461 |
+
return _pending_target_action(session, grade, unit, current_id, "move", -1)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def guarded_teacher_move_current_down(session: Dict[str, Any] | None, grade: str, unit: str, current_id: str):
|
| 465 |
+
return _pending_target_action(session, grade, unit, current_id, "move", 1)
|
| 466 |
|
| 467 |
|
| 468 |
+
def guarded_teacher_rebuild_cache_click(session: Dict[str, Any] | None):
|
| 469 |
+
if not auth_store.can_approve_edits(session):
|
| 470 |
+
return SUPER_ADMIN_ONLY_STATUS
|
| 471 |
return teacher_rebuild_cache_click()
|
| 472 |
|
| 473 |
|
| 474 |
+
def guarded_teacher_on_table_select(session: Dict[str, Any] | None, evt: gr.SelectData):
|
| 475 |
+
if not auth_store.can_manage_qa(session):
|
| 476 |
return "", "", teacher_render_answer_preview(""), "", LOCKED_STATUS
|
| 477 |
return teacher_on_table_select(evt)
|
| 478 |
|
| 479 |
|
| 480 |
+
def _move_is_possible(edit: Dict[str, Any]) -> str:
|
| 481 |
+
grade = str(edit.get("grade", ""))
|
| 482 |
+
unit = str(edit.get("unit", ""))
|
| 483 |
+
target_id = str(edit.get("target_id", ""))
|
| 484 |
+
direction = int(edit.get("move_direction") or 0)
|
| 485 |
+
entries = _unit_entries(grade, unit)
|
| 486 |
+
current_pos = next((idx for idx, entry in enumerate(entries) if str(entry.get("id", "")) == target_id), None)
|
| 487 |
+
if current_pos is None:
|
| 488 |
+
return "ບໍ່ພົບລາຍການທີ່ຈະປ່ຽນລຳດັບ."
|
| 489 |
+
target_pos = current_pos + direction
|
| 490 |
+
if target_pos < 0 or target_pos >= len(entries):
|
| 491 |
+
return "ລາຍການນີ້ຢູ່ຂອບລຳດັບແລ້ວ."
|
| 492 |
+
return ""
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
def _teacher_state_with_status(grade: str, unit: str, status: str):
|
| 496 |
+
q_value, a_value, preview_value, current_id, table_value, _ = teacher_on_unit_change(grade, unit)
|
| 497 |
+
return q_value, a_value, preview_value, current_id, table_value, status
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _apply_pending_edit(edit: Dict[str, Any]):
|
| 501 |
+
action = str(edit.get("action", ""))
|
| 502 |
+
grade = str(edit.get("grade", ""))
|
| 503 |
+
unit = str(edit.get("unit", ""))
|
| 504 |
+
question = str(edit.get("question", "")).strip()
|
| 505 |
+
answer = str(edit.get("answer", "")).strip()
|
| 506 |
+
target_id = str(edit.get("target_id", ""))
|
| 507 |
+
direction = int(edit.get("move_direction") or 0)
|
| 508 |
+
|
| 509 |
+
if action in {"save_add_overwrite", "update"}:
|
| 510 |
+
validation_msg = _validate_question_answer(question, answer)
|
| 511 |
+
if validation_msg:
|
| 512 |
+
return False, _teacher_state_with_status(grade, unit, validation_msg)
|
| 513 |
+
|
| 514 |
+
if action == "save_add_overwrite":
|
| 515 |
+
return True, teacher_save_add_overwrite(grade, unit, question, answer, target_id)
|
| 516 |
+
|
| 517 |
+
if action == "update":
|
| 518 |
+
if _entry_by_id(grade, unit, target_id) is None:
|
| 519 |
+
return False, _teacher_state_with_status(grade, unit, "ບໍ່ພົບລາຍການສຳລັບອັບເດດ.")
|
| 520 |
+
return True, teacher_update_current(grade, unit, question, answer, target_id)
|
| 521 |
+
|
| 522 |
+
if action == "delete":
|
| 523 |
+
if _entry_by_id(grade, unit, target_id) is None:
|
| 524 |
+
return False, _teacher_state_with_status(grade, unit, "ບໍ່ພົບລາຍການສຳລັບລຶບ.")
|
| 525 |
+
return True, teacher_delete_current(grade, unit, target_id)
|
| 526 |
+
|
| 527 |
+
if action == "move":
|
| 528 |
+
move_error = _move_is_possible(edit)
|
| 529 |
+
if move_error:
|
| 530 |
+
return False, _teacher_state_with_status(grade, unit, move_error)
|
| 531 |
+
if direction < 0:
|
| 532 |
+
return True, teacher_move_current_up(grade, unit, target_id)
|
| 533 |
+
return True, teacher_move_current_down(grade, unit, target_id)
|
| 534 |
+
|
| 535 |
+
return False, _teacher_state_with_status(grade, unit, "ປະເພດຄຳຂໍບໍ່ຖືກຕ້ອງ.")
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
def guarded_pending_refresh(session: Dict[str, Any] | None):
|
| 539 |
+
if not auth_store.can_approve_edits(session):
|
| 540 |
+
return [], SUPER_ADMIN_ONLY_STATUS
|
| 541 |
+
return _pending_table_data(), "ໂຫຼດລາຍການທີ່ລໍຖ້າການອະນຸມັດແລ້ວ."
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def guarded_pending_on_select(session: Dict[str, Any] | None, evt: gr.SelectData):
|
| 545 |
+
if not auth_store.can_approve_edits(session):
|
| 546 |
+
return "", _empty_pending_preview(SUPER_ADMIN_ONLY_STATUS), "", SUPER_ADMIN_ONLY_STATUS
|
| 547 |
+
|
| 548 |
+
try:
|
| 549 |
+
row = list(evt.row_value)
|
| 550 |
+
edit_id = str(row[1]) if len(row) > 1 else ""
|
| 551 |
+
except Exception: # noqa: BLE001
|
| 552 |
+
edit_id = ""
|
| 553 |
+
|
| 554 |
+
edit = pending_edits.get_edit(edit_id)
|
| 555 |
+
if not edit:
|
| 556 |
+
return "", _empty_pending_preview("ບໍ່ພົບລາຍການທີ່ເລືອກ."), "", "ບໍ່ພົບລາຍການທີ່ເລືອກ."
|
| 557 |
+
return edit_id, _pending_preview_html(edit), "", f"ເລືອກຄຳຂໍ {edit_id}."
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def guarded_approve_pending_edit(
|
| 561 |
+
session: Dict[str, Any] | None,
|
| 562 |
+
edit_id: str,
|
| 563 |
+
review_note: str,
|
| 564 |
+
grade: str,
|
| 565 |
+
unit: str,
|
| 566 |
+
):
|
| 567 |
+
if not auth_store.can_approve_edits(session):
|
| 568 |
+
return (*_empty_teacher_editor(SUPER_ADMIN_ONLY_STATUS), [], "", _empty_pending_preview(), "", SUPER_ADMIN_ONLY_STATUS)
|
| 569 |
+
|
| 570 |
+
edit = pending_edits.get_edit(edit_id)
|
| 571 |
+
if not edit or edit.get("status") != pending_edits.STATUS_PENDING:
|
| 572 |
+
status = "ບໍ່ພົບຄຳຂໍທີ່ລໍຖ້າການອະນຸມັດ."
|
| 573 |
+
return (*teacher_on_unit_change(grade, unit), _pending_table_data(), "", _empty_pending_preview(status), "", status)
|
| 574 |
+
|
| 575 |
+
ok, teacher_result = _apply_pending_edit(edit)
|
| 576 |
+
if not ok:
|
| 577 |
+
status = teacher_result[-1]
|
| 578 |
+
return (*teacher_result, _pending_table_data(), edit_id, _pending_preview_html(edit), review_note, status)
|
| 579 |
+
|
| 580 |
+
reviewer = str((session or {}).get("username") or "superadmin")
|
| 581 |
+
pending_edits.set_edit_review(edit_id, pending_edits.STATUS_APPROVED, reviewer, review_note)
|
| 582 |
+
status = f"ອະນຸມັດຄຳຂໍ {edit_id} ສຳເລັດ. {teacher_result[-1]}"
|
| 583 |
+
return (*teacher_result, _pending_table_data(), "", _empty_pending_preview(), "", status)
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def guarded_reject_pending_edit(
|
| 587 |
+
session: Dict[str, Any] | None,
|
| 588 |
+
edit_id: str,
|
| 589 |
+
review_note: str,
|
| 590 |
+
grade: str,
|
| 591 |
+
unit: str,
|
| 592 |
+
):
|
| 593 |
+
if not auth_store.can_approve_edits(session):
|
| 594 |
+
return (*_empty_teacher_editor(SUPER_ADMIN_ONLY_STATUS), [], "", _empty_pending_preview(), "", SUPER_ADMIN_ONLY_STATUS)
|
| 595 |
+
|
| 596 |
+
edit = pending_edits.get_edit(edit_id)
|
| 597 |
+
if not edit or edit.get("status") != pending_edits.STATUS_PENDING:
|
| 598 |
+
status = "ບໍ່ພົບຄຳຂໍທີ່ລໍຖ້າການປະຕິເສດ."
|
| 599 |
+
return (*teacher_on_unit_change(grade, unit), _pending_table_data(), "", _empty_pending_preview(status), "", status)
|
| 600 |
+
|
| 601 |
+
reviewer = str((session or {}).get("username") or "superadmin")
|
| 602 |
+
pending_edits.set_edit_review(edit_id, pending_edits.STATUS_REJECTED, reviewer, review_note)
|
| 603 |
+
status = f"ປະຕິເສດຄຳຂໍ {edit_id} ແລ້ວ."
|
| 604 |
+
return (*teacher_on_unit_change(grade, unit), _pending_table_data(), "", _empty_pending_preview(), "", status)
|
| 605 |
+
|
| 606 |
+
|
| 607 |
def student_send_message(message, history):
|
| 608 |
cleaned_message = (message or "").strip()
|
| 609 |
current_history = list(history or [])
|
|
|
|
| 622 |
|
| 623 |
|
| 624 |
with gr.Blocks(title=APP_TITLE) as demo:
|
| 625 |
+
if APP_PANEL == "admin":
|
| 626 |
+
gr.Markdown(
|
| 627 |
+
"## ໜ້າຈັດການແຊັດບອດວິທະຍາສາດທຳມະຊາດ",
|
| 628 |
+
elem_classes=["app-header"],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 629 |
)
|
| 630 |
+
session_state = gr.State(auth_store.student_session())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 631 |
|
| 632 |
with gr.Column(visible=True, elem_classes=["teacher-lock"]) as teacher_login_box:
|
| 633 |
+
gr.Markdown("### ເຂົ້າສູ່ໜ້າຈັດການ")
|
| 634 |
+
gr.Markdown(ACCOUNT_LOGIN_HELP)
|
| 635 |
+
account_username_box = gr.Textbox(
|
| 636 |
+
label="ຊື່ຜູ້ໃຊ້",
|
| 637 |
+
placeholder=f"{auth_store.teacher_username()} / {auth_store.super_admin_username()}",
|
| 638 |
+
)
|
| 639 |
+
account_password_box = gr.Textbox(
|
| 640 |
+
label="ລະຫັດຜ່ານ",
|
| 641 |
type="password",
|
| 642 |
placeholder="ປ້ອນລະຫັດຜ່ານ",
|
| 643 |
)
|
| 644 |
+
btn_teacher_login = gr.Button("ເຂົ້າສູ່ລະບົບ", variant="primary")
|
| 645 |
teacher_login_status = gr.Markdown("")
|
| 646 |
|
| 647 |
+
with gr.Column(visible=False, elem_classes=["teacher-page"]) as teacher_workspace:
|
| 648 |
with gr.Row():
|
| 649 |
gr.Markdown("### ໜ້າຈັດການຂອງອາຈານ")
|
| 650 |
+
btn_teacher_logout = gr.Button("ອອກຈາກລະບົບ", variant="secondary")
|
| 651 |
|
| 652 |
+
gr.Markdown("ອາຈານສາມາດສົ່ງຄຳຂໍແກ້ໄຂ Q&A. Super Admin ຕ້ອງອະນຸມັດກ່ອນຈຶ່ງນຳໃຊ້ໃນໜ້ານັກຮຽນ.")
|
| 653 |
|
| 654 |
with gr.Row():
|
| 655 |
grade_dd = gr.Dropdown(
|
|
|
|
| 688 |
|
| 689 |
gr.Markdown("---")
|
| 690 |
with gr.Row():
|
| 691 |
+
btn_rebuild = gr.Button("Super Admin: ສ້າງ ແລະ ອັບໂຫຼດແຄຊໃໝ່")
|
| 692 |
|
| 693 |
status_md = gr.Markdown("")
|
| 694 |
|
|
|
|
| 700 |
row_count=(0, "dynamic"),
|
| 701 |
)
|
| 702 |
|
| 703 |
+
with gr.Column(visible=False) as approval_workspace:
|
| 704 |
+
with gr.Row():
|
| 705 |
+
gr.Markdown("### Super Admin: ອະນຸມັດຄຳຂໍແກ້ໄຂຈາກອາຈານ")
|
| 706 |
+
btn_refresh_pending = gr.Button("ໂຫຼດຄຳຂໍໃໝ່", variant="secondary")
|
|
|
|
| 707 |
|
| 708 |
+
pending_edits_table = gr.Dataframe(
|
| 709 |
+
headers=PENDING_HEADERS,
|
| 710 |
+
value=[],
|
| 711 |
+
interactive=True,
|
| 712 |
+
wrap=True,
|
| 713 |
+
row_count=(0, "dynamic"),
|
| 714 |
)
|
| 715 |
+
pending_selected_id_state = gr.State("")
|
| 716 |
+
pending_edit_preview = gr.HTML(value=_empty_pending_preview())
|
| 717 |
+
review_note_box = gr.Textbox(label="ໝາຍເຫດການກວດທານ (ບໍ່ບັງຄັບ)", lines=2)
|
| 718 |
+
with gr.Row():
|
| 719 |
+
btn_approve_pending = gr.Button("ອະນຸມັດ", variant="primary")
|
| 720 |
+
btn_reject_pending = gr.Button("ປະຕິເສດ", variant="secondary")
|
| 721 |
+
approval_status_md = gr.Markdown("")
|
| 722 |
+
|
| 723 |
+
grade_dd.change(
|
| 724 |
+
fn=guarded_teacher_on_grade_change,
|
| 725 |
+
inputs=[session_state, grade_dd],
|
| 726 |
+
outputs=[unit_dd, qa_table, q_box, a_box, answer_preview, current_id_state, status_md],
|
| 727 |
+
)
|
| 728 |
|
| 729 |
+
unit_dd.change(
|
| 730 |
+
fn=guarded_teacher_on_unit_change,
|
| 731 |
+
inputs=[session_state, grade_dd, unit_dd],
|
| 732 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, qa_table, status_md],
|
| 733 |
+
)
|
| 734 |
|
| 735 |
+
a_box.change(
|
| 736 |
+
fn=teacher_render_answer_preview,
|
| 737 |
+
inputs=[a_box],
|
| 738 |
+
outputs=[answer_preview],
|
| 739 |
+
)
|
| 740 |
|
| 741 |
+
btn_save.click(
|
| 742 |
+
fn=guarded_teacher_save_add_overwrite,
|
| 743 |
+
inputs=[session_state, grade_dd, unit_dd, q_box, a_box, current_id_state],
|
| 744 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, qa_table, status_md],
|
| 745 |
+
)
|
| 746 |
|
| 747 |
+
btn_update.click(
|
| 748 |
+
fn=guarded_teacher_update_current,
|
| 749 |
+
inputs=[session_state, grade_dd, unit_dd, q_box, a_box, current_id_state],
|
| 750 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, qa_table, status_md],
|
| 751 |
+
)
|
| 752 |
|
| 753 |
+
btn_delete.click(
|
| 754 |
+
fn=guarded_teacher_delete_current,
|
| 755 |
+
inputs=[session_state, grade_dd, unit_dd, current_id_state],
|
| 756 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, qa_table, status_md],
|
| 757 |
+
)
|
| 758 |
|
| 759 |
+
btn_move_up.click(
|
| 760 |
+
fn=guarded_teacher_move_current_up,
|
| 761 |
+
inputs=[session_state, grade_dd, unit_dd, current_id_state],
|
| 762 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, qa_table, status_md],
|
| 763 |
+
)
|
| 764 |
|
| 765 |
+
btn_move_down.click(
|
| 766 |
+
fn=guarded_teacher_move_current_down,
|
| 767 |
+
inputs=[session_state, grade_dd, unit_dd, current_id_state],
|
| 768 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, qa_table, status_md],
|
| 769 |
+
)
|
| 770 |
|
| 771 |
+
btn_rebuild.click(
|
| 772 |
+
fn=guarded_teacher_rebuild_cache_click,
|
| 773 |
+
inputs=[session_state],
|
| 774 |
+
outputs=[status_md],
|
| 775 |
+
)
|
| 776 |
|
| 777 |
+
qa_table.select(
|
| 778 |
+
fn=guarded_teacher_on_table_select,
|
| 779 |
+
inputs=[session_state],
|
| 780 |
+
outputs=[q_box, a_box, answer_preview, current_id_state, status_md],
|
| 781 |
+
)
|
| 782 |
|
| 783 |
+
btn_refresh_pending.click(
|
| 784 |
+
fn=guarded_pending_refresh,
|
| 785 |
+
inputs=[session_state],
|
| 786 |
+
outputs=[pending_edits_table, approval_status_md],
|
| 787 |
+
)
|
| 788 |
|
| 789 |
+
pending_edits_table.select(
|
| 790 |
+
fn=guarded_pending_on_select,
|
| 791 |
+
inputs=[session_state],
|
| 792 |
+
outputs=[pending_selected_id_state, pending_edit_preview, review_note_box, approval_status_md],
|
| 793 |
+
)
|
| 794 |
|
| 795 |
+
btn_approve_pending.click(
|
| 796 |
+
fn=guarded_approve_pending_edit,
|
| 797 |
+
inputs=[session_state, pending_selected_id_state, review_note_box, grade_dd, unit_dd],
|
| 798 |
+
outputs=[
|
| 799 |
+
q_box,
|
| 800 |
+
a_box,
|
| 801 |
+
answer_preview,
|
| 802 |
+
current_id_state,
|
| 803 |
+
qa_table,
|
| 804 |
+
status_md,
|
| 805 |
+
pending_edits_table,
|
| 806 |
+
pending_selected_id_state,
|
| 807 |
+
pending_edit_preview,
|
| 808 |
+
review_note_box,
|
| 809 |
+
approval_status_md,
|
| 810 |
+
],
|
| 811 |
+
)
|
| 812 |
|
| 813 |
+
btn_reject_pending.click(
|
| 814 |
+
fn=guarded_reject_pending_edit,
|
| 815 |
+
inputs=[session_state, pending_selected_id_state, review_note_box, grade_dd, unit_dd],
|
| 816 |
+
outputs=[
|
| 817 |
+
q_box,
|
| 818 |
+
a_box,
|
| 819 |
+
answer_preview,
|
| 820 |
+
current_id_state,
|
| 821 |
+
qa_table,
|
| 822 |
+
status_md,
|
| 823 |
+
pending_edits_table,
|
| 824 |
+
pending_selected_id_state,
|
| 825 |
+
pending_edit_preview,
|
| 826 |
+
review_note_box,
|
| 827 |
+
approval_status_md,
|
| 828 |
+
],
|
| 829 |
+
)
|
| 830 |
|
| 831 |
+
btn_teacher_login.click(
|
| 832 |
+
fn=login_account,
|
| 833 |
+
inputs=[account_username_box, account_password_box, grade_dd, unit_dd],
|
| 834 |
+
outputs=[
|
| 835 |
+
teacher_login_box,
|
| 836 |
+
teacher_workspace,
|
| 837 |
+
approval_workspace,
|
| 838 |
+
account_password_box,
|
| 839 |
+
session_state,
|
| 840 |
+
q_box,
|
| 841 |
+
a_box,
|
| 842 |
+
answer_preview,
|
| 843 |
+
current_id_state,
|
| 844 |
+
qa_table,
|
| 845 |
+
status_md,
|
| 846 |
+
teacher_login_status,
|
| 847 |
+
pending_edits_table,
|
| 848 |
+
pending_selected_id_state,
|
| 849 |
+
pending_edit_preview,
|
| 850 |
+
review_note_box,
|
| 851 |
+
approval_status_md,
|
| 852 |
+
],
|
| 853 |
+
)
|
| 854 |
|
| 855 |
+
account_password_box.submit(
|
| 856 |
+
fn=login_account,
|
| 857 |
+
inputs=[account_username_box, account_password_box, grade_dd, unit_dd],
|
| 858 |
+
outputs=[
|
| 859 |
+
teacher_login_box,
|
| 860 |
+
teacher_workspace,
|
| 861 |
+
approval_workspace,
|
| 862 |
+
account_password_box,
|
| 863 |
+
session_state,
|
| 864 |
+
q_box,
|
| 865 |
+
a_box,
|
| 866 |
+
answer_preview,
|
| 867 |
+
current_id_state,
|
| 868 |
+
qa_table,
|
| 869 |
+
status_md,
|
| 870 |
+
teacher_login_status,
|
| 871 |
+
pending_edits_table,
|
| 872 |
+
pending_selected_id_state,
|
| 873 |
+
pending_edit_preview,
|
| 874 |
+
review_note_box,
|
| 875 |
+
approval_status_md,
|
| 876 |
+
],
|
| 877 |
+
)
|
| 878 |
+
|
| 879 |
+
btn_teacher_logout.click(
|
| 880 |
+
fn=logout_account,
|
| 881 |
+
inputs=None,
|
| 882 |
+
outputs=[
|
| 883 |
+
teacher_login_box,
|
| 884 |
+
teacher_workspace,
|
| 885 |
+
approval_workspace,
|
| 886 |
+
account_password_box,
|
| 887 |
+
session_state,
|
| 888 |
+
q_box,
|
| 889 |
+
a_box,
|
| 890 |
+
answer_preview,
|
| 891 |
+
current_id_state,
|
| 892 |
+
qa_table,
|
| 893 |
+
status_md,
|
| 894 |
+
teacher_login_status,
|
| 895 |
+
pending_edits_table,
|
| 896 |
+
pending_selected_id_state,
|
| 897 |
+
pending_edit_preview,
|
| 898 |
+
review_note_box,
|
| 899 |
+
approval_status_md,
|
| 900 |
+
],
|
| 901 |
+
)
|
| 902 |
+
else:
|
| 903 |
+
gr.Markdown(
|
| 904 |
+
"## ແຊັດບອດຄວາມຮູ້ພື້ນຖານວິທະຍາສາດທຳມະຊາດ ສຳລັບຊັ້ນ ມ.1 - ມ.4",
|
| 905 |
+
elem_classes=["app-header"],
|
| 906 |
+
)
|
| 907 |
+
with gr.Column(elem_classes=["student-page"]):
|
| 908 |
+
gr.Markdown("### ຫ້ອງສົນທະນານັກຮຽນ")
|
| 909 |
+
gr.Markdown("ຖາມຄຳຖາມວິທະຍາສາດທຳມະຊາດເປັນພາສາລາວ.")
|
| 910 |
+
student_chatbot = gr.Chatbot(
|
| 911 |
+
value=[{"role": "assistant", "content": GUIDE_WELCOME_MESSAGE}],
|
| 912 |
+
label="ຜູ້ຊ່ວຍຕອບຄຳຖາມ",
|
| 913 |
+
)
|
| 914 |
+
with gr.Row(elem_classes=["student-input-row"]):
|
| 915 |
+
student_message_box = gr.Textbox(
|
| 916 |
+
placeholder="ພິມຄຳຖາມຂອງເຈົ້າ...",
|
| 917 |
+
show_label=False,
|
| 918 |
+
container=False,
|
| 919 |
+
scale=9,
|
| 920 |
+
)
|
| 921 |
+
btn_student_send = gr.Button("ສົ່ງ", variant="primary", scale=1, min_width=96)
|
| 922 |
+
|
| 923 |
+
btn_student_send.click(
|
| 924 |
+
fn=student_send_message,
|
| 925 |
+
inputs=[student_message_box, student_chatbot],
|
| 926 |
+
outputs=[student_message_box, student_chatbot],
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
student_message_box.submit(
|
| 930 |
+
fn=student_send_message,
|
| 931 |
+
inputs=[student_message_box, student_chatbot],
|
| 932 |
+
outputs=[student_message_box, student_chatbot],
|
| 933 |
+
)
|
| 934 |
|
| 935 |
if __name__ == "__main__":
|
| 936 |
demo.launch(css=GLOBAL_FONT_CSS)
|
auth_store.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import base64
|
| 2 |
+
import hashlib
|
| 3 |
+
import hmac
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import secrets
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Any, Dict, Optional
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
ROLE_STUDENT = "student"
|
| 13 |
+
ROLE_TEACHER = "teacher"
|
| 14 |
+
ROLE_SUPER_ADMIN = "super_admin"
|
| 15 |
+
|
| 16 |
+
AUTH_ITERATIONS = 390_000
|
| 17 |
+
AUTH_ALGORITHM = "pbkdf2_sha256"
|
| 18 |
+
|
| 19 |
+
DEFAULT_TEACHER_USERNAME = "teacher"
|
| 20 |
+
DEFAULT_SUPER_ADMIN_USERNAME = "superadmin"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@dataclass(frozen=True)
|
| 24 |
+
class LoginResult:
|
| 25 |
+
ok: bool
|
| 26 |
+
session: Dict[str, Any]
|
| 27 |
+
created: bool = False
|
| 28 |
+
reason: str = ""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def student_session() -> Dict[str, Any]:
|
| 32 |
+
return {"authenticated": False, "username": "", "role": ROLE_STUDENT}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def session_for(username: str, role: str) -> Dict[str, Any]:
|
| 36 |
+
return {"authenticated": True, "username": username, "role": role}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def clean_text(value: str | None) -> str:
|
| 40 |
+
return (value or "").strip()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def can_manage_qa(session: Optional[Dict[str, Any]]) -> bool:
|
| 44 |
+
return bool(session and session.get("role") in {ROLE_TEACHER, ROLE_SUPER_ADMIN})
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def can_approve_edits(session: Optional[Dict[str, Any]]) -> bool:
|
| 48 |
+
return bool(session and session.get("role") == ROLE_SUPER_ADMIN)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def role_label(role: str | None) -> str:
|
| 52 |
+
if role == ROLE_SUPER_ADMIN:
|
| 53 |
+
return "Super Admin"
|
| 54 |
+
if role == ROLE_TEACHER:
|
| 55 |
+
return "Teacher"
|
| 56 |
+
return "Student"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def auth_users_path(path: str | Path | None = None) -> Path:
|
| 60 |
+
if path is not None:
|
| 61 |
+
return Path(path)
|
| 62 |
+
return Path(os.getenv("AUTH_USERS_FILE", ".auth_users.json"))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def legacy_teacher_auth_path(path: str | Path | None = None) -> Path:
|
| 66 |
+
if path is not None:
|
| 67 |
+
return Path(path)
|
| 68 |
+
return Path(os.getenv("TEACHER_AUTH_FILE", ".teacher_auth.json"))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def teacher_username() -> str:
|
| 72 |
+
return clean_text(os.getenv("TEACHER_USERNAME")) or DEFAULT_TEACHER_USERNAME
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def super_admin_username() -> str:
|
| 76 |
+
return clean_text(os.getenv("SUPER_ADMIN_USERNAME")) or DEFAULT_SUPER_ADMIN_USERNAME
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _env_password_for_role(role: str) -> str:
|
| 80 |
+
if role == ROLE_TEACHER:
|
| 81 |
+
return clean_text(os.getenv("TEACHER_PASSWORD"))
|
| 82 |
+
if role == ROLE_SUPER_ADMIN:
|
| 83 |
+
return clean_text(os.getenv("SUPER_ADMIN_PASSWORD"))
|
| 84 |
+
return ""
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def username_for_role(role: str) -> str:
|
| 88 |
+
if role == ROLE_SUPER_ADMIN:
|
| 89 |
+
return super_admin_username()
|
| 90 |
+
if role == ROLE_TEACHER:
|
| 91 |
+
return teacher_username()
|
| 92 |
+
return ""
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def password_hash(password: str, salt: bytes | None = None, iterations: int = AUTH_ITERATIONS) -> Dict[str, Any]:
|
| 96 |
+
salt = salt or secrets.token_bytes(16)
|
| 97 |
+
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
| 98 |
+
return {
|
| 99 |
+
"algorithm": AUTH_ALGORITHM,
|
| 100 |
+
"iterations": iterations,
|
| 101 |
+
"salt": base64.b64encode(salt).decode("ascii"),
|
| 102 |
+
"hash": base64.b64encode(digest).decode("ascii"),
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def verify_password(password: str, stored: Dict[str, Any]) -> bool:
|
| 107 |
+
try:
|
| 108 |
+
if stored.get("algorithm") != AUTH_ALGORITHM:
|
| 109 |
+
return False
|
| 110 |
+
salt = base64.b64decode(stored["salt"])
|
| 111 |
+
expected = base64.b64decode(stored["hash"])
|
| 112 |
+
iterations = int(stored["iterations"])
|
| 113 |
+
except (KeyError, TypeError, ValueError):
|
| 114 |
+
return False
|
| 115 |
+
|
| 116 |
+
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations)
|
| 117 |
+
return hmac.compare_digest(digest, expected)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def _load_json(path: Path) -> Dict[str, Any]:
|
| 121 |
+
if not path.exists():
|
| 122 |
+
return {}
|
| 123 |
+
try:
|
| 124 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 125 |
+
return payload if isinstance(payload, dict) else {}
|
| 126 |
+
except (OSError, ValueError):
|
| 127 |
+
return {}
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def load_local_users(path: str | Path | None = None) -> Dict[str, Any]:
|
| 131 |
+
payload = _load_json(auth_users_path(path))
|
| 132 |
+
users = payload.get("users")
|
| 133 |
+
return users if isinstance(users, dict) else {}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _write_local_users(users: Dict[str, Any], path: str | Path | None = None) -> None:
|
| 137 |
+
target = auth_users_path(path)
|
| 138 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 139 |
+
payload = {"version": 1, "users": users}
|
| 140 |
+
tmp_path = target.with_name(f"{target.name}.tmp")
|
| 141 |
+
tmp_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 142 |
+
tmp_path.replace(target)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def save_local_user(role: str, username: str, password: str, path: str | Path | None = None) -> None:
|
| 146 |
+
if role not in {ROLE_TEACHER, ROLE_SUPER_ADMIN}:
|
| 147 |
+
raise ValueError(f"Unsupported role: {role}")
|
| 148 |
+
username = clean_text(username)
|
| 149 |
+
password = clean_text(password)
|
| 150 |
+
if not username or not password:
|
| 151 |
+
raise ValueError("Username and password are required")
|
| 152 |
+
|
| 153 |
+
users = load_local_users(path)
|
| 154 |
+
users[role] = {"username": username, "role": role, **password_hash(password)}
|
| 155 |
+
_write_local_users(users, path)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _legacy_teacher_hash_exists(path: str | Path | None = None) -> bool:
|
| 159 |
+
payload = _load_json(legacy_teacher_auth_path(path))
|
| 160 |
+
return payload.get("algorithm") == AUTH_ALGORITHM
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _verify_legacy_teacher(password: str, path: str | Path | None = None) -> bool:
|
| 164 |
+
payload = _load_json(legacy_teacher_auth_path(path))
|
| 165 |
+
return verify_password(password, payload)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def role_configured(role: str, auth_path: str | Path | None = None, legacy_path: str | Path | None = None) -> bool:
|
| 169 |
+
if _env_password_for_role(role):
|
| 170 |
+
return True
|
| 171 |
+
if role in load_local_users(auth_path):
|
| 172 |
+
return True
|
| 173 |
+
return role == ROLE_TEACHER and _legacy_teacher_hash_exists(legacy_path)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _role_for_setup_username(username: str, auth_path: str | Path | None, legacy_path: str | Path | None) -> str:
|
| 177 |
+
if username == teacher_username() and not role_configured(ROLE_TEACHER, auth_path, legacy_path):
|
| 178 |
+
return ROLE_TEACHER
|
| 179 |
+
if username == super_admin_username() and not role_configured(ROLE_SUPER_ADMIN, auth_path, legacy_path):
|
| 180 |
+
return ROLE_SUPER_ADMIN
|
| 181 |
+
return ""
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def authenticate_or_setup(
|
| 185 |
+
username: str | None,
|
| 186 |
+
password: str | None,
|
| 187 |
+
auth_path: str | Path | None = None,
|
| 188 |
+
legacy_path: str | Path | None = None,
|
| 189 |
+
) -> LoginResult:
|
| 190 |
+
username = clean_text(username)
|
| 191 |
+
password = clean_text(password)
|
| 192 |
+
if not username or not password:
|
| 193 |
+
return LoginResult(False, student_session(), reason="missing_credentials")
|
| 194 |
+
|
| 195 |
+
for role in (ROLE_SUPER_ADMIN, ROLE_TEACHER):
|
| 196 |
+
configured_username = username_for_role(role)
|
| 197 |
+
configured_password = _env_password_for_role(role)
|
| 198 |
+
if username == configured_username and configured_password:
|
| 199 |
+
if hmac.compare_digest(password, configured_password):
|
| 200 |
+
return LoginResult(True, session_for(username, role), reason="env_credentials")
|
| 201 |
+
return LoginResult(False, student_session(), reason="invalid_credentials")
|
| 202 |
+
|
| 203 |
+
for role, user in load_local_users(auth_path).items():
|
| 204 |
+
if role not in {ROLE_TEACHER, ROLE_SUPER_ADMIN}:
|
| 205 |
+
continue
|
| 206 |
+
if _env_password_for_role(role):
|
| 207 |
+
continue
|
| 208 |
+
if username == clean_text(user.get("username")) and verify_password(password, user):
|
| 209 |
+
return LoginResult(True, session_for(username, role), reason="local_credentials")
|
| 210 |
+
|
| 211 |
+
if (
|
| 212 |
+
username == teacher_username()
|
| 213 |
+
and not _env_password_for_role(ROLE_TEACHER)
|
| 214 |
+
and ROLE_TEACHER not in load_local_users(auth_path)
|
| 215 |
+
and _verify_legacy_teacher(password, legacy_path)
|
| 216 |
+
):
|
| 217 |
+
return LoginResult(True, session_for(username, ROLE_TEACHER), reason="legacy_teacher_credentials")
|
| 218 |
+
|
| 219 |
+
setup_role = _role_for_setup_username(username, auth_path, legacy_path)
|
| 220 |
+
if setup_role:
|
| 221 |
+
save_local_user(setup_role, username, password, auth_path)
|
| 222 |
+
return LoginResult(True, session_for(username, setup_role), created=True, reason="local_user_created")
|
| 223 |
+
|
| 224 |
+
return LoginResult(False, student_session(), reason="invalid_credentials")
|
pending_edits.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Dict, List, Optional
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
STATUS_PENDING = "pending"
|
| 10 |
+
STATUS_APPROVED = "approved"
|
| 11 |
+
STATUS_REJECTED = "rejected"
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def pending_edits_path(path: str | Path | None = None) -> Path:
|
| 15 |
+
if path is not None:
|
| 16 |
+
return Path(path)
|
| 17 |
+
return Path(os.getenv("PENDING_TEACHER_EDITS_FILE", ".pending_teacher_edits.jsonl"))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def utc_now_iso() -> str:
|
| 21 |
+
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _read_jsonl(path: Path) -> List[Dict[str, Any]]:
|
| 25 |
+
if not path.exists():
|
| 26 |
+
return []
|
| 27 |
+
|
| 28 |
+
rows: List[Dict[str, Any]] = []
|
| 29 |
+
try:
|
| 30 |
+
for line in path.read_text(encoding="utf-8").splitlines():
|
| 31 |
+
line = line.strip()
|
| 32 |
+
if not line:
|
| 33 |
+
continue
|
| 34 |
+
obj = json.loads(line)
|
| 35 |
+
if isinstance(obj, dict):
|
| 36 |
+
rows.append(obj)
|
| 37 |
+
except (OSError, ValueError):
|
| 38 |
+
return []
|
| 39 |
+
return rows
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _write_jsonl(rows: List[Dict[str, Any]], path: Path) -> None:
|
| 43 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
tmp_path = path.with_name(f"{path.name}.tmp")
|
| 45 |
+
content = "".join(json.dumps(row, ensure_ascii=False) + "\n" for row in rows)
|
| 46 |
+
tmp_path.write_text(content, encoding="utf-8")
|
| 47 |
+
tmp_path.replace(path)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def list_edits(status: Optional[str] = None, path: str | Path | None = None) -> List[Dict[str, Any]]:
|
| 51 |
+
rows = _read_jsonl(pending_edits_path(path))
|
| 52 |
+
if status:
|
| 53 |
+
rows = [row for row in rows if row.get("status") == status]
|
| 54 |
+
return rows
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def get_edit(edit_id: str, path: str | Path | None = None) -> Optional[Dict[str, Any]]:
|
| 58 |
+
edit_id = (edit_id or "").strip()
|
| 59 |
+
if not edit_id:
|
| 60 |
+
return None
|
| 61 |
+
return next((row for row in list_edits(path=path) if row.get("id") == edit_id), None)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def append_pending_edit(
|
| 65 |
+
action: str,
|
| 66 |
+
grade: str,
|
| 67 |
+
unit: str,
|
| 68 |
+
question: str = "",
|
| 69 |
+
answer: str = "",
|
| 70 |
+
target_id: str = "",
|
| 71 |
+
move_direction: int = 0,
|
| 72 |
+
submitted_by: str = "",
|
| 73 |
+
submitted_role: str = "",
|
| 74 |
+
path: str | Path | None = None,
|
| 75 |
+
) -> Dict[str, Any]:
|
| 76 |
+
target = pending_edits_path(path)
|
| 77 |
+
rows = _read_jsonl(target)
|
| 78 |
+
edit = {
|
| 79 |
+
"id": f"edit_{uuid.uuid4().hex[:12]}",
|
| 80 |
+
"status": STATUS_PENDING,
|
| 81 |
+
"action": action,
|
| 82 |
+
"grade": grade,
|
| 83 |
+
"unit": unit,
|
| 84 |
+
"question": question or "",
|
| 85 |
+
"answer": answer or "",
|
| 86 |
+
"target_id": target_id or "",
|
| 87 |
+
"move_direction": int(move_direction or 0),
|
| 88 |
+
"submitted_by": submitted_by or "",
|
| 89 |
+
"submitted_role": submitted_role or "",
|
| 90 |
+
"created_at": utc_now_iso(),
|
| 91 |
+
"reviewed_by": "",
|
| 92 |
+
"reviewed_at": "",
|
| 93 |
+
"review_note": "",
|
| 94 |
+
}
|
| 95 |
+
rows.append(edit)
|
| 96 |
+
_write_jsonl(rows, target)
|
| 97 |
+
return edit
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def set_edit_review(
|
| 101 |
+
edit_id: str,
|
| 102 |
+
status: str,
|
| 103 |
+
reviewed_by: str,
|
| 104 |
+
review_note: str = "",
|
| 105 |
+
path: str | Path | None = None,
|
| 106 |
+
) -> Optional[Dict[str, Any]]:
|
| 107 |
+
if status not in {STATUS_APPROVED, STATUS_REJECTED}:
|
| 108 |
+
raise ValueError(f"Unsupported review status: {status}")
|
| 109 |
+
|
| 110 |
+
target = pending_edits_path(path)
|
| 111 |
+
rows = _read_jsonl(target)
|
| 112 |
+
updated: Optional[Dict[str, Any]] = None
|
| 113 |
+
for row in rows:
|
| 114 |
+
if row.get("id") == edit_id:
|
| 115 |
+
row["status"] = status
|
| 116 |
+
row["reviewed_by"] = reviewed_by or ""
|
| 117 |
+
row["reviewed_at"] = utc_now_iso()
|
| 118 |
+
row["review_note"] = review_note or ""
|
| 119 |
+
updated = row
|
| 120 |
+
break
|
| 121 |
+
|
| 122 |
+
if updated is None:
|
| 123 |
+
return None
|
| 124 |
+
|
| 125 |
+
_write_jsonl(rows, target)
|
| 126 |
+
return updated
|
tests/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
tests/test_auth_store.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import unittest
|
| 4 |
+
from unittest.mock import patch
|
| 5 |
+
|
| 6 |
+
import auth_store
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class AuthStoreTests(unittest.TestCase):
|
| 10 |
+
def test_password_hash_verifies_only_matching_password(self):
|
| 11 |
+
stored = auth_store.password_hash("correct-password")
|
| 12 |
+
|
| 13 |
+
self.assertTrue(auth_store.verify_password("correct-password", stored))
|
| 14 |
+
self.assertFalse(auth_store.verify_password("wrong-password", stored))
|
| 15 |
+
|
| 16 |
+
def test_env_teacher_login(self):
|
| 17 |
+
env = {
|
| 18 |
+
"TEACHER_USERNAME": "science_teacher",
|
| 19 |
+
"TEACHER_PASSWORD": "teacher-secret",
|
| 20 |
+
"SUPER_ADMIN_PASSWORD": "",
|
| 21 |
+
}
|
| 22 |
+
with patch.dict(os.environ, env, clear=False):
|
| 23 |
+
result = auth_store.authenticate_or_setup("science_teacher", "teacher-secret")
|
| 24 |
+
|
| 25 |
+
self.assertTrue(result.ok)
|
| 26 |
+
self.assertEqual(result.session["role"], auth_store.ROLE_TEACHER)
|
| 27 |
+
self.assertEqual(result.session["username"], "science_teacher")
|
| 28 |
+
|
| 29 |
+
def test_local_json_login(self):
|
| 30 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 31 |
+
auth_path = os.path.join(tmp_dir, "auth_users.json")
|
| 32 |
+
env = {"TEACHER_PASSWORD": "", "SUPER_ADMIN_PASSWORD": "", "TEACHER_AUTH_FILE": os.path.join(tmp_dir, "missing.json")}
|
| 33 |
+
with patch.dict(os.environ, env, clear=False):
|
| 34 |
+
auth_store.save_local_user(auth_store.ROLE_TEACHER, "local_teacher", "local-secret", auth_path)
|
| 35 |
+
result = auth_store.authenticate_or_setup("local_teacher", "local-secret", auth_path=auth_path)
|
| 36 |
+
|
| 37 |
+
self.assertTrue(result.ok)
|
| 38 |
+
self.assertEqual(result.session["role"], auth_store.ROLE_TEACHER)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
if __name__ == "__main__":
|
| 42 |
+
unittest.main()
|
tests/test_pending_edits.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
import pending_edits
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class PendingEditsTests(unittest.TestCase):
|
| 9 |
+
def test_append_list_and_reject_pending_edit(self):
|
| 10 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 11 |
+
path = os.path.join(tmp_dir, "pending.jsonl")
|
| 12 |
+
edit = pending_edits.append_pending_edit(
|
| 13 |
+
action="update",
|
| 14 |
+
grade="M_1",
|
| 15 |
+
unit="U_01",
|
| 16 |
+
question="ຄຳຖາມທົດສອບ",
|
| 17 |
+
answer="ຄຳຕອບທົດສອບ",
|
| 18 |
+
target_id="M_1_U_01_manual_0001",
|
| 19 |
+
submitted_by="teacher",
|
| 20 |
+
submitted_role="teacher",
|
| 21 |
+
path=path,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
pending_rows = pending_edits.list_edits(status=pending_edits.STATUS_PENDING, path=path)
|
| 25 |
+
self.assertEqual(len(pending_rows), 1)
|
| 26 |
+
self.assertEqual(pending_rows[0]["id"], edit["id"])
|
| 27 |
+
|
| 28 |
+
rejected = pending_edits.set_edit_review(
|
| 29 |
+
edit["id"],
|
| 30 |
+
pending_edits.STATUS_REJECTED,
|
| 31 |
+
reviewed_by="superadmin",
|
| 32 |
+
review_note="Needs clearer answer",
|
| 33 |
+
path=path,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
self.assertIsNotNone(rejected)
|
| 37 |
+
self.assertEqual(rejected["status"], pending_edits.STATUS_REJECTED)
|
| 38 |
+
self.assertEqual(rejected["reviewed_by"], "superadmin")
|
| 39 |
+
self.assertEqual(pending_edits.list_edits(status=pending_edits.STATUS_PENDING, path=path), [])
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if __name__ == "__main__":
|
| 43 |
+
unittest.main()
|