-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
261 lines (217 loc) · 8.33 KB
/
Copy pathserver.py
File metadata and controls
261 lines (217 loc) · 8.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python3
"""grU Trainer — Flask backend with per-user progress persistence."""
import json
import os
import re
from datetime import datetime, date, timedelta
from pathlib import Path
from flask import Flask, abort, jsonify, request, send_from_directory
app = Flask(__name__)
BASE = Path(__file__).parent
DATA = Path(os.environ.get("DATA_DIR", BASE / "data"))
STATIC = BASE / "static"
APP_BASE = os.environ.get("APP_BASE", "/").rstrip("/") + "/"
DATA.mkdir(parents=True, exist_ok=True)
# ── helpers ─────────────────────────────────────────────────────────────────
def _slug(name: str) -> str:
return re.sub(r"[^\w-]", "_", name.strip().lower())[:40]
def _path(name: str) -> Path:
return DATA / f"{_slug(name)}.json"
def _now() -> str:
return datetime.now().isoformat()
def _load(name: str) -> dict:
p = _path(name)
if p.exists():
return json.loads(p.read_text("utf-8"))
return {"name": name, "created": _now(), "progress": {}, "sessions": [], "bookmarks": []}
def _save(name: str, d: dict):
_path(name).write_text(json.dumps(d, ensure_ascii=False, indent=2), "utf-8")
def _compute_stats(d: dict) -> dict:
prog = d.get("progress", {})
now_ms = datetime.now().timestamp() * 1000
DAY_MS = 86_400_000
# Mutually exclusive buckets (priority: mastered > struggling > due > learning)
seen = mastered = struggling = due = learning = 0
for v in prog.values():
if v.get("attempts", 0) == 0:
continue
seen += 1
streak = v.get("streak", 0)
attempts = v.get("attempts", 0)
correct = v.get("correct", 0)
if streak >= 3:
mastered += 1
elif (
v.get('struggling') is True or
(v.get('struggling') is None and attempts >= 2 and correct / attempts < 0.6)
):
struggling += 1
elif v.get("lastSeen", 0) + v.get("interval", 0) * DAY_MS <= now_ms:
due += 1
else:
learning += 1
sessions = d.get("sessions", [])
# daily streak — consecutive days with at least one session
today = date.today()
session_dates = sorted(
set(s.get("date", "")[:10] for s in sessions if s.get("date")),
reverse=True,
)
streak = 0
check = today
for sd in session_dates:
if sd == check.isoformat():
streak += 1
check -= timedelta(days=1)
elif sd < check.isoformat():
break
today_answered = sum(
s.get("total", 0) for s in sessions
if s.get("date", "").startswith(today.isoformat())
)
# per-chapter error rates
chapter_errors: dict[int, dict] = {}
for tid, v in prog.items():
if v.get("attempts", 0) < 2:
continue
cid = v.get("chapter_id")
if cid is None:
continue
bucket = chapter_errors.setdefault(cid, {"wrong": 0, "total": 0})
bucket["total"] += v["attempts"]
bucket["wrong"] += v["attempts"] - v.get("correct", 0)
weak_chapters = sorted(
[
{"chapter_id": cid, "error_rate": round(b["wrong"] / b["total"], 3)}
for cid, b in chapter_errors.items()
if b["total"] >= 3 and b["wrong"] / b["total"] > 0.15
],
key=lambda x: -x["error_rate"],
)[:8]
return {
"seen": seen,
"mastered": mastered,
"struggling": struggling,
"due": due,
"learning": learning,
"streak": streak,
"today_answered": today_answered,
"total_sessions": len(sessions),
"last_session": sessions[-1] if sessions else None,
"weak_chapters": weak_chapters,
}
# ── static ──────────────────────────────────────────────────────────────────
STATIC_PATHS = {"/tickets.json", "/cheatsheets.json", "/sw.js", "/manifest.json", "/icon.svg"}
@app.after_request
def cache_policy(r):
p = request.path
# static assets cacheable (SW precache works); HTML + API stay fresh
if p in STATIC_PATHS or p.startswith("/static/"):
r.headers["Cache-Control"] = "public, max-age=300"
else:
r.headers["Cache-Control"] = "no-store, no-cache"
return r
@app.route("/")
def index():
if APP_BASE == "/":
return send_from_directory(BASE, "study.html")
html = (BASE / "study.html").read_text("utf-8")
html = html.replace("<head>", f'<head><base href="{APP_BASE}">', 1)
return html, 200, {"Content-Type": "text/html; charset=utf-8"}
@app.route("/tickets.json")
def tickets():
return send_from_directory(BASE, "tickets.json")
@app.route("/cheatsheets.json")
def cheatsheets():
return send_from_directory(BASE, "cheatsheets.json")
@app.route("/sw.js")
def service_worker():
return send_from_directory(BASE, "sw.js", mimetype="application/javascript")
@app.route("/manifest.json")
def manifest():
return send_from_directory(BASE, "manifest.json")
@app.route("/icon.svg")
def icon():
return send_from_directory(BASE, "icon.svg", mimetype="image/svg+xml")
@app.route("/static/img/<path:filename>")
def static_img(filename):
return send_from_directory(STATIC / "img", filename)
# ── API ─────────────────────────────────────────────────────────────────────
@app.route("/api/users", methods=["GET"])
def list_users():
out = []
for f in sorted(DATA.glob("*.json")):
try:
d = json.loads(f.read_text("utf-8"))
out.append({"name": d["name"], **_compute_stats(d)})
except Exception:
pass
return jsonify(out)
@app.route("/api/login", methods=["POST"])
def login():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "").strip()
if not name:
abort(400, "name required")
is_new = not _path(name).exists()
d = _load(name)
if is_new:
_save(name, d)
return jsonify({
"name": d["name"],
"is_new": is_new,
"progress": d.get("progress", {}),
"bookmarks": d.get("bookmarks", []),
"recent_sessions": d.get("sessions", [])[-30:],
"stats": _compute_stats(d),
})
@app.route("/api/progress", methods=["PUT"])
def update_progress():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "").strip()
updates = body.get("updates", {})
if not name or not isinstance(updates, dict):
abort(400)
d = _load(name)
if body.get("_reset"):
d["progress"] = {}
else:
d.setdefault("progress", {}).update(updates)
_save(name, d)
return jsonify({"ok": True})
@app.route("/api/session", methods=["POST"])
def save_session():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "").strip()
summary = body.get("summary", {})
if not name:
abort(400)
d = _load(name)
summary["date"] = _now()
d.setdefault("sessions", []).append(summary)
d["sessions"] = d["sessions"][-100:]
_save(name, d)
return jsonify({"ok": True})
@app.route("/api/bookmark", methods=["POST"])
def toggle_bookmark():
body = request.get_json(silent=True) or {}
name = (body.get("name") or "").strip()
ticket_id = body.get("ticket_id")
if not name or ticket_id is None:
abort(400)
d = _load(name)
bookmarks = set(d.get("bookmarks", []))
if ticket_id in bookmarks:
bookmarks.discard(ticket_id)
added = False
else:
bookmarks.add(ticket_id)
added = True
d["bookmarks"] = sorted(bookmarks)
_save(name, d)
return jsonify({"ok": True, "bookmarked": added})
# ── run ─────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
port = int(os.environ.get("PORT", 8080))
print(f"grU Trainer → http://localhost:{port}")
app.run(host="0.0.0.0", port=port, debug=False)