Spaces:
Running
Running
Commit ·
ab6d17c
1
Parent(s): 122614e
Add durable weekly classroom checkpoints
Browse files- classroom_service.py +65 -21
- classroom_static/admin.html +1 -1
- classroom_static/classroom.css +2 -0
- classroom_static/student.html +4 -4
- classroom_static/student.js +8 -7
- classroom_static/teacher.html +4 -4
- classroom_static/teacher.js +9 -3
- tests/test_classroom.py +34 -1
classroom_service.py
CHANGED
|
@@ -7,7 +7,7 @@ from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect
|
|
| 7 |
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
|
| 10 |
-
ROOT=Path(__file__).resolve().parent; STATIC=ROOT/"classroom_static"; DATA=ROOT/"classroom_data"; TEMPLATES=DATA/"templates"; REPAIRS=DATA/"repairs"; PUBLISHED=ROOT/"projects"
|
| 11 |
RUNTIME=Path(os.getenv("CLASSROOM_DATA_DIR","/tmp/telearn_classroom")); DB=RUNTIME/"classroom.sqlite3"
|
| 12 |
PASSWORD=os.getenv("CLASSROOM_TEACHER_PASSWORD",""); REPO=os.getenv("CLASSROOM_DEMO_REPO",os.getenv("SPACE_ID","Telearn/Project_Demo")).strip(); DEMO_CLASS=os.getenv("CLASSROOM_DEMO_CLASS","2026Fall進階專題"); TOKEN=os.getenv("HF_TOKEN","").strip()
|
| 13 |
ALLOWED={".py",".json",".txt",".csv",".md",".toml",".yaml",".yml"}; ID_RE=re.compile(r"[^0-9A-Za-z_\-一-鿿]")
|
|
@@ -36,7 +36,10 @@ def now(): return int(time.time()*1000)
|
|
| 36 |
def init_db():
|
| 37 |
RUNTIME.mkdir(parents=True,exist_ok=True)
|
| 38 |
with lock,sqlite3.connect(DB) as c:
|
| 39 |
-
c.execute("""CREATE TABLE IF NOT EXISTS classroom_projects(class_code TEXT,student_id TEXT,display_name TEXT,week_id TEXT,project_name TEXT,draft_files TEXT,final_files TEXT,active_file TEXT,output TEXT,status TEXT,needs_help INTEGER,updated_at INTEGER,submitted_at INTEGER,PRIMARY KEY(class_code,student_id,week_id))""")
|
|
|
|
|
|
|
|
|
|
| 40 |
c.execute("""CREATE TABLE IF NOT EXISTS classroom_courses(class_code TEXT PRIMARY KEY,course_name TEXT,created_at INTEGER)""")
|
| 41 |
c.execute("""CREATE TABLE IF NOT EXISTS classroom_members(class_code TEXT,student_id TEXT,display_name TEXT,created_at INTEGER,PRIMARY KEY(class_code,student_id))""")
|
| 42 |
c.execute("""CREATE TABLE IF NOT EXISTS classroom_migrations(migration_id TEXT PRIMARY KEY,applied_at INTEGER)""")
|
|
@@ -56,7 +59,17 @@ def init_db():
|
|
| 56 |
submitted_at=int(record.get("submitted_at") or int(path.stat().st_mtime*1000));project_name=clean_label(record.get("project_name"),"")
|
| 57 |
c.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(code,code,now()))
|
| 58 |
c.execute("INSERT OR IGNORE INTO classroom_members VALUES(?,?,?,?)",(code,student_id,name,now()))
|
| 59 |
-
c.execute("INSERT OR IGNORE INTO classroom_projects VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",(code,student_id,name,week_id,project_name,json.dumps(files,ensure_ascii=False),json.dumps(files,ensure_ascii=False),"main.py","","idle",0,submitted_at,submitted_at))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
migration_id="lesson2_syntax_repair_20260916"
|
| 61 |
if not c.execute("SELECT 1 FROM classroom_migrations WHERE migration_id=?",(migration_id,)).fetchone():
|
| 62 |
for repair in REPAIRS.glob("*/*/*.py") if REPAIRS.is_dir() else []:
|
|
@@ -68,18 +81,18 @@ def init_db():
|
|
| 68 |
if final is not None:final["main.py"]=fixed
|
| 69 |
c.execute("UPDATE classroom_projects SET draft_files=?,final_files=?,updated_at=? WHERE class_code=? AND student_id=? AND week_id=?",(json.dumps(draft,ensure_ascii=False),json.dumps(final,ensure_ascii=False) if final is not None else None,now(),class_code,student_id,week_id))
|
| 70 |
c.execute("INSERT INTO classroom_migrations VALUES(?,?)",(migration_id,now()))
|
| 71 |
-
def empty(c,s,n,w): return {"class_code":c,"student_id":s,"display_name":n,"week_id":w,"project_name":"","files":{"main.py":"# 在這裡寫 Python\n"},"final_files":None,"active_file":"main.py","output":"","status":"idle","needs_help":False,"updated_at":now(),"submitted_at":None,"connected":True}
|
| 72 |
-
def from_row(r,connected=False): return {"class_code":r[0],"student_id":r[1],"display_name":r[2],"week_id":r[3],"project_name":r[4],"files":json.loads(r[5]),"final_files":json.loads(r[6]) if r[6] else None,"active_file":r[7],"output":r[8],"status":r[9],"needs_help":bool(r[10]),"updated_at":r[11],"submitted_at":r[12],"connected":connected}
|
| 73 |
-
SELECT="SELECT class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at FROM classroom_projects"
|
| 74 |
def load(c,s,n,w):
|
| 75 |
with lock,sqlite3.connect(DB) as db:r=db.execute(SELECT+" WHERE class_code=? AND student_id=? AND week_id=?",(c,s,w)).fetchone()
|
| 76 |
state=from_row(r,True) if r else empty(c,s,n,w); state["display_name"]=n; return state
|
| 77 |
def save(x):
|
| 78 |
-
values=(x["class_code"],x["student_id"],x["display_name"],x["week_id"],x["project_name"],json.dumps(x["files"],ensure_ascii=False),json.dumps(x["final_files"],ensure_ascii=False) if x["final_files"] else None,x["active_file"],x["output"][-40000:],x["status"],int(x["needs_help"]),x["updated_at"],x["submitted_at"])
|
| 79 |
with lock,sqlite3.connect(DB) as db:
|
| 80 |
db.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(x["class_code"],x["class_code"],now()))
|
| 81 |
db.execute("""INSERT INTO classroom_members VALUES(?,?,?,?) ON CONFLICT(class_code,student_id) DO UPDATE SET display_name=excluded.display_name""",(x["class_code"],x["student_id"],x["display_name"],now()))
|
| 82 |
-
db.execute("""INSERT INTO classroom_projects VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(class_code,student_id,week_id) DO UPDATE SET display_name=excluded.display_name,project_name=excluded.project_name,draft_files=excluded.draft_files,final_files=excluded.final_files,active_file=excluded.active_file,output=excluded.output,status=excluded.status,needs_help=excluded.needs_help,updated_at=excluded.updated_at,submitted_at=excluded.submitted_at""",values)
|
| 83 |
def catalog():
|
| 84 |
with lock,sqlite3.connect(DB) as db:
|
| 85 |
courses=db.execute("SELECT class_code,course_name FROM classroom_courses ORDER BY course_name,class_code").fetchall()
|
|
@@ -106,9 +119,12 @@ def get_submission(class_code,student_id,week_id):
|
|
| 106 |
if not row:raise HTTPException(404,"找不到這份提交")
|
| 107 |
return from_row(row)
|
| 108 |
def archived_paths(class_code,student_id=""):
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
def snapshot(c,w):
|
| 113 |
with lock,sqlite3.connect(DB) as db:rows=db.execute(SELECT+" WHERE class_code=? AND week_id=?",(c,w)).fetchall()
|
| 114 |
found={r[1]:from_row(r) for r in rows}
|
|
@@ -128,8 +144,12 @@ def template_files(w):
|
|
| 128 |
files={p.relative_to(root).as_posix():p.read_text(encoding="utf-8") for p in root.rglob("*") if p.is_file() and p.suffix.lower() in ALLOWED}
|
| 129 |
if not files:raise HTTPException(404,"這個 Lesson 尚未發布套版")
|
| 130 |
return norm_files(files)
|
| 131 |
-
def
|
| 132 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
if not student_root.is_dir():return found
|
| 134 |
for project_root in sorted(student_root.iterdir()):
|
| 135 |
match=re.match(r"^(week\d{2})_(.+)$",project_root.name)
|
|
@@ -165,12 +185,24 @@ def persist_catalog(message,deletions=None):
|
|
| 165 |
except Exception as exc:
|
| 166 |
logger.exception("Could not persist classroom roster to %s",REPO)
|
| 167 |
return hf_failure_message(exc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
def finals(c,w):return [x for x in snapshot(c,w) if x.get("final_files")]
|
| 169 |
def make_zip(c,w):
|
| 170 |
b=io.BytesIO()
|
| 171 |
with zipfile.ZipFile(b,"w",zipfile.ZIP_DEFLATED) as z:
|
| 172 |
for x in finals(c,w):
|
| 173 |
-
root=PurePosixPath(
|
| 174 |
for path,text in x["final_files"].items():z.writestr((root/path).as_posix(),text)
|
| 175 |
return b.getvalue()
|
| 176 |
|
|
@@ -253,9 +285,17 @@ async def delete_student(req:StudentDelete):
|
|
| 253 |
def template(week_id):return {"week_id":week_id,"files":template_files(week_id)}
|
| 254 |
@router.get("/api/classroom/progress")
|
| 255 |
def progress(class_code:str,student_id:str,display_name:str=""):
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
merged
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
return {"progress":[merged[key] for key in sorted(merged)]}
|
| 260 |
@router.post("/api/classroom/export")
|
| 261 |
def export(req:TeacherRequest):
|
|
@@ -271,7 +311,7 @@ def publish(req:TeacherRequest):
|
|
| 271 |
from huggingface_hub import CommitOperationAdd,CommitOperationDelete,HfApi
|
| 272 |
api=HfApi(token=TOKEN); existing=set(api.list_repo_files(repo_id=REPO,repo_type="space")); desired={}; prefixes=[]
|
| 273 |
for x in states:
|
| 274 |
-
root=PurePosixPath("projects",
|
| 275 |
for path,text in x["final_files"].items():desired[(root/path).as_posix()]=text
|
| 276 |
stale=sorted(path for path in existing if any(path.startswith(prefix) for prefix in prefixes) and path not in desired)
|
| 277 |
ops=[CommitOperationDelete(path_in_repo=path) for path in stale]
|
|
@@ -292,16 +332,20 @@ async def student_ws(ws:WebSocket):
|
|
| 292 |
students[key]=ws;state=load(c,s,n,w);state["connected"]=True;live[key]=state;save(state);await ws.send_json({"type":"restore","state":state});await broadcast(c,w)
|
| 293 |
try:
|
| 294 |
while True:
|
| 295 |
-
m=await ws.receive_json();kind=m.get("type");state["updated_at"]=now()
|
| 296 |
if kind=="project":
|
| 297 |
state["files"]=norm_files(m.get("files"));state["project_name"]=clean_label(m.get("project_name"),"");active=safe_path(m.get("active_file","main.py"));state["active_file"]=active if active in state["files"] else "main.py"
|
| 298 |
elif kind=="output":state["output"]=str(m.get("output",""))[-40000:]
|
| 299 |
elif kind=="status":state["status"]=m.get("status") if m.get("status") in {"idle","running","success","error"} else "idle"
|
| 300 |
elif kind=="help":state["needs_help"]=bool(m.get("needs_help"))
|
|
|
|
|
|
|
| 301 |
elif kind=="submit":state["files"]=norm_files(m.get("files",state["files"]));state["final_files"]=dict(state["files"]);state["submitted_at"]=now()
|
| 302 |
-
elif kind=="ping":await ws.send_json({"type":"pong","needs_help":state["needs_help"],"submitted_at":state["submitted_at"]});continue
|
| 303 |
else:continue
|
| 304 |
-
save(state)
|
|
|
|
|
|
|
| 305 |
except (WebSocketDisconnect,json.JSONDecodeError):pass
|
| 306 |
finally:
|
| 307 |
if students.get(key) is ws:students.pop(key,None);state["connected"]=False;state["status"]="idle";save(state);await broadcast(c,w)
|
|
|
|
| 7 |
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
|
| 8 |
from pydantic import BaseModel
|
| 9 |
|
| 10 |
+
ROOT=Path(__file__).resolve().parent; STATIC=ROOT/"classroom_static"; DATA=ROOT/"classroom_data"; TEMPLATES=DATA/"templates"; REPAIRS=DATA/"repairs"; CHECKPOINTS=DATA/"checkpoints"; PUBLISHED=ROOT/"projects"
|
| 11 |
RUNTIME=Path(os.getenv("CLASSROOM_DATA_DIR","/tmp/telearn_classroom")); DB=RUNTIME/"classroom.sqlite3"
|
| 12 |
PASSWORD=os.getenv("CLASSROOM_TEACHER_PASSWORD",""); REPO=os.getenv("CLASSROOM_DEMO_REPO",os.getenv("SPACE_ID","Telearn/Project_Demo")).strip(); DEMO_CLASS=os.getenv("CLASSROOM_DEMO_CLASS","2026Fall進階專題"); TOKEN=os.getenv("HF_TOKEN","").strip()
|
| 13 |
ALLOWED={".py",".json",".txt",".csv",".md",".toml",".yaml",".yml"}; ID_RE=re.compile(r"[^0-9A-Za-z_\-一-鿿]")
|
|
|
|
| 36 |
def init_db():
|
| 37 |
RUNTIME.mkdir(parents=True,exist_ok=True)
|
| 38 |
with lock,sqlite3.connect(DB) as c:
|
| 39 |
+
c.execute("""CREATE TABLE IF NOT EXISTS classroom_projects(class_code TEXT,student_id TEXT,display_name TEXT,week_id TEXT,project_name TEXT,draft_files TEXT,final_files TEXT,active_file TEXT,output TEXT,status TEXT,needs_help INTEGER,updated_at INTEGER,submitted_at INTEGER,checkpoint_files TEXT,checkpoint_at INTEGER,PRIMARY KEY(class_code,student_id,week_id))""")
|
| 40 |
+
columns={row[1] for row in c.execute("PRAGMA table_info(classroom_projects)")}
|
| 41 |
+
if "checkpoint_files" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN checkpoint_files TEXT")
|
| 42 |
+
if "checkpoint_at" not in columns:c.execute("ALTER TABLE classroom_projects ADD COLUMN checkpoint_at INTEGER")
|
| 43 |
c.execute("""CREATE TABLE IF NOT EXISTS classroom_courses(class_code TEXT PRIMARY KEY,course_name TEXT,created_at INTEGER)""")
|
| 44 |
c.execute("""CREATE TABLE IF NOT EXISTS classroom_members(class_code TEXT,student_id TEXT,display_name TEXT,created_at INTEGER,PRIMARY KEY(class_code,student_id))""")
|
| 45 |
c.execute("""CREATE TABLE IF NOT EXISTS classroom_migrations(migration_id TEXT PRIMARY KEY,applied_at INTEGER)""")
|
|
|
|
| 59 |
submitted_at=int(record.get("submitted_at") or int(path.stat().st_mtime*1000));project_name=clean_label(record.get("project_name"),"")
|
| 60 |
c.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(code,code,now()))
|
| 61 |
c.execute("INSERT OR IGNORE INTO classroom_members VALUES(?,?,?,?)",(code,student_id,name,now()))
|
| 62 |
+
c.execute("""INSERT OR IGNORE INTO classroom_projects(class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)""",(code,student_id,name,week_id,project_name,json.dumps(files,ensure_ascii=False),json.dumps(files,ensure_ascii=False),"main.py","","idle",0,submitted_at,submitted_at))
|
| 63 |
+
if CHECKPOINTS.is_dir():
|
| 64 |
+
for path in CHECKPOINTS.glob("*/*/*.json"):
|
| 65 |
+
try:record=json.loads(path.read_text(encoding="utf-8"));files=norm_files(record.get("files",{}));code=clean(record.get("class_code"),"");student_id=clean(record.get("student_id"),"");name=clean_label(record.get("display_name"),"");week_id=clean(record.get("week_id"),"")
|
| 66 |
+
except (OSError,ValueError,TypeError):continue
|
| 67 |
+
if not all((code,student_id,name,week_id)):continue
|
| 68 |
+
checkpoint_at=int(record.get("checkpoint_at") or int(path.stat().st_mtime*1000));project_name=clean_label(record.get("project_name"),"")
|
| 69 |
+
encoded=json.dumps(files,ensure_ascii=False)
|
| 70 |
+
c.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(code,code,now()))
|
| 71 |
+
c.execute("INSERT OR IGNORE INTO classroom_members VALUES(?,?,?,?)",(code,student_id,name,now()))
|
| 72 |
+
c.execute("""INSERT INTO classroom_projects(class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(class_code,student_id,week_id) DO UPDATE SET checkpoint_files=excluded.checkpoint_files,checkpoint_at=excluded.checkpoint_at,draft_files=CASE WHEN excluded.checkpoint_at>=classroom_projects.updated_at THEN excluded.draft_files ELSE classroom_projects.draft_files END,project_name=CASE WHEN excluded.checkpoint_at>=classroom_projects.updated_at THEN excluded.project_name ELSE classroom_projects.project_name END,updated_at=MAX(classroom_projects.updated_at,excluded.updated_at)""",(code,student_id,name,week_id,project_name,encoded,None,"main.py","","idle",0,checkpoint_at,None,encoded,checkpoint_at))
|
| 73 |
migration_id="lesson2_syntax_repair_20260916"
|
| 74 |
if not c.execute("SELECT 1 FROM classroom_migrations WHERE migration_id=?",(migration_id,)).fetchone():
|
| 75 |
for repair in REPAIRS.glob("*/*/*.py") if REPAIRS.is_dir() else []:
|
|
|
|
| 81 |
if final is not None:final["main.py"]=fixed
|
| 82 |
c.execute("UPDATE classroom_projects SET draft_files=?,final_files=?,updated_at=? WHERE class_code=? AND student_id=? AND week_id=?",(json.dumps(draft,ensure_ascii=False),json.dumps(final,ensure_ascii=False) if final is not None else None,now(),class_code,student_id,week_id))
|
| 83 |
c.execute("INSERT INTO classroom_migrations VALUES(?,?)",(migration_id,now()))
|
| 84 |
+
def empty(c,s,n,w): return {"class_code":c,"student_id":s,"display_name":n,"week_id":w,"project_name":"","files":{"main.py":"# 在這裡寫 Python\n"},"final_files":None,"checkpoint_files":None,"active_file":"main.py","output":"","status":"idle","needs_help":False,"updated_at":now(),"submitted_at":None,"checkpoint_at":None,"connected":True}
|
| 85 |
+
def from_row(r,connected=False): return {"class_code":r[0],"student_id":r[1],"display_name":r[2],"week_id":r[3],"project_name":r[4],"files":json.loads(r[5]),"final_files":json.loads(r[6]) if r[6] else None,"active_file":r[7],"output":r[8],"status":r[9],"needs_help":bool(r[10]),"updated_at":r[11],"submitted_at":r[12],"checkpoint_files":json.loads(r[13]) if r[13] else None,"checkpoint_at":r[14],"connected":connected}
|
| 86 |
+
SELECT="SELECT class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at FROM classroom_projects"
|
| 87 |
def load(c,s,n,w):
|
| 88 |
with lock,sqlite3.connect(DB) as db:r=db.execute(SELECT+" WHERE class_code=? AND student_id=? AND week_id=?",(c,s,w)).fetchone()
|
| 89 |
state=from_row(r,True) if r else empty(c,s,n,w); state["display_name"]=n; return state
|
| 90 |
def save(x):
|
| 91 |
+
values=(x["class_code"],x["student_id"],x["display_name"],x["week_id"],x["project_name"],json.dumps(x["files"],ensure_ascii=False),json.dumps(x["final_files"],ensure_ascii=False) if x["final_files"] else None,x["active_file"],x["output"][-40000:],x["status"],int(x["needs_help"]),x["updated_at"],x["submitted_at"],json.dumps(x["checkpoint_files"],ensure_ascii=False) if x.get("checkpoint_files") else None,x.get("checkpoint_at"))
|
| 92 |
with lock,sqlite3.connect(DB) as db:
|
| 93 |
db.execute("INSERT OR IGNORE INTO classroom_courses VALUES(?,?,?)",(x["class_code"],x["class_code"],now()))
|
| 94 |
db.execute("""INSERT INTO classroom_members VALUES(?,?,?,?) ON CONFLICT(class_code,student_id) DO UPDATE SET display_name=excluded.display_name""",(x["class_code"],x["student_id"],x["display_name"],now()))
|
| 95 |
+
db.execute("""INSERT INTO classroom_projects(class_code,student_id,display_name,week_id,project_name,draft_files,final_files,active_file,output,status,needs_help,updated_at,submitted_at,checkpoint_files,checkpoint_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(class_code,student_id,week_id) DO UPDATE SET display_name=excluded.display_name,project_name=excluded.project_name,draft_files=excluded.draft_files,final_files=excluded.final_files,active_file=excluded.active_file,output=excluded.output,status=excluded.status,needs_help=excluded.needs_help,updated_at=excluded.updated_at,submitted_at=excluded.submitted_at,checkpoint_files=excluded.checkpoint_files,checkpoint_at=excluded.checkpoint_at""",values)
|
| 96 |
def catalog():
|
| 97 |
with lock,sqlite3.connect(DB) as db:
|
| 98 |
courses=db.execute("SELECT class_code,course_name FROM classroom_courses ORDER BY course_name,class_code").fetchall()
|
|
|
|
| 119 |
if not row:raise HTTPException(404,"找不到這份提交")
|
| 120 |
return from_row(row)
|
| 121 |
def archived_paths(class_code,student_id=""):
|
| 122 |
+
found=[]
|
| 123 |
+
for kind in ("submissions","checkpoints"):
|
| 124 |
+
root=DATA/kind/clean(class_code,"")
|
| 125 |
+
target=root/clean(student_id,"") if student_id else root
|
| 126 |
+
if target.is_dir():found.extend(path.relative_to(ROOT).as_posix() for path in target.rglob("*.json"))
|
| 127 |
+
return found
|
| 128 |
def snapshot(c,w):
|
| 129 |
with lock,sqlite3.connect(DB) as db:rows=db.execute(SELECT+" WHERE class_code=? AND week_id=?",(c,w)).fetchall()
|
| 130 |
found={r[1]:from_row(r) for r in rows}
|
|
|
|
| 144 |
files={p.relative_to(root).as_posix():p.read_text(encoding="utf-8") for p in root.rglob("*") if p.is_file() and p.suffix.lower() in ALLOWED}
|
| 145 |
if not files:raise HTTPException(404,"這個 Lesson 尚未發布套版")
|
| 146 |
return norm_files(files)
|
| 147 |
+
def demo_class_name(class_code):
|
| 148 |
+
with lock,sqlite3.connect(DB) as db:row=db.execute("SELECT course_name FROM classroom_courses WHERE class_code=?",(clean(class_code,""),)).fetchone()
|
| 149 |
+
name=clean_label(row[0],"") if row else ""
|
| 150 |
+
return name if name.startswith("2026Fall進階專題") else DEMO_CLASS
|
| 151 |
+
def published_progress(class_code,display_name):
|
| 152 |
+
student_root=PUBLISHED/demo_class_name(class_code)/clean(display_name,"student"); found=[]
|
| 153 |
if not student_root.is_dir():return found
|
| 154 |
for project_root in sorted(student_root.iterdir()):
|
| 155 |
match=re.match(r"^(week\d{2})_(.+)$",project_root.name)
|
|
|
|
| 185 |
except Exception as exc:
|
| 186 |
logger.exception("Could not persist classroom roster to %s",REPO)
|
| 187 |
return hf_failure_message(exc)
|
| 188 |
+
def persist_checkpoint(state):
|
| 189 |
+
if not TOKEN:return "進度已暫存在教室,但尚未永久寫入 Space;請設定 HF_TOKEN。"
|
| 190 |
+
try:
|
| 191 |
+
from huggingface_hub import CommitOperationAdd,HfApi
|
| 192 |
+
payload={key:state[key] for key in ("class_code","student_id","display_name","week_id","project_name","checkpoint_at")}|{"files":state["checkpoint_files"]}
|
| 193 |
+
content=(json.dumps(payload,ensure_ascii=False,indent=2)+"\n").encode()
|
| 194 |
+
path=PurePosixPath("classroom_data","checkpoints",clean(state["class_code"],""),clean(state["student_id"],""),f"{clean(state['week_id'],'week')}.json").as_posix()
|
| 195 |
+
with persist_lock:HfApi(token=TOKEN).create_commit(repo_id=REPO,repo_type="space",operations=[CommitOperationAdd(path_in_repo=path,path_or_fileobj=content)],commit_message=f"Checkpoint {state['class_code']} {state['student_id']} {state['week_id']}")
|
| 196 |
+
return ""
|
| 197 |
+
except Exception as exc:
|
| 198 |
+
logger.exception("Could not persist student checkpoint to %s",REPO)
|
| 199 |
+
return hf_failure_message(exc)
|
| 200 |
def finals(c,w):return [x for x in snapshot(c,w) if x.get("final_files")]
|
| 201 |
def make_zip(c,w):
|
| 202 |
b=io.BytesIO()
|
| 203 |
with zipfile.ZipFile(b,"w",zipfile.ZIP_DEFLATED) as z:
|
| 204 |
for x in finals(c,w):
|
| 205 |
+
root=PurePosixPath(demo_class_name(c),clean(x["display_name"],"student"),f"{w}_{clean(x['project_name'],'project')}")
|
| 206 |
for path,text in x["final_files"].items():z.writestr((root/path).as_posix(),text)
|
| 207 |
return b.getvalue()
|
| 208 |
|
|
|
|
| 285 |
def template(week_id):return {"week_id":week_id,"files":template_files(week_id)}
|
| 286 |
@router.get("/api/classroom/progress")
|
| 287 |
def progress(class_code:str,student_id:str,display_name:str=""):
|
| 288 |
+
class_code=clean(class_code,"L6A");student_id=clean(student_id,"student")
|
| 289 |
+
with lock,sqlite3.connect(DB) as db:rows=db.execute("SELECT week_id,project_name,final_files,submitted_at,checkpoint_files,checkpoint_at FROM classroom_projects WHERE class_code=? AND student_id=? AND (final_files IS NOT NULL OR checkpoint_files IS NOT NULL) ORDER BY week_id",(class_code,student_id)).fetchall()
|
| 290 |
+
merged={p["week_id"]:p for p in published_progress(class_code,display_name)}
|
| 291 |
+
for week_id,project_name,final_files,submitted_at,checkpoint_files,checkpoint_at in rows:
|
| 292 |
+
candidates=[]
|
| 293 |
+
if checkpoint_files:candidates.append({"week_id":week_id,"project_name":project_name,"files":json.loads(checkpoint_files),"submitted_at":checkpoint_at,"source":"checkpoint"})
|
| 294 |
+
if final_files:candidates.append({"week_id":week_id,"project_name":project_name,"files":json.loads(final_files),"submitted_at":submitted_at,"source":"classroom"})
|
| 295 |
+
if candidates:
|
| 296 |
+
latest=max(candidates,key=lambda item:item["submitted_at"] or 0)
|
| 297 |
+
previous=merged.get(week_id)
|
| 298 |
+
if not previous or (latest["submitted_at"] or 0)>=(previous["submitted_at"] or 0):merged[week_id]=latest
|
| 299 |
return {"progress":[merged[key] for key in sorted(merged)]}
|
| 300 |
@router.post("/api/classroom/export")
|
| 301 |
def export(req:TeacherRequest):
|
|
|
|
| 311 |
from huggingface_hub import CommitOperationAdd,CommitOperationDelete,HfApi
|
| 312 |
api=HfApi(token=TOKEN); existing=set(api.list_repo_files(repo_id=REPO,repo_type="space")); desired={}; prefixes=[]
|
| 313 |
for x in states:
|
| 314 |
+
root=PurePosixPath("projects",demo_class_name(class_code),clean(x["display_name"],"student"),f"{week_id}_{clean(x['project_name'],'project')}"); prefix=root.as_posix()+"/"; prefixes.append(prefix)
|
| 315 |
for path,text in x["final_files"].items():desired[(root/path).as_posix()]=text
|
| 316 |
stale=sorted(path for path in existing if any(path.startswith(prefix) for prefix in prefixes) and path not in desired)
|
| 317 |
ops=[CommitOperationDelete(path_in_repo=path) for path in stale]
|
|
|
|
| 332 |
students[key]=ws;state=load(c,s,n,w);state["connected"]=True;live[key]=state;save(state);await ws.send_json({"type":"restore","state":state});await broadcast(c,w)
|
| 333 |
try:
|
| 334 |
while True:
|
| 335 |
+
m=await ws.receive_json();kind=m.get("type");state["updated_at"]=now();checkpoint_requested=False
|
| 336 |
if kind=="project":
|
| 337 |
state["files"]=norm_files(m.get("files"));state["project_name"]=clean_label(m.get("project_name"),"");active=safe_path(m.get("active_file","main.py"));state["active_file"]=active if active in state["files"] else "main.py"
|
| 338 |
elif kind=="output":state["output"]=str(m.get("output",""))[-40000:]
|
| 339 |
elif kind=="status":state["status"]=m.get("status") if m.get("status") in {"idle","running","success","error"} else "idle"
|
| 340 |
elif kind=="help":state["needs_help"]=bool(m.get("needs_help"))
|
| 341 |
+
elif kind=="checkpoint":
|
| 342 |
+
state["files"]=norm_files(m.get("files",state["files"]));state["project_name"]=clean_label(m.get("project_name",state["project_name"]),"");state["checkpoint_files"]=dict(state["files"]);state["checkpoint_at"]=now();checkpoint_requested=True
|
| 343 |
elif kind=="submit":state["files"]=norm_files(m.get("files",state["files"]));state["final_files"]=dict(state["files"]);state["submitted_at"]=now()
|
| 344 |
+
elif kind=="ping":await ws.send_json({"type":"pong","needs_help":state["needs_help"],"submitted_at":state["submitted_at"],"checkpoint_at":state.get("checkpoint_at")});continue
|
| 345 |
else:continue
|
| 346 |
+
save(state)
|
| 347 |
+
warning=await asyncio.to_thread(persist_checkpoint,state) if checkpoint_requested else ""
|
| 348 |
+
await ws.send_json({"type":"ack","needs_help":state["needs_help"],"submitted_at":state["submitted_at"],"checkpoint_at":state.get("checkpoint_at"),"checkpoint_warning":warning});await broadcast(c,w)
|
| 349 |
except (WebSocketDisconnect,json.JSONDecodeError):pass
|
| 350 |
finally:
|
| 351 |
if students.get(key) is ws:students.pop(key,None);state["connected"]=False;state["status"]="idle";save(state);await broadcast(c,w)
|
classroom_static/admin.html
CHANGED
|
@@ -4,7 +4,7 @@
|
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 6 |
<title>Telearn 內容管理後台</title>
|
| 7 |
-
<link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-
|
| 8 |
<link rel="stylesheet" href="/classroom-assets/admin.css?v=2026fall-6">
|
| 9 |
</head>
|
| 10 |
<body class="admin-body">
|
|
|
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width,initial-scale=1">
|
| 6 |
<title>Telearn 內容管理後台</title>
|
| 7 |
+
<link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-7">
|
| 8 |
<link rel="stylesheet" href="/classroom-assets/admin.css?v=2026fall-6">
|
| 9 |
</head>
|
| 10 |
<body class="admin-body">
|
classroom_static/classroom.css
CHANGED
|
@@ -234,6 +234,8 @@ button:disabled { cursor: not-allowed; opacity: .48; }
|
|
| 234 |
font-weight: 800;
|
| 235 |
}
|
| 236 |
.copy-button:hover { background: var(--action-soft); }
|
|
|
|
|
|
|
| 237 |
|
| 238 |
.editor-toolbar { display: flex; align-items: center; gap: var(--space-sm); }
|
| 239 |
.file-name { font: 700 .875rem/1 "SFMono-Regular", Consolas, monospace; color: oklch(0.82 0.025 255); }
|
|
|
|
| 234 |
font-weight: 800;
|
| 235 |
}
|
| 236 |
.copy-button:hover { background: var(--action-soft); }
|
| 237 |
+
.checkpoint-action { border-color: oklch(0.72 0.1 150); color: oklch(0.38 0.13 150); }
|
| 238 |
+
.checkpoint-action:hover { background: var(--success-soft); }
|
| 239 |
|
| 240 |
.editor-toolbar { display: flex; align-items: center; gap: var(--space-sm); }
|
| 241 |
.file-name { font: 700 .875rem/1 "SFMono-Regular", Consolas, monospace; color: oklch(0.82 0.025 255); }
|
classroom_static/student.html
CHANGED
|
@@ -1,10 +1,10 @@
|
|
| 1 |
-
<!doctype html><html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Python 專案教室|學生工作區</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css"><link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-
|
| 2 |
<header class="app-header"><div class="brand"><div class="brand-mark">Py</div><div class="brand-copy"><strong>Python 專案教室</strong><span id="studentIdentity">尚未進入教室</span></div></div><div class="header-actions"><div class="connection-state"><i class="status-dot" id="connectionDot"></i><span id="connectionText">未連線</span></div><button class="btn help compact" id="helpButton">請老師協助</button><button class="btn secondary compact" id="identityButton">更換身分</button></div></header>
|
| 3 |
-
<section class="project-bar"><div class="project-context"><label for="weekSelect">Lesson</label><select id="weekSelect"></select><label for="projectName">專案</label><input id="projectName" maxlength="36"></div><div class="project-actions"><button class="copy-button" id="templateButton">匯入專案起始套版</button><button class="copy-button" id="progressButton">選擇舊進度</button><button class="copy-button" id="importButton">匯入 .py / ZIP</button><button class="copy-button" id="exportButton">匯出專案</button><button class="btn compact" id="submitButton">提交
|
| 4 |
<nav class="mobile-tabs" role="tablist"><button class="mobile-tab" data-panel="referencePanel">專案/語法</button><button class="mobile-tab" data-panel="editorPanel" aria-selected="true">程式</button><button class="mobile-tab" data-panel="consolePanel">執行結果</button></nav>
|
| 5 |
<main class="student-layout"><aside class="panel reference-panel" id="referencePanel"><div class="side-tabs"><button class="side-tab active" data-side="filesView">專案檔案</button><button class="side-tab" data-side="syntaxView">語法查詢</button></div><section class="side-view" id="filesView"><div class="panel-heading"><h1>檔案夾</h1><button class="copy-button" id="newFileButton">+新增</button></div><div class="file-list" id="fileList"></div><p class="side-note">入口固定為 <code>main.py</code>,可用 <code>import</code> 引入其他 Python 檔。</p></section><section class="side-view" id="syntaxView" hidden><div class="panel-heading"><h1>Python 語法查詢</h1><span id="snippetCount">0 項</span></div><div class="search-wrap"><label class="field-label" for="syntaxSearch">輸入語法或用途</label><input class="text-field" id="syntaxSearch" type="search"><div class="chip-row" id="categoryFilters"></div></div><div class="snippet-list" id="snippetList"></div></section></aside>
|
| 6 |
<section class="panel editor-panel mobile-active" id="editorPanel"><div class="panel-heading dark"><span class="file-name" id="activeFileLabel">main.py</span><div class="editor-toolbar"><button class="btn stop compact" id="stopButton" disabled>停止</button><button class="btn compact" id="runButton" disabled>載入 Python…</button></div></div><div class="editor-host"><textarea id="codeEditor" aria-label="程式碼"></textarea></div></section>
|
| 7 |
<aside class="panel console-panel" id="consolePanel"><div class="panel-heading"><h2>互動式 Console</h2><button class="copy-button" id="clearOutputButton">清除</button></div><div class="console-body"><div class="console-stream"><pre class="console-output" id="consoleOutput">Python 執行環境載入中…</pre><form class="console-input-row" id="consoleInputForm" hidden><span aria-hidden="true">›</span><label class="sr-only" for="consoleInput">Python 程式要求輸入</label><input id="consoleInput" autocomplete="off"><button class="btn compact" type="submit">送出</button></form></div><p class="console-hint">執行 <code>main.py</code>;遇到 <code>input()</code> 時會在這裡詢問。</p><div class="console-status"><i class="status-dot" id="runStatusDot"></i><span id="runStatusText">準備環境</span><span>·</span><span id="saveStatus">尚未同步</span><span>·</span><span id="submitStatus">目前專案尚未提交</span></div></div></aside></main>
|
| 8 |
<dialog id="identityDialog"><form class="dialog-content form-stack" id="identityForm"><div><h1>進入程式教室</h1><p>選擇班級並輸入自己在名單上的姓名。</p></div><div><label class="field-label" for="classCode">課程</label><select class="text-field" id="classCode" required></select></div><div><label class="field-label" for="displayName">姓名</label><input class="text-field" id="displayName" autocomplete="name" required><p class="field-help">姓名必須與老師建立的名單一致。</p></div><p class="form-error" id="identityError" role="alert"></p><button class="btn" type="submit">進入教室</button></form></dialog>
|
| 9 |
-
<dialog id="progressDialog"><div class="dialog-content"><h2>選擇
|
| 10 |
-
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script><script src="/classroom-assets/student.js?v=2026fall-
|
|
|
|
| 1 |
+
<!doctype html><html lang="zh-Hant"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="color-scheme" content="light"><title>Python 專案教室|學生工作區</title><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css"><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/material-darker.min.css"><link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-7"></head><body>
|
| 2 |
<header class="app-header"><div class="brand"><div class="brand-mark">Py</div><div class="brand-copy"><strong>Python 專案教室</strong><span id="studentIdentity">尚未進入教室</span></div></div><div class="header-actions"><div class="connection-state"><i class="status-dot" id="connectionDot"></i><span id="connectionText">未連線</span></div><button class="btn help compact" id="helpButton">請老師協助</button><button class="btn secondary compact" id="identityButton">更換身分</button></div></header>
|
| 3 |
+
<section class="project-bar"><div class="project-context"><label for="weekSelect">Lesson</label><select id="weekSelect"></select><label for="projectName">專案</label><input id="projectName" maxlength="36"></div><div class="project-actions"><button class="copy-button" id="templateButton">匯入專案起始套版</button><button class="copy-button" id="progressButton">選擇舊進度</button><button class="copy-button" id="importButton">匯入 .py / ZIP</button><button class="copy-button" id="exportButton">匯出專案</button><button class="copy-button checkpoint-action" id="checkpointButton">暫存本週進度</button><button class="btn compact" id="submitButton">提交正式版本</button><input id="fileImport" type="file" accept=".py,.zip" hidden></div></section>
|
| 4 |
<nav class="mobile-tabs" role="tablist"><button class="mobile-tab" data-panel="referencePanel">專案/語法</button><button class="mobile-tab" data-panel="editorPanel" aria-selected="true">程式</button><button class="mobile-tab" data-panel="consolePanel">執行結果</button></nav>
|
| 5 |
<main class="student-layout"><aside class="panel reference-panel" id="referencePanel"><div class="side-tabs"><button class="side-tab active" data-side="filesView">專案檔案</button><button class="side-tab" data-side="syntaxView">語法查詢</button></div><section class="side-view" id="filesView"><div class="panel-heading"><h1>檔案夾</h1><button class="copy-button" id="newFileButton">+新增</button></div><div class="file-list" id="fileList"></div><p class="side-note">入口固定為 <code>main.py</code>,可用 <code>import</code> 引入其他 Python 檔。</p></section><section class="side-view" id="syntaxView" hidden><div class="panel-heading"><h1>Python 語法查詢</h1><span id="snippetCount">0 項</span></div><div class="search-wrap"><label class="field-label" for="syntaxSearch">輸入語法或用途</label><input class="text-field" id="syntaxSearch" type="search"><div class="chip-row" id="categoryFilters"></div></div><div class="snippet-list" id="snippetList"></div></section></aside>
|
| 6 |
<section class="panel editor-panel mobile-active" id="editorPanel"><div class="panel-heading dark"><span class="file-name" id="activeFileLabel">main.py</span><div class="editor-toolbar"><button class="btn stop compact" id="stopButton" disabled>停止</button><button class="btn compact" id="runButton" disabled>載入 Python…</button></div></div><div class="editor-host"><textarea id="codeEditor" aria-label="程式碼"></textarea></div></section>
|
| 7 |
<aside class="panel console-panel" id="consolePanel"><div class="panel-heading"><h2>互動式 Console</h2><button class="copy-button" id="clearOutputButton">清除</button></div><div class="console-body"><div class="console-stream"><pre class="console-output" id="consoleOutput">Python 執行環境載入中…</pre><form class="console-input-row" id="consoleInputForm" hidden><span aria-hidden="true">›</span><label class="sr-only" for="consoleInput">Python 程式要求輸入</label><input id="consoleInput" autocomplete="off"><button class="btn compact" type="submit">送出</button></form></div><p class="console-hint">執行 <code>main.py</code>;遇到 <code>input()</code> 時會在這裡詢問。</p><div class="console-status"><i class="status-dot" id="runStatusDot"></i><span id="runStatusText">準備環境</span><span>·</span><span id="saveStatus">尚未同步</span><span>·</span><span id="submitStatus">目前專案尚未提交</span></div></div></aside></main>
|
| 8 |
<dialog id="identityDialog"><form class="dialog-content form-stack" id="identityForm"><div><h1>進入程式教室</h1><p>選擇班級並輸入自己在名單上的姓名。</p></div><div><label class="field-label" for="classCode">課程</label><select class="text-field" id="classCode" required></select></div><div><label class="field-label" for="displayName">姓名</label><input class="text-field" id="displayName" autocomplete="name" required><p class="field-help">姓名必須與老師建立的名單一致。</p></div><p class="form-error" id="identityError" role="alert"></p><button class="btn" type="submit">進入教室</button></form></dialog>
|
| 9 |
+
<dialog id="progressDialog"><div class="dialog-content"><h2>選擇已儲存進度</h2><p>可載入每週最後一次暫存、正式提交或已發布版本;載入後會成為目前專案的工作副本。</p><div class="progress-list" id="progressList"></div><button class="btn secondary dialog-close">關閉</button></div></dialog><div class="toast" id="toast"></div>
|
| 10 |
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/python/python.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script><script src="/classroom-assets/student.js?v=2026fall-8"></script></body></html>
|
classroom_static/student.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
const SNIPPETS=[["基礎","輸入與輸出",'name = input("名字:")\nprint("你好", name)'],["判斷","if / elif / else",'if score >= 90:\n print("A")\nelse:\n print("繼續加油")'],["迴圈","for 與 range",'for number in range(1, 6):\n print(number)'],["迴圈","while",'while True:\n choice = input("選擇:")\n if choice == "q":\n break'],["資料","list",'items = []\nitems.append("線索")\nfor item in items:\n print(item)'],["資料","dict",'student = {"name": "Alex"}\nprint(student.get("team", "未分組"))'],["函式","def / return",'def add(a, b):\n return a + b'],["檔案","引入自己的模組",'from clues import find_clue'],["檔案","讀取 JSON",'import json\nwith open("data.json", encoding="utf-8") as file:\n data = json.load(file)'],["錯誤","try / except",'try:\n age = int(input("年齡:"))\nexcept ValueError:\n print("請輸入整數")']].map(([category,title,code])=>({category,title,code}));
|
| 2 |
-
const $=id=>document.getElementById(id),E={};["identityDialog","identityForm","identityError","classCode","displayName","studentIdentity","identityButton","connectionDot","connectionText","helpButton","weekSelect","projectName","templateButton","progressButton","importButton","exportButton","submitButton","fileImport","fileList","newFileButton","activeFileLabel","syntaxSearch","categoryFilters","snippetList","snippetCount","runButton","stopButton","consoleInputForm","consoleInput","consoleOutput","clearOutputButton","runStatusDot","runStatusText","saveStatus","submitStatus","toast","progressDialog","progressList"].forEach(id=>E[id]=$(id));
|
| 3 |
const editor=CodeMirror.fromTextArea($("codeEditor"),{mode:"python",theme:"material-darker",lineNumbers:true,indentUnit:4,tabSize:4,extraKeys:{Tab:cm=>cm.replaceSelection(" ")}});
|
| 4 |
let studentId=localStorage.getItem("classroom_student_id")||"",catalog={courses:[]};
|
| 5 |
-
let course,files={"main.py":"# 在這裡寫 Python\n"},activeFile="main.py",socket,worker,workerReady=false,running=false,needsHelp=false,submittedAt=null,output="",suppress=false,timer,reconnect,category="全部",inputBuffer,inputControl,inputBytes,stdoutDecoder=new TextDecoder(),stderrDecoder=new TextDecoder();
|
| 6 |
const clean=v=>String(v||"").trim().replace(/[^0-9A-Za-z_\-一-鿿]/g,"").slice(0,48),lesson=()=>E.weekSelect.value||"week02",lessonInfo=()=>course?.weeks.find(item=>item.id===lesson()),workspace=()=>lessonInfo()?.workspace_id||lesson(),key=()=>`classroom_project_${localStorage.getItem("classroom_code")}_${workspace()}`;
|
| 7 |
function toast(t){E.toast.textContent=t;E.toast.classList.add("visible");setTimeout(()=>E.toast.classList.remove("visible"),1900)}
|
| 8 |
-
function send(m){if(socket?.readyState==
|
| 9 |
function esc(t){return String(t).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}
|
| 10 |
function saveLocal(){localStorage.setItem(key(),JSON.stringify({files,activeFile,projectName:E.projectName.value,output,savedAt:Date.now()}))}
|
| 11 |
function sync(){saveLocal();E.saveStatus.textContent="同步中";clearTimeout(timer);timer=setTimeout(()=>send({type:"project",files,active_file:activeFile,project_name:E.projectName.value}),450)}
|
|
@@ -29,14 +29,14 @@ function connect(){
|
|
| 29 |
const local=JSON.parse(localStorage.getItem(key())||"null"),s=m.state;
|
| 30 |
const server={files:s.files,activeFile:s.active_file,projectName:s.project_name,output:s.output};
|
| 31 |
const src=local&&Number(local.savedAt||0)>Number(s.updated_at||0)?local:server;
|
| 32 |
-
output=src.output||"";E.consoleOutput.textContent=output||"尚無執行結果。";submittedAt=s.submitted_at;needsHelp=!!s.needs_help;renderState();setProject(src.files,src.projectName,src.activeFile);send({type:"output",output});
|
| 33 |
}
|
| 34 |
if(m.type==="help_ack"){needsHelp=false;renderState();toast("老師已看到你的協助請求")}
|
| 35 |
-
if(["ack","pong"].includes(m.type)){if(typeof m.needs_help==="boolean"){const seen=needsHelp&&!m.needs_help;needsHelp=m.needs_help;if(seen)toast("老師已看到你的協助請求")}if(m.submitted_at)submittedAt=m.submitted_at;renderState();if(m.type==="ack")E.saveStatus.textContent="已同步"}
|
| 36 |
};
|
| 37 |
current.onclose=async e=>{if(socket!==current)return;E.connectionDot.className="status-dot error";E.connectionText.textContent="已離線";E.saveStatus.textContent="保存在此裝置";if(e.code===4004||e.code===4404){localStorage.removeItem("classroom_student_id");localStorage.removeItem("classroom_name");studentId="";await loadCatalog();E.identityError.textContent=e.code===4004?"老師已將你從名單移除。":"姓名與班級名單不符,請重新輸入。";E.identityDialog.showModal();return}reconnect=setTimeout(connect,2500)};
|
| 38 |
}
|
| 39 |
-
function renderState(){E.helpButton.classList.toggle("active",needsHelp);E.helpButton.textContent=needsHelp?"取消請求協助":"請老師協助";
|
| 40 |
function renderLesson(){const item=lessonInfo(),shared=item?.workspace_id&&item.workspace_id!==item.id;E.templateButton.disabled=!item?.template;E.templateButton.textContent=item?.template?"匯入專案起始套版":shared?"沿用目前專案":"尚未提供套版"}
|
| 41 |
function initWorker(){worker?.terminate();workerReady=false;running=false;E.consoleInputForm.hidden=true;E.runButton.disabled=true;E.runButton.textContent="載入 Python…";if(!crossOriginIsolated||typeof SharedArrayBuffer==="undefined"){append("瀏覽器未啟用互動式 Python。請重新整理,並使用最新版 Chrome、Edge 或 Safari。\n");runState("error","環境不支援");return}inputBuffer=new SharedArrayBuffer(16392);inputControl=new Int32Array(inputBuffer,0,2);inputBytes=new Uint8Array(inputBuffer,8);worker=new Worker("/classroom-assets/py-worker.js?v=2026fall-4");worker.onmessage=e=>{const m=e.data;if(m.type==="ready"){workerReady=true;E.runButton.disabled=false;E.runButton.textContent="執行";runState("online","準備完成")}else if(m.type==="stream"){const decoder=m.channel==="stderr"?stderrDecoder:stdoutDecoder;append(decoder.decode(m.bytes,{stream:true}))}else if(m.type==="input_request"){E.consoleInputForm.hidden=false;E.consoleInput.value="";E.runStatusText.textContent="等待輸入";E.consoleInput.focus()}else if(m.type==="done"){E.consoleInputForm.hidden=true;runState("success","執行成功")}else if(m.type==="python_error"){E.consoleInputForm.hidden=true;if(m.text)append(`${m.text}\n`);runState("error","程式錯誤")}else if(m.type==="load_error"){append(`Python 載入失敗:${m.text}\n`);runState("error","載入失敗")}};worker.onerror=e=>{append(`Python 執行器錯誤:${e.message}\n`);runState("error","執行器錯誤")}}
|
| 42 |
function runState(s,t){running=s==="running";E.runStatusDot.className=`status-dot ${s}`;E.runStatusText.textContent=t;E.runButton.disabled=!workerReady||running;E.stopButton.disabled=!running;send({type:"status",status:s==="online"?"idle":s})}
|
|
@@ -46,9 +46,10 @@ async function loadCatalog(){catalog=await(await fetch("/api/classroom/classes")
|
|
| 46 |
E.identityForm.onsubmit=async e=>{e.preventDefault();const c=clean(E.classCode.value),n=E.displayName.value.trim(),button=E.identityForm.querySelector("button[type=submit]");if(!c||!n){E.identityError.textContent="請選擇課程並輸入姓名";return}button.disabled=true;button.textContent="驗證名單中…";E.identityError.textContent="";try{const response=await fetch("/api/classroom/student-login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_code:c,display_name:n})});const data=await response.json();if(!response.ok)throw Error(data.detail||"無法驗證名單");studentId=data.student_id;localStorage.setItem("classroom_student_id",studentId);localStorage.setItem("classroom_code",c);localStorage.setItem("classroom_name",data.display_name);E.identityDialog.close();connect()}catch(error){E.identityError.textContent=error.message}finally{button.disabled=false;button.textContent="進入教室"}};E.identityButton.onclick=async()=>{await loadCatalog();E.identityDialog.showModal()};E.weekSelect.onchange=()=>{localStorage.setItem("classroom_week",lesson());renderLesson();connect()};E.projectName.oninput=sync;
|
| 47 |
E.newFileButton.onclick=()=>{const p=(prompt("新檔名(例如 clues.py):")||"").trim();if(!/^[\w\-\u4e00-\u9fff/]+\.(py|json|txt|csv|md)$/.test(p)||p.includes(".."))return toast("檔名不合規格");if(p in files)return toast("檔案已存在");files[p]=p.endsWith(".py")?"# 新的 Python 模組\n":"";openFile(p);sync()};
|
| 48 |
E.templateButton.onclick=async()=>{const item=lessonInfo();if(!item?.template)return;if(!confirm("匯入起始套版會取代目前專案內容,繼續?"))return;const r=await fetch(`/api/classroom/template/${item.id}`);if(!r.ok)return toast("這個專案尚未發布套版");const d=await r.json();setProject(d.files,item.project);toast("已匯入專案起始套版")};
|
| 49 |
-
E.progressButton.onclick=async()=>{const q=new URLSearchParams({class_code:localStorage.getItem("classroom_code")||"",student_id:studentId,display_name:localStorage.getItem("classroom_name")||""}),r=await fetch(`/api/classroom/progress?${q}`),d=await r.json();E.progressList.innerHTML=d.progress.length?d.progress.map((p,i)=>{const item=course.weeks.find(w=>w.id===p.week_id),label=item?`Lesson ${item.lesson??item.week}`:p.week_id;return `<button class="progress-item" data-i="${i}"><strong>${esc(label)}|${esc(p.project_name)}</strong><span>${p.source
|
| 50 |
E.importButton.onclick=()=>E.fileImport.click();E.fileImport.onchange=async()=>{const f=E.fileImport.files[0];if(!f)return;if(f.name.endsWith(".py"))setProject({"main.py":await f.text()},f.name.replace(/\.py$/,"").trim());else{const z=await JSZip.loadAsync(f),next={};for(const [p,item] of Object.entries(z.files))if(!item.dir&&/\.(py|json|txt|csv|md)$/i.test(p)&&!p.includes(".."))next[p]=await item.async("string");setProject(next,f.name.replace(/\.zip$/i,""))}E.fileImport.value="";toast("已匯入專案")};
|
| 51 |
E.exportButton.onclick=async()=>{files[activeFile]=editor.getValue();const z=new JSZip();Object.entries(files).forEach(([p,t])=>z.file(p,t));const blob=await z.generateAsync({type:"blob"}),a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=`${clean(E.projectName.value)||"project"}.zip`;a.click();URL.revokeObjectURL(a.href)};
|
|
|
|
| 52 |
E.submitButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");if(!confirm("設為目前專案的最後正式版本?重新提交會覆蓋前一版。"))return;send({type:"submit",files});submittedAt=Date.now();renderState();toast("專案正式版本已提交")};E.helpButton.onclick=()=>{needsHelp=!needsHelp;renderState();send({type:"help",needs_help:needsHelp})};
|
| 53 |
E.runButton.onclick=()=>{if(!workerReady||running)return;files[activeFile]=editor.getValue();output="";E.consoleOutput.textContent="";E.consoleInputForm.hidden=true;stdoutDecoder=new TextDecoder();stderrDecoder=new TextDecoder();Atomics.store(inputControl,0,0);runState("running","執行中");worker.postMessage({type:"run",files,entry:"main.py",inputBuffer})};E.consoleInputForm.onsubmit=e=>{e.preventDefault();if(!running||E.consoleInputForm.hidden)return;const encoded=new TextEncoder().encode(E.consoleInput.value);if(encoded.length>inputBytes.length)return toast("單次輸入內容太長");inputBytes.fill(0);inputBytes.set(encoded);Atomics.store(inputControl,1,encoded.length);append(`${E.consoleInput.value}\n`);E.consoleInputForm.hidden=true;E.runStatusText.textContent="執行中";Atomics.store(inputControl,0,1);Atomics.notify(inputControl,0,1)};E.stopButton.onclick=()=>{append("\n[已停止]\n");runState("idle","已停止");initWorker()};E.clearOutputButton.onclick=()=>{output="";E.consoleOutput.textContent="尚無執行結果。";send({type:"output",output:""})};E.syntaxSearch.oninput=renderSyntax;editor.on("change",()=>{if(!suppress){files[activeFile]=editor.getValue();sync()}});
|
| 54 |
document.querySelectorAll(".side-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".side-tab").forEach(x=>x.classList.toggle("active",x===b));document.querySelectorAll(".side-view").forEach(v=>v.hidden=v.id!==b.dataset.side)});document.querySelectorAll(".mobile-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".mobile-tab").forEach(x=>x.setAttribute("aria-selected",String(x===b)));document.querySelectorAll(".student-layout>.panel").forEach(p=>p.classList.toggle("mobile-active",p.id===b.dataset.panel));if(b.dataset.panel==="editorPanel")setTimeout(()=>editor.refresh(),0)});setInterval(()=>send({type:"ping"}),4000);
|
|
|
|
| 1 |
const SNIPPETS=[["基礎","輸入與輸出",'name = input("名字:")\nprint("你好", name)'],["判斷","if / elif / else",'if score >= 90:\n print("A")\nelse:\n print("繼續加油")'],["迴圈","for 與 range",'for number in range(1, 6):\n print(number)'],["迴圈","while",'while True:\n choice = input("選擇:")\n if choice == "q":\n break'],["資料","list",'items = []\nitems.append("線索")\nfor item in items:\n print(item)'],["資料","dict",'student = {"name": "Alex"}\nprint(student.get("team", "未分組"))'],["函式","def / return",'def add(a, b):\n return a + b'],["檔案","引入自己的模組",'from clues import find_clue'],["檔案","讀取 JSON",'import json\nwith open("data.json", encoding="utf-8") as file:\n data = json.load(file)'],["錯誤","try / except",'try:\n age = int(input("年齡:"))\nexcept ValueError:\n print("請輸入整數")']].map(([category,title,code])=>({category,title,code}));
|
| 2 |
+
const $=id=>document.getElementById(id),E={};["identityDialog","identityForm","identityError","classCode","displayName","studentIdentity","identityButton","connectionDot","connectionText","helpButton","weekSelect","projectName","templateButton","progressButton","importButton","exportButton","checkpointButton","submitButton","fileImport","fileList","newFileButton","activeFileLabel","syntaxSearch","categoryFilters","snippetList","snippetCount","runButton","stopButton","consoleInputForm","consoleInput","consoleOutput","clearOutputButton","runStatusDot","runStatusText","saveStatus","submitStatus","toast","progressDialog","progressList"].forEach(id=>E[id]=$(id));
|
| 3 |
const editor=CodeMirror.fromTextArea($("codeEditor"),{mode:"python",theme:"material-darker",lineNumbers:true,indentUnit:4,tabSize:4,extraKeys:{Tab:cm=>cm.replaceSelection(" ")}});
|
| 4 |
let studentId=localStorage.getItem("classroom_student_id")||"",catalog={courses:[]};
|
| 5 |
+
let course,files={"main.py":"# 在這裡寫 Python\n"},activeFile="main.py",socket,worker,workerReady=false,running=false,needsHelp=false,checkpointAt=null,submittedAt=null,output="",suppress=false,timer,reconnect,category="全部",inputBuffer,inputControl,inputBytes,stdoutDecoder=new TextDecoder(),stderrDecoder=new TextDecoder();
|
| 6 |
const clean=v=>String(v||"").trim().replace(/[^0-9A-Za-z_\-一-鿿]/g,"").slice(0,48),lesson=()=>E.weekSelect.value||"week02",lessonInfo=()=>course?.weeks.find(item=>item.id===lesson()),workspace=()=>lessonInfo()?.workspace_id||lesson(),key=()=>`classroom_project_${localStorage.getItem("classroom_code")}_${workspace()}`;
|
| 7 |
function toast(t){E.toast.textContent=t;E.toast.classList.add("visible");setTimeout(()=>E.toast.classList.remove("visible"),1900)}
|
| 8 |
+
function send(m){if(socket?.readyState!==WebSocket.OPEN)return false;socket.send(JSON.stringify(m));return true}
|
| 9 |
function esc(t){return String(t).replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}
|
| 10 |
function saveLocal(){localStorage.setItem(key(),JSON.stringify({files,activeFile,projectName:E.projectName.value,output,savedAt:Date.now()}))}
|
| 11 |
function sync(){saveLocal();E.saveStatus.textContent="同步中";clearTimeout(timer);timer=setTimeout(()=>send({type:"project",files,active_file:activeFile,project_name:E.projectName.value}),450)}
|
|
|
|
| 29 |
const local=JSON.parse(localStorage.getItem(key())||"null"),s=m.state;
|
| 30 |
const server={files:s.files,activeFile:s.active_file,projectName:s.project_name,output:s.output};
|
| 31 |
const src=local&&Number(local.savedAt||0)>Number(s.updated_at||0)?local:server;
|
| 32 |
+
output=src.output||"";E.consoleOutput.textContent=output||"尚無執行結果。";checkpointAt=s.checkpoint_at;submittedAt=s.submitted_at;needsHelp=!!s.needs_help;renderState();setProject(src.files,src.projectName,src.activeFile);send({type:"output",output});
|
| 33 |
}
|
| 34 |
if(m.type==="help_ack"){needsHelp=false;renderState();toast("老師已看到你的協助請求")}
|
| 35 |
+
if(["ack","pong"].includes(m.type)){if(typeof m.needs_help==="boolean"){const seen=needsHelp&&!m.needs_help;needsHelp=m.needs_help;if(seen)toast("老師已看到你的協助請求")}if(m.checkpoint_at)checkpointAt=m.checkpoint_at;if(m.submitted_at)submittedAt=m.submitted_at;renderState();if(m.type==="ack")E.saveStatus.textContent="已同步";if(m.checkpoint_warning)toast(m.checkpoint_warning)}
|
| 36 |
};
|
| 37 |
current.onclose=async e=>{if(socket!==current)return;E.connectionDot.className="status-dot error";E.connectionText.textContent="已離線";E.saveStatus.textContent="保存在此裝置";if(e.code===4004||e.code===4404){localStorage.removeItem("classroom_student_id");localStorage.removeItem("classroom_name");studentId="";await loadCatalog();E.identityError.textContent=e.code===4004?"老師已將你從名單移除。":"姓名與班級名單不符,請重新輸入。";E.identityDialog.showModal();return}reconnect=setTimeout(connect,2500)};
|
| 38 |
}
|
| 39 |
+
function renderState(){E.helpButton.classList.toggle("active",needsHelp);E.helpButton.textContent=needsHelp?"取消請求協助":"請老師協助";const time=value=>new Date(value).toLocaleTimeString("zh-TW",{hour:"2-digit",minute:"2-digit"}),labels=[];if(checkpointAt)labels.push(`本週暫存 ${time(checkpointAt)}`);if(submittedAt)labels.push(`正式提交 ${time(submittedAt)}`);E.submitStatus.textContent=labels.join(" · ")||"尚未暫存或提交"}
|
| 40 |
function renderLesson(){const item=lessonInfo(),shared=item?.workspace_id&&item.workspace_id!==item.id;E.templateButton.disabled=!item?.template;E.templateButton.textContent=item?.template?"匯入專案起始套版":shared?"沿用目前專案":"尚未提供套版"}
|
| 41 |
function initWorker(){worker?.terminate();workerReady=false;running=false;E.consoleInputForm.hidden=true;E.runButton.disabled=true;E.runButton.textContent="載入 Python…";if(!crossOriginIsolated||typeof SharedArrayBuffer==="undefined"){append("瀏覽器未啟用互動式 Python。請重新整理,並使用最新版 Chrome、Edge 或 Safari。\n");runState("error","環境不支援");return}inputBuffer=new SharedArrayBuffer(16392);inputControl=new Int32Array(inputBuffer,0,2);inputBytes=new Uint8Array(inputBuffer,8);worker=new Worker("/classroom-assets/py-worker.js?v=2026fall-4");worker.onmessage=e=>{const m=e.data;if(m.type==="ready"){workerReady=true;E.runButton.disabled=false;E.runButton.textContent="執行";runState("online","準備完成")}else if(m.type==="stream"){const decoder=m.channel==="stderr"?stderrDecoder:stdoutDecoder;append(decoder.decode(m.bytes,{stream:true}))}else if(m.type==="input_request"){E.consoleInputForm.hidden=false;E.consoleInput.value="";E.runStatusText.textContent="等待輸入";E.consoleInput.focus()}else if(m.type==="done"){E.consoleInputForm.hidden=true;runState("success","執行成功")}else if(m.type==="python_error"){E.consoleInputForm.hidden=true;if(m.text)append(`${m.text}\n`);runState("error","程式錯誤")}else if(m.type==="load_error"){append(`Python 載入失敗:${m.text}\n`);runState("error","載入失敗")}};worker.onerror=e=>{append(`Python 執行器錯誤:${e.message}\n`);runState("error","執行器錯誤")}}
|
| 42 |
function runState(s,t){running=s==="running";E.runStatusDot.className=`status-dot ${s}`;E.runStatusText.textContent=t;E.runButton.disabled=!workerReady||running;E.stopButton.disabled=!running;send({type:"status",status:s==="online"?"idle":s})}
|
|
|
|
| 46 |
E.identityForm.onsubmit=async e=>{e.preventDefault();const c=clean(E.classCode.value),n=E.displayName.value.trim(),button=E.identityForm.querySelector("button[type=submit]");if(!c||!n){E.identityError.textContent="請選擇課程並輸入姓名";return}button.disabled=true;button.textContent="驗證名單中…";E.identityError.textContent="";try{const response=await fetch("/api/classroom/student-login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({class_code:c,display_name:n})});const data=await response.json();if(!response.ok)throw Error(data.detail||"無法驗證名單");studentId=data.student_id;localStorage.setItem("classroom_student_id",studentId);localStorage.setItem("classroom_code",c);localStorage.setItem("classroom_name",data.display_name);E.identityDialog.close();connect()}catch(error){E.identityError.textContent=error.message}finally{button.disabled=false;button.textContent="進入教室"}};E.identityButton.onclick=async()=>{await loadCatalog();E.identityDialog.showModal()};E.weekSelect.onchange=()=>{localStorage.setItem("classroom_week",lesson());renderLesson();connect()};E.projectName.oninput=sync;
|
| 47 |
E.newFileButton.onclick=()=>{const p=(prompt("新檔名(例如 clues.py):")||"").trim();if(!/^[\w\-\u4e00-\u9fff/]+\.(py|json|txt|csv|md)$/.test(p)||p.includes(".."))return toast("檔名不合規格");if(p in files)return toast("檔案已存在");files[p]=p.endsWith(".py")?"# 新的 Python 模組\n":"";openFile(p);sync()};
|
| 48 |
E.templateButton.onclick=async()=>{const item=lessonInfo();if(!item?.template)return;if(!confirm("匯入起始套版會取代目前專案內容,繼續?"))return;const r=await fetch(`/api/classroom/template/${item.id}`);if(!r.ok)return toast("這個專案尚未發布套版");const d=await r.json();setProject(d.files,item.project);toast("已匯入專案起始套版")};
|
| 49 |
+
E.progressButton.onclick=async()=>{const q=new URLSearchParams({class_code:localStorage.getItem("classroom_code")||"",student_id:studentId,display_name:localStorage.getItem("classroom_name")||""}),r=await fetch(`/api/classroom/progress?${q}`),d=await r.json(),source={published:"已發布",classroom:"正式提交",checkpoint:"本週暫存"};E.progressList.innerHTML=d.progress.length?d.progress.map((p,i)=>{const item=course.weeks.find(w=>w.id===p.week_id),label=item?`Lesson ${item.lesson??item.week}`:p.week_id;return `<button class="progress-item" data-i="${i}"><strong>${esc(label)}|${esc(p.project_name)}</strong><span>${source[p.source]||"已儲存"} · ${new Date(p.submitted_at).toLocaleString("zh-TW")}</span></button>`}).join(""):'<p>還沒有已儲存的進度。</p>';E.progressList.querySelectorAll("[data-i]").forEach(b=>b.onclick=()=>{const p=d.progress[+b.dataset.i];setProject(p.files,p.project_name);E.progressDialog.close()});E.progressDialog.showModal()};document.querySelectorAll(".dialog-close").forEach(b=>b.onclick=()=>b.closest("dialog").close());
|
| 50 |
E.importButton.onclick=()=>E.fileImport.click();E.fileImport.onchange=async()=>{const f=E.fileImport.files[0];if(!f)return;if(f.name.endsWith(".py"))setProject({"main.py":await f.text()},f.name.replace(/\.py$/,"").trim());else{const z=await JSZip.loadAsync(f),next={};for(const [p,item] of Object.entries(z.files))if(!item.dir&&/\.(py|json|txt|csv|md)$/i.test(p)&&!p.includes(".."))next[p]=await item.async("string");setProject(next,f.name.replace(/\.zip$/i,""))}E.fileImport.value="";toast("已匯入專案")};
|
| 51 |
E.exportButton.onclick=async()=>{files[activeFile]=editor.getValue();const z=new JSZip();Object.entries(files).forEach(([p,t])=>z.file(p,t));const blob=await z.generateAsync({type:"blob"}),a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download=`${clean(E.projectName.value)||"project"}.zip`;a.click();URL.revokeObjectURL(a.href)};
|
| 52 |
+
E.checkpointButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");if(!send({type:"checkpoint",files,project_name:E.projectName.value}))return toast("目前離線,請連線後再暫存");checkpointAt=Date.now();renderState();toast("已暫存本週進度,不會發布到 Demo")};
|
| 53 |
E.submitButton.onclick=()=>{files[activeFile]=editor.getValue();if(!files["main.py"].trim())return toast("main.py 不能為空");if(!confirm("設為目前專案的最後正式版本?重新提交會覆蓋前一版。"))return;send({type:"submit",files});submittedAt=Date.now();renderState();toast("專案正式版本已提交")};E.helpButton.onclick=()=>{needsHelp=!needsHelp;renderState();send({type:"help",needs_help:needsHelp})};
|
| 54 |
E.runButton.onclick=()=>{if(!workerReady||running)return;files[activeFile]=editor.getValue();output="";E.consoleOutput.textContent="";E.consoleInputForm.hidden=true;stdoutDecoder=new TextDecoder();stderrDecoder=new TextDecoder();Atomics.store(inputControl,0,0);runState("running","執行中");worker.postMessage({type:"run",files,entry:"main.py",inputBuffer})};E.consoleInputForm.onsubmit=e=>{e.preventDefault();if(!running||E.consoleInputForm.hidden)return;const encoded=new TextEncoder().encode(E.consoleInput.value);if(encoded.length>inputBytes.length)return toast("單次輸入內容太長");inputBytes.fill(0);inputBytes.set(encoded);Atomics.store(inputControl,1,encoded.length);append(`${E.consoleInput.value}\n`);E.consoleInputForm.hidden=true;E.runStatusText.textContent="執行中";Atomics.store(inputControl,0,1);Atomics.notify(inputControl,0,1)};E.stopButton.onclick=()=>{append("\n[已停止]\n");runState("idle","已停止");initWorker()};E.clearOutputButton.onclick=()=>{output="";E.consoleOutput.textContent="尚無執行結果。";send({type:"output",output:""})};E.syntaxSearch.oninput=renderSyntax;editor.on("change",()=>{if(!suppress){files[activeFile]=editor.getValue();sync()}});
|
| 55 |
document.querySelectorAll(".side-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".side-tab").forEach(x=>x.classList.toggle("active",x===b));document.querySelectorAll(".side-view").forEach(v=>v.hidden=v.id!==b.dataset.side)});document.querySelectorAll(".mobile-tab").forEach(b=>b.onclick=()=>{document.querySelectorAll(".mobile-tab").forEach(x=>x.setAttribute("aria-selected",String(x===b)));document.querySelectorAll(".student-layout>.panel").forEach(p=>p.classList.toggle("mobile-active",p.id===b.dataset.panel));if(b.dataset.panel==="editorPanel")setTimeout(()=>editor.refresh(),0)});setInterval(()=>send({type:"ping"}),4000);
|
classroom_static/teacher.html
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
<!doctype html>
|
| 2 |
<html lang="zh-Hant">
|
| 3 |
-
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Python 專案教室|教師控制台</title><link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-
|
| 4 |
<body>
|
| 5 |
<header class="app-header"><div class="brand"><div class="brand-mark">Py</div><div class="brand-copy"><strong>全班專案控制台</strong><span id="classLabel">尚未進入班級</span></div></div><div class="header-actions"><div class="connection-state"><i id="connectionDot" class="status-dot"></i><span id="connectionText">未連線</span></div><a class="btn secondary compact header-link" href="/admin">內容管理</a><button class="btn secondary compact" id="loginButton">切換班級</button></div></header>
|
| 6 |
<section class="project-bar"><div class="project-context"><label for="teacherWeek">Lesson</label><select id="teacherWeek"></select><span id="submissionSummary" class="submission-summary">等待學生</span></div><div class="project-actions"><button class="copy-button" id="downloadButton">下載全班 ZIP</button><button class="btn compact" id="publishButton">結算並發布 Demo</button></div></section>
|
|
@@ -8,12 +8,12 @@
|
|
| 8 |
<section class="roster-panel">
|
| 9 |
<div class="panel-heading"><h1>學生狀態</h1><span id="studentTotal">0 人</span></div>
|
| 10 |
<form class="roster-add" id="rosterAddForm"><label class="sr-only" for="studentNames">新增學生姓名,多人可用逗號分開</label><input class="text-field" id="studentNames" autocomplete="off"><button class="btn compact" id="addStudentsButton" type="submit">加入名單</button></form>
|
| 11 |
-
<div class="filter-bar" id="teacherFilters"><button class="chip" data-filter="all" aria-pressed="true">全部</button><button class="chip" data-filter="submitted">已提交</button><button class="chip" data-filter="help">需要協助</button><button class="chip" data-filter="error">錯誤</button></div>
|
| 12 |
-
<div class="roster-header"><span>學生</span><span>狀態</span><span>檔案</span><span>
|
| 13 |
</section>
|
| 14 |
<section class="teacher-detail" id="teacherDetail"><div class="detail-empty" id="detailEmpty">選擇一位學生查看多檔案專案。</div><div class="detail-view" id="detailView" hidden><header class="detail-header"><div><h1 id="selectedStudentName"></h1><p class="detail-meta" id="selectedStudentMeta"></p></div><div class="detail-actions"><button class="copy-button" id="ackHelpButton" hidden>標記已查看</button><button class="copy-button" id="copyCodeButton">複製檔案</button><button class="copy-button danger-action" id="deleteStudentButton">刪除學生</button></div></header><div class="teacher-project"><nav class="teacher-file-tabs" id="teacherFiles"></nav><div class="detail-split"><section class="read-only-pane"><div class="pane-label"><span id="teacherActiveFile">main.py</span><span id="lineCount">0 行</span></div><pre class="code-readonly" id="studentCode"></pre></section><section class="read-only-pane"><div class="pane-label"><span>Console</span><span id="outputState"></span></div><pre class="output-readonly" id="studentOutput"></pre></section></div></div></div></section>
|
| 15 |
</main>
|
| 16 |
<dialog id="loginDialog"><form class="dialog-content form-stack" id="loginForm"><div><h1>進入教師控制台</h1><p>選取現有課程,或建立新的課程代碼。</p></div><div><label class="field-label" for="classCode">課程</label><select class="text-field" id="classCode" required></select></div><div id="newClassFields" hidden><label class="field-label" for="newClassCode">新課程代碼</label><input class="text-field" id="newClassCode"><label class="field-label secondary-label" for="newClassName">課程名稱</label><input class="text-field" id="newClassName"></div><div><label class="field-label" for="teacherPassword">教師密碼</label><input class="text-field" id="teacherPassword" type="password" required></div><p class="form-error" id="loginError"></p><button class="btn" type="submit">開始監看</button></form></dialog>
|
| 17 |
-
<dialog id="publishDialog"><div class="dialog-content"><h2>結算並發布</h2><p id="publishMessage"></p><div class="publish-actions"><button class="btn secondary" id="cancelPublish">取消</button><button class="btn" id="confirmPublish">確認發布</button></div></div></dialog><div class="toast" id="toast"></div><script src="/classroom-assets/teacher.js?v=2026fall-
|
| 18 |
</body>
|
| 19 |
</html>
|
|
|
|
| 1 |
<!doctype html>
|
| 2 |
<html lang="zh-Hant">
|
| 3 |
+
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Python 專案教室|教師控制台</title><link rel="stylesheet" href="/classroom-assets/classroom.css?v=2026fall-7"></head>
|
| 4 |
<body>
|
| 5 |
<header class="app-header"><div class="brand"><div class="brand-mark">Py</div><div class="brand-copy"><strong>全班專案控制台</strong><span id="classLabel">尚未進入班級</span></div></div><div class="header-actions"><div class="connection-state"><i id="connectionDot" class="status-dot"></i><span id="connectionText">未連線</span></div><a class="btn secondary compact header-link" href="/admin">內容管理</a><button class="btn secondary compact" id="loginButton">切換班級</button></div></header>
|
| 6 |
<section class="project-bar"><div class="project-context"><label for="teacherWeek">Lesson</label><select id="teacherWeek"></select><span id="submissionSummary" class="submission-summary">等待學生</span></div><div class="project-actions"><button class="copy-button" id="downloadButton">下載全班 ZIP</button><button class="btn compact" id="publishButton">結算並發布 Demo</button></div></section>
|
|
|
|
| 8 |
<section class="roster-panel">
|
| 9 |
<div class="panel-heading"><h1>學生狀態</h1><span id="studentTotal">0 人</span></div>
|
| 10 |
<form class="roster-add" id="rosterAddForm"><label class="sr-only" for="studentNames">新增學生姓名,多人可用逗號分開</label><input class="text-field" id="studentNames" autocomplete="off"><button class="btn compact" id="addStudentsButton" type="submit">加入名單</button></form>
|
| 11 |
+
<div class="filter-bar" id="teacherFilters"><button class="chip" data-filter="all" aria-pressed="true">全部</button><button class="chip" data-filter="checkpointed">已暫存</button><button class="chip" data-filter="submitted">已提交</button><button class="chip" data-filter="help">需要協助</button><button class="chip" data-filter="error">錯誤</button></div>
|
| 12 |
+
<div class="roster-header"><span>學生</span><span>狀態</span><span>檔案</span><span>進度</span></div><div class="roster-list" id="rosterList"></div>
|
| 13 |
</section>
|
| 14 |
<section class="teacher-detail" id="teacherDetail"><div class="detail-empty" id="detailEmpty">選擇一位學生查看多檔案專案。</div><div class="detail-view" id="detailView" hidden><header class="detail-header"><div><h1 id="selectedStudentName"></h1><p class="detail-meta" id="selectedStudentMeta"></p></div><div class="detail-actions"><button class="copy-button" id="ackHelpButton" hidden>標記已查看</button><button class="copy-button" id="copyCodeButton">複製檔案</button><button class="copy-button danger-action" id="deleteStudentButton">刪除學生</button></div></header><div class="teacher-project"><nav class="teacher-file-tabs" id="teacherFiles"></nav><div class="detail-split"><section class="read-only-pane"><div class="pane-label"><span id="teacherActiveFile">main.py</span><span id="lineCount">0 行</span></div><pre class="code-readonly" id="studentCode"></pre></section><section class="read-only-pane"><div class="pane-label"><span>Console</span><span id="outputState"></span></div><pre class="output-readonly" id="studentOutput"></pre></section></div></div></div></section>
|
| 15 |
</main>
|
| 16 |
<dialog id="loginDialog"><form class="dialog-content form-stack" id="loginForm"><div><h1>進入教師控制台</h1><p>選取現有課程,或建立新的課程代碼。</p></div><div><label class="field-label" for="classCode">課程</label><select class="text-field" id="classCode" required></select></div><div id="newClassFields" hidden><label class="field-label" for="newClassCode">新課程代碼</label><input class="text-field" id="newClassCode"><label class="field-label secondary-label" for="newClassName">課程名稱</label><input class="text-field" id="newClassName"></div><div><label class="field-label" for="teacherPassword">教師密碼</label><input class="text-field" id="teacherPassword" type="password" required></div><p class="form-error" id="loginError"></p><button class="btn" type="submit">開始監看</button></form></dialog>
|
| 17 |
+
<dialog id="publishDialog"><div class="dialog-content"><h2>結算並發布</h2><p id="publishMessage"></p><div class="publish-actions"><button class="btn secondary" id="cancelPublish">取消</button><button class="btn" id="confirmPublish">確認發布</button></div></div></dialog><div class="toast" id="toast"></div><script src="/classroom-assets/teacher.js?v=2026fall-10"></script>
|
| 18 |
</body>
|
| 19 |
</html>
|
classroom_static/teacher.js
CHANGED
|
@@ -42,15 +42,18 @@ function status(student) {
|
|
| 42 |
|
| 43 |
function show() {
|
| 44 |
const submitted = students.filter(student => student.submitted_at).length;
|
|
|
|
| 45 |
E.studentTotal.textContent = `${students.length} 人`;
|
| 46 |
-
E.submissionSummary.textContent = `${submitted}/${students.length} 已提交`;
|
| 47 |
const list = students.filter(student => filter === "all" || (
|
| 48 |
filter === "submitted" ? student.submitted_at :
|
|
|
|
| 49 |
filter === "help" ? student.needs_help : student.status === filter
|
| 50 |
));
|
| 51 |
E.rosterList.innerHTML = list.length ? list.map(student => {
|
| 52 |
const [dot, label] = status(student);
|
| 53 |
-
|
|
|
|
| 54 |
}).join("") : '<div class="empty-roster">這個班級尚無學生。請用上方欄位建立名單。</div>';
|
| 55 |
E.rosterList.querySelectorAll("[data-id]").forEach(button => button.onclick = () => {
|
| 56 |
selected = button.dataset.id;
|
|
@@ -73,7 +76,10 @@ function detail() {
|
|
| 73 |
const paths = Object.keys(student.files || {}).sort((a, b) => a === "main.py" ? -1 : b === "main.py" ? 1 : a.localeCompare(b));
|
| 74 |
if (!(file in student.files)) file = paths[0];
|
| 75 |
E.selectedStudentName.textContent = `${student.display_name} · ${student.project_name}`;
|
| 76 |
-
|
|
|
|
|
|
|
|
|
|
| 77 |
E.ackHelpButton.hidden = !student.needs_help;
|
| 78 |
E.teacherFiles.innerHTML = paths.map(path => `<button class="teacher-file-tab ${path === file ? "active" : ""}" data-file="${esc(path)}">${esc(path)}</button>`).join("");
|
| 79 |
E.teacherFiles.querySelectorAll("[data-file]").forEach(button => button.onclick = () => {
|
|
|
|
| 42 |
|
| 43 |
function show() {
|
| 44 |
const submitted = students.filter(student => student.submitted_at).length;
|
| 45 |
+
const checkpointed = students.filter(student => student.checkpoint_at).length;
|
| 46 |
E.studentTotal.textContent = `${students.length} 人`;
|
| 47 |
+
E.submissionSummary.textContent = `${checkpointed}/${students.length} 已暫存 · ${submitted}/${students.length} 已提交`;
|
| 48 |
const list = students.filter(student => filter === "all" || (
|
| 49 |
filter === "submitted" ? student.submitted_at :
|
| 50 |
+
filter === "checkpointed" ? student.checkpoint_at :
|
| 51 |
filter === "help" ? student.needs_help : student.status === filter
|
| 52 |
));
|
| 53 |
E.rosterList.innerHTML = list.length ? list.map(student => {
|
| 54 |
const [dot, label] = status(student);
|
| 55 |
+
const progressLabel = student.submitted_at && student.checkpoint_at ? "已交+暫存" : student.submitted_at ? "已交" : student.checkpoint_at ? "暫存" : "—";
|
| 56 |
+
return `<button class="student-row ${student.student_id === selected ? "selected" : ""}" data-id="${student.student_id}"><span class="student-name">${esc(student.display_name)}</span><span class="status-label"><i class="status-dot ${dot}"></i>${label}</span><span class="time-label">${Object.keys(student.files || {}).length} 檔</span><span class="help-label">${progressLabel}</span></button>`;
|
| 57 |
}).join("") : '<div class="empty-roster">這個班級尚無學生。請用上方欄位建立名單。</div>';
|
| 58 |
E.rosterList.querySelectorAll("[data-id]").forEach(button => button.onclick = () => {
|
| 59 |
selected = button.dataset.id;
|
|
|
|
| 76 |
const paths = Object.keys(student.files || {}).sort((a, b) => a === "main.py" ? -1 : b === "main.py" ? 1 : a.localeCompare(b));
|
| 77 |
if (!(file in student.files)) file = paths[0];
|
| 78 |
E.selectedStudentName.textContent = `${student.display_name} · ${student.project_name}`;
|
| 79 |
+
const progress=[];
|
| 80 |
+
if(student.checkpoint_at)progress.push("已暫存本週進度(不發布)");
|
| 81 |
+
if(student.submitted_at)progress.push("已提交正式版本");
|
| 82 |
+
E.selectedStudentMeta.textContent = `${label} · ${progress.join(" · ") || "尚未暫存或提交"}`;
|
| 83 |
E.ackHelpButton.hidden = !student.needs_help;
|
| 84 |
E.teacherFiles.innerHTML = paths.map(path => `<button class="teacher-file-tab ${path === file ? "active" : ""}" data-file="${esc(path)}">${esc(path)}</button>`).join("");
|
| 85 |
E.teacherFiles.querySelectorAll("[data-file]").forEach(button => button.onclick = () => {
|
tests/test_classroom.py
CHANGED
|
@@ -48,6 +48,39 @@ class ClassroomServiceTests(unittest.TestCase):
|
|
| 48 |
self.assertEqual(restored["final_files"], state["files"])
|
| 49 |
self.assertNotIn("first", restored["final_files"]["main.py"])
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
def test_class_zip_contains_each_students_final_project_folder(self):
|
| 52 |
state = classroom.empty("L6A", "student-1", "Alex", "week02")
|
| 53 |
state["project_name"] = "校園謎案"
|
|
@@ -204,7 +237,7 @@ class ClassroomServiceTests(unittest.TestCase):
|
|
| 204 |
project = classroom.PUBLISHED / classroom.DEMO_CLASS / "Alex" / "week02_校園謎案"
|
| 205 |
project.mkdir(parents=True)
|
| 206 |
(project / "main.py").write_text('print("已發布")\n', encoding="utf-8")
|
| 207 |
-
progress = classroom.published_progress("Alex")
|
| 208 |
finally:
|
| 209 |
classroom.PUBLISHED = old_published
|
| 210 |
self.assertEqual(progress[0]["week_id"], "week02")
|
|
|
|
| 48 |
self.assertEqual(restored["final_files"], state["files"])
|
| 49 |
self.assertNotIn("first", restored["final_files"]["main.py"])
|
| 50 |
|
| 51 |
+
def test_keeps_latest_weekly_checkpoint_separate_from_final(self):
|
| 52 |
+
state = classroom.empty("L6A", "student-1", "Alex", "week02")
|
| 53 |
+
state["project_name"] = "校園謎案"
|
| 54 |
+
state["files"] = {"main.py": 'print("checkpoint")\n'}
|
| 55 |
+
state["checkpoint_files"] = dict(state["files"])
|
| 56 |
+
state["checkpoint_at"] = 100
|
| 57 |
+
classroom.save(state)
|
| 58 |
+
|
| 59 |
+
restored = classroom.load("L6A", "student-1", "Alex", "week02")
|
| 60 |
+
self.assertEqual(restored["checkpoint_files"], state["files"])
|
| 61 |
+
self.assertIsNone(restored["final_files"])
|
| 62 |
+
with zipfile.ZipFile(io.BytesIO(classroom.make_zip("L6A", "week02"))) as archive:
|
| 63 |
+
self.assertEqual(archive.namelist(), [])
|
| 64 |
+
|
| 65 |
+
def test_progress_picker_prefers_newer_checkpoint_over_formal_submission(self):
|
| 66 |
+
state = classroom.empty("L6A", "student-1", "Alex", "week02")
|
| 67 |
+
state["project_name"] = "校園謎案"
|
| 68 |
+
state["final_files"] = {"main.py": 'print("formal")\n'}
|
| 69 |
+
state["submitted_at"] = 100
|
| 70 |
+
state["files"] = {"main.py": 'print("newer checkpoint")\n'}
|
| 71 |
+
state["checkpoint_files"] = dict(state["files"])
|
| 72 |
+
state["checkpoint_at"] = 200
|
| 73 |
+
classroom.save(state)
|
| 74 |
+
|
| 75 |
+
old_published = classroom.PUBLISHED
|
| 76 |
+
try:
|
| 77 |
+
classroom.PUBLISHED = Path(self.temp_dir.name) / "empty-projects"
|
| 78 |
+
result = classroom.progress("L6A", "student-1", "Alex")
|
| 79 |
+
finally:
|
| 80 |
+
classroom.PUBLISHED = old_published
|
| 81 |
+
self.assertEqual(result["progress"][0]["source"], "checkpoint")
|
| 82 |
+
self.assertIn("newer checkpoint", result["progress"][0]["files"]["main.py"])
|
| 83 |
+
|
| 84 |
def test_class_zip_contains_each_students_final_project_folder(self):
|
| 85 |
state = classroom.empty("L6A", "student-1", "Alex", "week02")
|
| 86 |
state["project_name"] = "校園謎案"
|
|
|
|
| 237 |
project = classroom.PUBLISHED / classroom.DEMO_CLASS / "Alex" / "week02_校園謎案"
|
| 238 |
project.mkdir(parents=True)
|
| 239 |
(project / "main.py").write_text('print("已發布")\n', encoding="utf-8")
|
| 240 |
+
progress = classroom.published_progress("L6A", "Alex")
|
| 241 |
finally:
|
| 242 |
classroom.PUBLISHED = old_published
|
| 243 |
self.assertEqual(progress[0]["week_id"], "week02")
|