-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
239 lines (205 loc) · 7.69 KB
/
Copy pathapi.py
File metadata and controls
239 lines (205 loc) · 7.69 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
from flask import Blueprint, request, jsonify
from models import db, Problem, Attempt, Category, Topic
from datetime import date, timedelta
from sqlalchemy import func, case
api_bp = Blueprint("api", __name__, url_prefix="/api")
@api_bp.route("/problems")
def list_problems():
query = Problem.query
if cat := request.args.get("category"):
query = query.join(Category).filter(Category.name == cat)
if topic := request.args.get("topic"):
query = query.filter(Problem.topics.any(Topic.name == topic))
if diff := request.args.get("difficulty"):
query = query.filter(Problem.difficulty == diff)
if box := request.args.get("box"):
query = query.filter(Problem.leitner_box == int(box))
if status := request.args.get("status"):
if status == "not_attempted":
query = query.filter(~Problem.attempts.any())
elif status == "mastered":
query = query.filter(Problem.leitner_box >= 4)
elif status == "learning":
query = query.filter(Problem.attempts.any(), Problem.leitner_box < 4)
problems = query.order_by(Problem.next_review_date.asc()).all()
return jsonify([p.to_dict() for p in problems])
@api_bp.route("/problems/<int:problem_id>")
def get_problem(problem_id):
problem = Problem.query.get_or_404(problem_id)
return jsonify(problem.to_dict(include_attempts=True))
@api_bp.route("/due")
def due_today():
"""Get problems due for review today (Leitner-scheduled), interleaved by topic."""
problems = (
Problem.query.filter(Problem.next_review_date <= date.today())
.order_by(Problem.leitner_box.asc(), func.random())
.all()
)
type_filter = request.args.get("type")
if type_filter == "new":
problems = [p for p in problems if not p.attempts]
elif type_filter == "review":
problems = [p for p in problems if p.attempts]
result = []
for p in problems:
d = p.to_dict()
d["review_type"] = "new" if not p.attempts else "review"
result.append(d)
return jsonify(result)
@api_bp.route("/attempts", methods=["POST"])
def log_attempt():
data = request.get_json()
problem = Problem.query.get_or_404(data["problem_id"])
attempt = Attempt(
problem_id=problem.id,
passed=data.get("passed", False),
time_taken_minutes=data.get("time_taken_minutes"),
confidence=data.get("confidence"),
solution_code=data.get("solution_code"),
ai_score=data.get("ai_score"),
ai_feedback=data.get("ai_feedback"),
complexity_score=data.get("complexity_score"),
notes=data.get("notes"),
)
db.session.add(attempt)
problem.record_attempt(attempt.passed, attempt.confidence or 1)
db.session.commit()
return jsonify({
"attempt": attempt.to_dict(),
"leitner_update": {
"new_box": problem.leitner_box,
"next_review": problem.next_review_date.isoformat(),
},
}), 201
@api_bp.route("/stats")
def stats():
total = Problem.query.count()
attempted = Problem.query.filter(Problem.attempts.any()).count()
mastered = Problem.query.filter(Problem.leitner_box >= 4).count()
due_today_count = Problem.query.filter(Problem.next_review_date <= date.today()).count()
attempts = Attempt.query.all()
avg_confidence = (
db.session.query(func.avg(Attempt.confidence)).scalar() or 0
)
avg_ai_score = (
db.session.query(func.avg(Attempt.ai_score)).filter(Attempt.ai_score.isnot(None)).scalar() or 0
)
avg_complexity = (
db.session.query(func.avg(Attempt.complexity_score)).filter(Attempt.complexity_score.isnot(None)).scalar() or 0
)
total_attempts = len(attempts)
pass_rate = (
sum(1 for a in attempts if a.passed) / total_attempts * 100
if total_attempts
else 0
)
# Confidence vs reality per topic
calibration = []
topics = Topic.query.all()
for topic in topics:
topic_attempts = (
Attempt.query.join(Problem)
.filter(Problem.topics.any(Topic.id == topic.id))
.all()
)
if topic_attempts:
t_conf = sum(a.confidence or 0 for a in topic_attempts) / len(topic_attempts)
t_pass = sum(1 for a in topic_attempts if a.passed) / len(topic_attempts) * 100
calibration.append({
"topic": topic.name,
"avg_confidence": round(t_conf, 1),
"pass_rate": round(t_pass, 1),
"attempt_count": len(topic_attempts),
})
# Box distribution
box_dist = {}
for box in range(1, 6):
box_dist[str(box)] = Problem.query.filter(Problem.leitner_box == box).count()
# Recent activity (last 10 attempts)
recent = (
Attempt.query.order_by(Attempt.created_at.desc()).limit(10).all()
)
return jsonify({
"total_problems": total,
"attempted": attempted,
"mastered": mastered,
"due_today": due_today_count,
"total_attempts": total_attempts,
"avg_confidence": round(float(avg_confidence), 1),
"avg_ai_score": round(float(avg_ai_score), 1),
"avg_complexity_score": round(float(avg_complexity), 1),
"pass_rate": round(pass_rate, 1),
"box_distribution": box_dist,
"calibration": sorted(calibration, key=lambda x: x["pass_rate"]),
"recent_activity": [
{
**a.to_dict(),
"problem_name": a.problem.name,
}
for a in recent
],
})
@api_bp.route("/topics")
def topic_analytics():
topics = Topic.query.all()
result = []
for topic in topics:
problems = topic.problems
topic_attempts = (
Attempt.query.join(Problem)
.filter(Problem.topics.any(Topic.id == topic.id))
.all()
)
avg_conf = (
sum(a.confidence or 0 for a in topic_attempts) / len(topic_attempts)
if topic_attempts
else 0
)
pass_rate = (
sum(1 for a in topic_attempts if a.passed) / len(topic_attempts) * 100
if topic_attempts
else 0
)
box_counts = {}
for p in problems:
box_counts[p.leitner_box] = box_counts.get(p.leitner_box, 0) + 1
result.append({
"topic": topic.to_dict(),
"problem_count": len(problems),
"attempt_count": len(topic_attempts),
"avg_confidence": round(avg_conf, 1),
"pass_rate": round(pass_rate, 1),
"box_distribution": box_counts,
})
return jsonify(sorted(result, key=lambda x: x["pass_rate"]))
@api_bp.route("/calendar")
def calendar():
"""Daily attempt counts. Minimum 3 months lookback, expands to cover all history."""
today = date.today()
min_start = today - timedelta(days=90)
earliest_attempt = db.session.query(func.min(func.date(Attempt.created_at))).scalar()
if earliest_attempt:
earliest = date.fromisoformat(str(earliest_attempt))
start = min(earliest, min_start)
else:
start = min_start
# Align start to previous Monday for clean grid
while start.weekday() != 0:
start -= timedelta(days=1)
rows = (
db.session.query(
func.date(Attempt.created_at).label("day"),
func.count().label("count"),
)
.filter(Attempt.created_at >= start.isoformat())
.group_by(func.date(Attempt.created_at))
.all()
)
counts = {str(r.day): r.count for r in rows}
result = []
d = start
while d <= today:
ds = d.isoformat()
result.append({"date": ds, "count": counts.get(ds, 0)})
d += timedelta(days=1)
return jsonify(result)