smart-study-planner 0.5.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
study_plan/planner.py ADDED
@@ -0,0 +1,356 @@
1
+ """Smart Study Planner: validate a form request and build an explainable timetable.
2
+
3
+ This module has no web framework dependencies. Dates are local calendar dates,
4
+ while time intervals use minutes since midnight (end exclusive).
5
+ """
6
+
7
+ from datetime import date, timedelta
8
+ from decimal import Decimal, InvalidOperation
9
+ from fractions import Fraction
10
+ import re
11
+
12
+ TIME_RE = re.compile(r"^(?:[01]\d|2[0-3]):[0-5]\d$|^24:00$")
13
+ MAX_DAYS = 63
14
+ MAX_SUBJECTS = 20
15
+ MAX_WINDOWS = 12
16
+
17
+
18
+ class InputError(ValueError):
19
+ """Invalid user form values (safe to display in the interface)."""
20
+
21
+
22
+ def parse_date(value, label):
23
+ if not isinstance(value, str):
24
+ raise InputError(f"{label} must use YYYY-MM-DD format.")
25
+ try:
26
+ parsed = date.fromisoformat(value)
27
+ except ValueError as exc:
28
+ raise InputError(f"{label} is not a valid calendar date.") from exc
29
+ if parsed.isoformat() != value:
30
+ raise InputError(f"{label} must use YYYY-MM-DD format.")
31
+ return parsed
32
+
33
+
34
+ def parse_time(value, *, is_end=False):
35
+ if not isinstance(value, str) or not TIME_RE.fullmatch(value):
36
+ raise InputError("Time must use HH:MM format, such as 08:00.")
37
+ if value == "24:00" and not is_end:
38
+ raise InputError("24:00 may only be used as an end time.")
39
+ h, m = map(int, value.split(":"))
40
+ return h * 60 + m
41
+
42
+
43
+ def minute_label(value):
44
+ return f"{value // 60:02d}:{value % 60:02d}"
45
+
46
+
47
+ def parse_windows(value, label):
48
+ if not isinstance(value, list) or len(value) > MAX_WINDOWS:
49
+ raise InputError(f"{label} supports at most {MAX_WINDOWS} time windows.")
50
+ windows = []
51
+ for item in value:
52
+ if not isinstance(item, dict):
53
+ raise InputError(f"{label} contains an invalid time window.")
54
+ start = parse_time(item.get("start"))
55
+ end = parse_time(item.get("end"), is_end=True)
56
+ if end - start < 30:
57
+ raise InputError(f"{label} requires time windows of at least 30 minutes.")
58
+ windows.append((start, end))
59
+ # Merge overlapping *and touching* windows so capacity is not counted twice.
60
+ merged = []
61
+ for start, end in sorted(windows):
62
+ if merged and start <= merged[-1][1]:
63
+ merged[-1] = (merged[-1][0], max(end, merged[-1][1]))
64
+ else:
65
+ merged.append((start, end))
66
+ return merged
67
+
68
+
69
+ def parse_subjects(value):
70
+ if not isinstance(value, list) or not 1 <= len(value) <= MAX_SUBJECTS:
71
+ raise InputError(f"Please enter between 1 and {MAX_SUBJECTS} subjects.")
72
+ subjects = []
73
+ for index, item in enumerate(value):
74
+ if not isinstance(item, dict):
75
+ raise InputError(f"Subject #{index + 1} is invalid.")
76
+ name = item.get("name")
77
+ if not isinstance(name, str) or not name.strip() or len(name.strip()) > 80:
78
+ raise InputError(f"Subject #{index + 1} must have a name of 1–80 characters.")
79
+ raw_hours = item.get("hours")
80
+ try:
81
+ hours = Decimal(str(raw_hours))
82
+ except (InvalidOperation, ValueError) as exc:
83
+ raise InputError(f"{name}: required study hours must be a valid number.") from exc
84
+ if not hours.is_finite() or not (Decimal("0") < hours <= Decimal("500")):
85
+ raise InputError(f"{name}: required study hours must be more than 0 and at most 500.")
86
+ minutes = hours * 60
87
+ if minutes % 30 != 0:
88
+ raise InputError(f"{name}: required study hours must be in 0.5-hour increments.")
89
+ raw_deadline = item.get("exam_date")
90
+ exam_date = parse_date(raw_deadline, f"{name} exam date") if raw_deadline else None
91
+ subjects.append({"id": index, "name": name.strip(), "minutes": int(minutes),
92
+ "exam_date": exam_date})
93
+ return subjects
94
+
95
+
96
+ def parse_request(data):
97
+ """Return normalized input; all error messages are suitable for the UI."""
98
+ if not isinstance(data, dict):
99
+ raise InputError("Invalid request format.")
100
+ start = parse_date(data.get("start_date"), "Start date")
101
+ end = parse_date(data.get("end_date"), "End date")
102
+ if end < start:
103
+ raise InputError("End date cannot be before start date.")
104
+ if (end - start).days + 1 > MAX_DAYS:
105
+ raise InputError(f"A plan can cover at most {MAX_DAYS} days.")
106
+ subjects = parse_subjects(data.get("subjects"))
107
+ daily = parse_windows(data.get("daily_windows", []), "Default free time")
108
+ raw_overrides = data.get("date_overrides", [])
109
+ if not isinstance(raw_overrides, list) or len(raw_overrides) > MAX_DAYS:
110
+ raise InputError("Invalid date-specific availability format.")
111
+ overrides = {}
112
+ for obj in raw_overrides:
113
+ if not isinstance(obj, dict):
114
+ raise InputError("Invalid date-specific availability format.")
115
+ day = parse_date(obj.get("date"), "Custom date")
116
+ if not start <= day <= end:
117
+ raise InputError(f"{day.isoformat()} is outside the planning date range.")
118
+ if day in overrides:
119
+ raise InputError(f"Only one override is allowed for {day.isoformat()}.")
120
+ overrides[day] = parse_windows(obj.get("windows", []), f"Availability on {day}")
121
+
122
+ session_minutes = data.get("session_minutes", 60)
123
+ break_minutes = data.get("break_minutes", 10)
124
+ daily_subject_limit = data.get("daily_subject_limit_minutes", 120)
125
+ if (type(daily_subject_limit) is not int or
126
+ not 60 <= daily_subject_limit <= 480 or
127
+ daily_subject_limit % 30 != 0):
128
+ raise InputError("Daily per-subject limit must be between 1 and 8 hours, in 30-minute increments.")
129
+ if type(session_minutes) is not int or session_minutes not in (30, 60, 90):
130
+ raise InputError("Session length must be 30, 60, or 90 minutes.")
131
+ if type(break_minutes) is not int or break_minutes not in (0, 5, 10, 15):
132
+ raise InputError("Break length must be 0, 5, 10, or 15 minutes.")
133
+ slots = []
134
+ day = start
135
+ while day <= end:
136
+ for window_start, window_end in overrides.get(day, daily):
137
+ slots.append({"date": day, "start": window_start, "end": window_end})
138
+ day += timedelta(days=1)
139
+ return {"start": start, "end": end, "subjects": subjects, "slots": slots,
140
+ "session_minutes": session_minutes, "break_minutes": break_minutes,
141
+ "daily_subject_limit_minutes": daily_subject_limit}
142
+
143
+
144
+ def plan_study(normalized):
145
+ """Schedule sessions using explicit user-defined priority order.
146
+
147
+ Subjects are ranked from highest to lowest in the incoming list. A
148
+ priority-weighted fair-queuing score gives earlier subjects more total
149
+ study time when capacity is scarce, while alternating subjects whenever
150
+ possible. A hard per-subject daily limit prevents monopolization.
151
+
152
+ Work is paced across the entire eligible date range rather than front-loaded.
153
+ Within each date, study time is balanced over available windows, with
154
+ alternating tie-breaks so light days do not always land in the morning.
155
+ Priority never overrides availability, completion, or exam cutoffs.
156
+ When capacities are abundant, subjects may receive equal hours because
157
+ the planner does not waste usable time just to force unequal totals.
158
+ """
159
+ subjects = normalized["subjects"]
160
+ slots = sorted(normalized["slots"], key=lambda s: (s["date"], s["start"]))
161
+ remaining = {s["id"]: s["minutes"] for s in subjects}
162
+ total_used = {s["id"]: 0 for s in subjects}
163
+ per_day_used = {}
164
+ scheduled = []
165
+ duration = normalized["session_minutes"]
166
+ rest = normalized["break_minutes"]
167
+ daily_limit = normalized.get("daily_subject_limit_minutes", 120)
168
+
169
+ # Theoretical individual upper bounds. These ignore breaks and competition
170
+ # for free slots, so they are never presented as guaranteed allocations.
171
+ available_by_day = {}
172
+ for slot in slots:
173
+ available_by_day[slot["date"]] = (available_by_day.get(slot["date"], 0)
174
+ + slot["end"] - slot["start"])
175
+
176
+ def individual_capacity(subject, from_day=None):
177
+ deadline = subject["exam_date"]
178
+ return sum(min(minutes, daily_limit) for day, minutes in available_by_day.items()
179
+ if (from_day is None or day >= from_day)
180
+ and (deadline is None or day < deadline))
181
+
182
+ individual_caps = {s["id"]: individual_capacity(s) for s in subjects}
183
+
184
+ # A cumulative, date-aware pacing target spreads shorter workloads across
185
+ # the full selected period rather than filling the earliest dates first.
186
+ # Targets count half-hour study units, respecting each subject's exam cutoff.
187
+ # Days with more free time receive a proportionally larger share, while
188
+ # days without availability receive nothing. A deadline naturally shortens
189
+ # the pacing horizon to eligible dates before that exam.
190
+ pacing_targets = {}
191
+ for subject in subjects:
192
+ sid = subject["id"]
193
+ target_units = min(subject["minutes"], individual_caps[sid]) // 30
194
+ eligible = [
195
+ (day, min(minutes, daily_limit) // 30)
196
+ for day, minutes in sorted(available_by_day.items())
197
+ if minutes >= 30 and
198
+ (subject["exam_date"] is None or day < subject["exam_date"])
199
+ ]
200
+ total_weight = sum(weight for _, weight in eligible)
201
+ cumulative_weight = 0
202
+ for day, weight in eligible:
203
+ cumulative_weight += weight
204
+ # Round to the nearest half-hour, using integer arithmetic to avoid
205
+ # floating-point drift. The final eligible day gets the full target.
206
+ pacing_targets[(day, sid)] = (
207
+ (target_units * cumulative_weight * 2 + total_weight)
208
+ // (2 * total_weight)
209
+ ) * 30 if total_weight else 0
210
+
211
+ # Work out WHICH dates need study first (pacing_targets above), then choose
212
+ # WHERE within each date to place those sessions. Filling each morning
213
+ # window to completion before moving to the afternoon makes a calendar
214
+ # appear lopsided even when the dates themselves are well balanced.
215
+ slots_by_day = {}
216
+ for slot in slots:
217
+ slots_by_day.setdefault(slot["date"], []).append(slot)
218
+
219
+ active_day_count = 0
220
+ for day, day_slots in sorted(slots_by_day.items()):
221
+ windows = [
222
+ {"start": slot["start"], "end": slot["end"],
223
+ "cursor": slot["start"], "used": 0, "capacity": slot["end"] - slot["start"]}
224
+ for slot in day_slots
225
+ ]
226
+ day_sessions = []
227
+ previous_subject = None
228
+ # Rotate equal-utilization ties by date: when a day requires only one
229
+ # session, it alternates between morning/afternoon across the week.
230
+ rotation = active_day_count % len(windows)
231
+
232
+ while True:
233
+ candidates = [s for s in subjects
234
+ if remaining[s["id"]] >= 30
235
+ and per_day_used.get((day, s["id"]), 0) < daily_limit
236
+ and total_used[s["id"]] < pacing_targets.get((day, s["id"]), 0)
237
+ and (s["exam_date"] is None or day < s["exam_date"])]
238
+ if not candidates:
239
+ break
240
+
241
+ # Choose a window with the smallest fraction already occupied by
242
+ # actual study (rather than always the earliest window). Larger
243
+ # windows can naturally receive more sessions than shorter ones.
244
+ # Also honor the configured break across nearly touching windows,
245
+ # even when the windows were filled out of chronological order.
246
+ available_windows = []
247
+ for index, window in enumerate(windows):
248
+ cursor, limit = window["cursor"], window["end"]
249
+ for event in day_sessions:
250
+ if event["end"] <= cursor:
251
+ cursor = max(cursor, event["end"] + rest)
252
+ elif event["start"] >= window["end"]:
253
+ limit = min(limit, event["start"] - rest)
254
+ if cursor + 30 <= limit:
255
+ available_windows.append((index, window, cursor, limit))
256
+ if not available_windows:
257
+ break
258
+
259
+ index, window, cursor, limit = min(
260
+ available_windows,
261
+ key=lambda item: (Fraction(item[1]["used"], item[1]["capacity"]),
262
+ (item[0] - rotation) % len(windows)),
263
+ )
264
+
265
+ # Prefer a different subject from the most recently chosen one,
266
+ # without overriding exam eligibility, caps or pacing targets.
267
+ alternate = [s for s in candidates if s["id"] != previous_subject]
268
+ if alternate:
269
+ candidates = alternate
270
+
271
+ def priority(subject):
272
+ sid = subject["id"]
273
+ weight = len(subjects) - sid # rank 1 gets the largest weight
274
+ return (Fraction(total_used[sid], weight),
275
+ per_day_used.get((day, sid), 0), sid)
276
+
277
+ chosen = min(candidates, key=priority)
278
+ sid = chosen["id"]
279
+ free_today = daily_limit - per_day_used.get((day, sid), 0)
280
+ work = min(duration, remaining[sid], free_today,
281
+ pacing_targets[(day, sid)] - total_used[sid],
282
+ ((limit - cursor) // 30) * 30)
283
+ if work < 30:
284
+ break
285
+ event = {"date": day, "start": cursor, "end": cursor + work,
286
+ "subject": chosen["name"], "subject_id": sid}
287
+ scheduled.append(event)
288
+ day_sessions.append(event)
289
+ remaining[sid] -= work
290
+ per_day_used[(day, sid)] = per_day_used.get((day, sid), 0) + work
291
+ total_used[sid] += work
292
+ previous_subject = sid
293
+ window["cursor"] = cursor + work + rest
294
+ window["used"] += work
295
+
296
+ if day_sessions:
297
+ active_day_count += 1
298
+
299
+ # Windows may have been filled out of chronological order. Public API,
300
+ # calendar rendering, and ICS export all receive time-ordered sessions.
301
+ scheduled.sort(key=lambda event: (event["date"], event["start"], event["subject_id"]))
302
+
303
+ warnings = []
304
+ for s in subjects:
305
+ sid = s["id"]
306
+ if remaining[sid] == 0:
307
+ continue
308
+ cap = individual_caps[sid]
309
+ if s["minutes"] > cap:
310
+ period = "before the exam" if s["exam_date"] else "in the planning period"
311
+ warnings.append(
312
+ f"Priority #{sid + 1} · {s['name']}: requires {s['minutes'] / 60:g}h. "
313
+ f"With a {daily_limit / 60:g}h daily subject limit and the "
314
+ f"available dates, the theoretical maximum {period} is "
315
+ f"{cap / 60:g}h (before breaks and competing subjects). "
316
+ f"At least {max(0, s['minutes'] - cap) / 60:g}h cannot fit."
317
+ )
318
+ else:
319
+ warnings.append(
320
+ f"Priority #{sid + 1} · {s['name']}: {remaining[sid] / 60:g}h "
321
+ "remain unscheduled. Check available time, exam dates, "
322
+ "breaks, and competing subjects."
323
+ )
324
+
325
+ required = sum(s["minutes"] for s in subjects)
326
+ planned = sum(s["end"] - s["start"] for s in scheduled)
327
+ available = sum(s["end"] - s["start"] for s in slots)
328
+ return {
329
+ "sessions": [{**s, "date": s["date"].isoformat(),
330
+ "start_time": minute_label(s["start"]),
331
+ "end_time": minute_label(s["end"])} for s in scheduled],
332
+ "subjects": [{"id": s["id"], "name": s["name"],
333
+ "priority_rank": s["id"] + 1,
334
+ "priority_weight": len(subjects) - s["id"],
335
+ "required_minutes": s["minutes"],
336
+ "scheduled_minutes": s["minutes"] - remaining[s["id"]],
337
+ "remaining_minutes": remaining[s["id"]],
338
+ "individual_capacity_upper_bound_minutes": individual_caps[s["id"]],
339
+ "exam_date": s["exam_date"].isoformat() if s["exam_date"] else None}
340
+ for s in subjects],
341
+ "availability": [{"date": s["date"].isoformat(), "start": s["start"],
342
+ "end": s["end"]} for s in slots],
343
+ "start_date": normalized["start"].isoformat(),
344
+ "end_date": normalized["end"].isoformat(),
345
+ "settings": {"session_minutes": duration, "break_minutes": rest,
346
+ "daily_subject_limit_minutes": daily_limit},
347
+ "warnings": warnings,
348
+ "summary": {"required_minutes": required, "scheduled_minutes": planned,
349
+ "remaining_minutes": required - planned,
350
+ "available_minutes": available, "session_count": len(scheduled)}
351
+ }
352
+
353
+
354
+ def generate_plan(request):
355
+ """Convenience API for browser request bodies and unit tests."""
356
+ return plan_study(parse_request(request))
@@ -0,0 +1,43 @@
1
+ """Legacy data-only scheduler. Dates use datetime.date and times use minutes since midnight."""
2
+
3
+
4
+ def schedule(tasks, available_slots):
5
+ """Sort by exam date and return (sessions, unscheduled) without changing inputs.
6
+
7
+ tasks: [{subject, exam_date, minutes}]
8
+ available_slots: [{date, start, end}]; every slot length is a multiple of 30 minutes.
9
+ sessions: [{date, start, end, subject, subject_id}]
10
+ unscheduled: [{subject, remaining_minutes}]
11
+ subject_id is the input order, allowing separate events with equal names.
12
+ """
13
+ free_slots = set()
14
+ for slot in available_slots:
15
+ if not (0 <= slot["start"] < slot["end"] <= 1440):
16
+ raise ValueError("Each availability window must be within one day, with start before end.")
17
+ if slot["start"] % 30 or slot["end"] % 30:
18
+ raise ValueError("Time windows must align to 30-minute boundaries.")
19
+ for start in range(slot["start"], slot["end"], 30):
20
+ free_slots.add((slot["date"], start))
21
+
22
+ ordered_slots = sorted(free_slots)
23
+ used = set()
24
+ sessions = []
25
+ unscheduled = []
26
+ ordered_tasks = sorted(enumerate(tasks), key=lambda item: item[1]["exam_date"])
27
+ for subject_id, task in ordered_tasks:
28
+ remaining = task["minutes"]
29
+ if not isinstance(remaining, int) or remaining <= 0 or remaining % 30:
30
+ raise ValueError("Study time must be positive and divisible by 30 minutes.")
31
+ for day, start in ordered_slots:
32
+ if remaining == 0:
33
+ break
34
+ if day >= task["exam_date"] or (day, start) in used:
35
+ continue
36
+ sessions.append({"date": day, "start": start, "end": start + 30,
37
+ "subject": task["subject"], "subject_id": subject_id})
38
+ used.add((day, start))
39
+ remaining -= 30
40
+ if remaining:
41
+ unscheduled.append({"subject": task["subject"], "remaining_minutes": remaining})
42
+ sessions.sort(key=lambda session: (session["date"], session["start"]))
43
+ return sessions, unscheduled