studysystem 1.0.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.
Files changed (112) hide show
  1. studysystem/__init__.py +1 -0
  2. studysystem/assets/note-callouts.lua +100 -0
  3. studysystem/assets/note-no-html.lua +28 -0
  4. studysystem/assets/note.css +146 -0
  5. studysystem/cli.py +344 -0
  6. studysystem/dashboard.html +781 -0
  7. studysystem/dashboard.py +377 -0
  8. studysystem/db/__init__.py +1 -0
  9. studysystem/db/engine.py +158 -0
  10. studysystem/db/migrate.py +122 -0
  11. studysystem/db/migrations/env.py +59 -0
  12. studysystem/db/migrations/script.py.mako +29 -0
  13. studysystem/db/migrations/versions/0000_baseline.py +19 -0
  14. studysystem/db/migrations/versions/0001_the_whole_schema.py +1743 -0
  15. studysystem/db/migrations/versions/0002_semester_ignores_case.py +38 -0
  16. studysystem/db/migrations/versions/0003_course_vault_folder.py +26 -0
  17. studysystem/db/migrations/versions/0004_note_pdf_path.py +26 -0
  18. studysystem/db/migrations/versions/0005_tagging_kind.py +39 -0
  19. studysystem/db/migrations/versions/0006_practice_mode.py +36 -0
  20. studysystem/db/migrations/versions/0007_exam_prep_from.py +25 -0
  21. studysystem/db/migrations/versions/0008_more_papers_kind.py +37 -0
  22. studysystem/db/migrations/versions/0009_past_exam_month_date.py +28 -0
  23. studysystem/db/migrations/versions/0010_task_parts.py +70 -0
  24. studysystem/db/migrations/versions/0011_observation_kind.py +39 -0
  25. studysystem/db/migrations/versions/0012_profile_claim.py +52 -0
  26. studysystem/db/migrations/versions/0013_assumed_instructor_papers.py +40 -0
  27. studysystem/db/migrations/versions/0014_scan_confirmation.py +44 -0
  28. studysystem/db/migrations/versions/0015_practice_item_count.py +37 -0
  29. studysystem/db/migrations/versions/0016_timetable_patterns.py +102 -0
  30. studysystem/db/migrations/versions/0017_course_dropped.py +36 -0
  31. studysystem/db/migrations/versions/0018_syllabus_topics.py +82 -0
  32. studysystem/db/migrations/versions/0019_course_lab_group.py +36 -0
  33. studysystem/db/migrations/versions/0020_chapter_scope.py +61 -0
  34. studysystem/db/migrations/versions/0021_note_retired_at.py +28 -0
  35. studysystem/db/migrations/versions/0022_rescope.py +48 -0
  36. studysystem/db/migrations/versions/0023_backlog_reason.py +42 -0
  37. studysystem/db/migrations/versions/0024_guess_sensitivity.py +35 -0
  38. studysystem/db/migrations/versions/0025_shortfall_inputs.py +83 -0
  39. studysystem/db/migrations/versions/0026_trials_switch.py +36 -0
  40. studysystem/db/tables.py +1096 -0
  41. studysystem/demo.py +722 -0
  42. studysystem/errors.py +39 -0
  43. studysystem/server/__init__.py +83 -0
  44. studysystem/server/__main__.py +5 -0
  45. studysystem/services/__init__.py +1 -0
  46. studysystem/services/adherence.py +147 -0
  47. studysystem/services/assessments.py +171 -0
  48. studysystem/services/capacity.py +164 -0
  49. studysystem/services/claims.py +405 -0
  50. studysystem/services/course_folder.py +82 -0
  51. studysystem/services/courses.py +176 -0
  52. studysystem/services/coverage.py +121 -0
  53. studysystem/services/dashboard_key.py +102 -0
  54. studysystem/services/feedback.py +412 -0
  55. studysystem/services/forward_eval.py +65 -0
  56. studysystem/services/gate.py +77 -0
  57. studysystem/services/generation.py +2864 -0
  58. studysystem/services/ids.py +15 -0
  59. studysystem/services/intake.py +278 -0
  60. studysystem/services/launcher.py +455 -0
  61. studysystem/services/lookups.py +91 -0
  62. studysystem/services/materials.py +97 -0
  63. studysystem/services/note_markdown.py +241 -0
  64. studysystem/services/notes.py +396 -0
  65. studysystem/services/parts.py +65 -0
  66. studysystem/services/past_exams.py +115 -0
  67. studysystem/services/pdf_render.py +148 -0
  68. studysystem/services/pdf_worker.py +184 -0
  69. studysystem/services/plan.py +1300 -0
  70. studysystem/services/private_view.py +38 -0
  71. studysystem/services/profiles.py +544 -0
  72. studysystem/services/programs.py +16 -0
  73. studysystem/services/replacements.py +107 -0
  74. studysystem/services/rescope.py +277 -0
  75. studysystem/services/settings.py +50 -0
  76. studysystem/services/setup.py +235 -0
  77. studysystem/services/shortfall.py +443 -0
  78. studysystem/services/state.py +846 -0
  79. studysystem/services/statements.py +222 -0
  80. studysystem/services/study_loop.py +998 -0
  81. studysystem/services/summaries.py +369 -0
  82. studysystem/services/syllabus.py +138 -0
  83. studysystem/services/system_work.py +113 -0
  84. studysystem/services/taxonomy.py +459 -0
  85. studysystem/services/topics.py +477 -0
  86. studysystem/services/trials.py +201 -0
  87. studysystem/services/unconfirmed.py +95 -0
  88. studysystem/services/units.py +34 -0
  89. studysystem/services/users.py +53 -0
  90. studysystem/services/values.py +168 -0
  91. studysystem/startup.py +147 -0
  92. studysystem/tools/__init__.py +4 -0
  93. studysystem/tools/course_setup.py +185 -0
  94. studysystem/tools/dashboard.py +27 -0
  95. studysystem/tools/feedback.py +66 -0
  96. studysystem/tools/gate.py +24 -0
  97. studysystem/tools/generation.py +156 -0
  98. studysystem/tools/materials.py +32 -0
  99. studysystem/tools/notes.py +29 -0
  100. studysystem/tools/past_exams.py +51 -0
  101. studysystem/tools/ping.py +9 -0
  102. studysystem/tools/plan.py +40 -0
  103. studysystem/tools/profiles.py +94 -0
  104. studysystem/tools/results.py +77 -0
  105. studysystem/tools/study_loop.py +145 -0
  106. studysystem/tools/summaries.py +52 -0
  107. studysystem/tools/topics.py +143 -0
  108. studysystem-1.0.0.dist-info/METADATA +254 -0
  109. studysystem-1.0.0.dist-info/RECORD +112 -0
  110. studysystem-1.0.0.dist-info/WHEEL +4 -0
  111. studysystem-1.0.0.dist-info/entry_points.txt +3 -0
  112. studysystem-1.0.0.dist-info/licenses/LICENSE +21 -0
studysystem/demo.py ADDED
@@ -0,0 +1,722 @@
1
+ """The seeded demo (4.11; D-305 - D-308): `study demo` builds a fresh database of invented data in a
2
+ folder of its own, then serves the dashboard on it. Every row goes through the service layer - the
3
+ same calls the tools make - so the demo proves the real write path, and no fixture file can drift
4
+ from the schema.
5
+
6
+ The data copies the *shape* of one real semester (how many courses, papers, topics, chapters, hours)
7
+ and nothing else: the course codes, names, instructors, targets, topic names and one-line questions
8
+ are invented (D-306). No assessment carries a mark. Dates are relative to the day it runs: exams
9
+ ahead, hours in the last 40 days, plans on past days stamped with a past clock (D-308).
10
+ """
11
+
12
+ import datetime
13
+ import importlib.metadata
14
+ import math
15
+ import os
16
+ import shutil
17
+ import tempfile
18
+ from collections.abc import Sequence
19
+ from pathlib import Path
20
+
21
+ import platformdirs
22
+ from sqlalchemy import Engine, select
23
+
24
+ from studysystem.db.engine import data_dir, db_path
25
+ from studysystem.db.tables import course, material
26
+ from studysystem.errors import StudyError
27
+ from studysystem.services import (
28
+ assessments,
29
+ capacity,
30
+ courses,
31
+ feedback,
32
+ intake,
33
+ materials,
34
+ past_exams,
35
+ plan,
36
+ profiles,
37
+ state,
38
+ study_loop,
39
+ syllabus,
40
+ topics,
41
+ )
42
+ from studysystem.services.generation import start_generation, submit_generation
43
+ from studysystem.services.users import ensure_user
44
+
45
+ DATA_ENV = "STUDYSYSTEM_DATA_DIR"
46
+ DIRECTIVE_COURSE = "CS304"
47
+ DIRECTIVE = "Prefer short MCQ with four options over open questions." # written for the demo
48
+ VAULT_ENV = "STUDYSYSTEM_VAULT_DIR"
49
+ APP_NAME = "studysystem-demo"
50
+ SEMESTER = "Demo Semester"
51
+ PARTIAL = "Partial exam"
52
+ FINAL = "Final exam"
53
+
54
+ # --- the invented semester ------------------------------------------------------------------
55
+ # Each course: the shape of one real course, with an invented name. `partial`/`final` are how many
56
+ # past papers each exam has; `approx` of the final's papers print only a month; `chapters`/`slides`
57
+ # how many materials; `topics` the textbook terms (from the papers when a slot has MIN_PAPERS or
58
+ # more, else the syllabus route, D-218).
59
+ COURSES = [
60
+ {
61
+ "code": "HUM300",
62
+ "name": "Ethics",
63
+ "credits": 3,
64
+ "target": 75,
65
+ "elective": True,
66
+ "hours_per_credit": 2.7,
67
+ "instructor": "Dr. Imani Okafor",
68
+ },
69
+ {
70
+ "code": "ENG300",
71
+ "name": "Academic Writing",
72
+ "planned": False,
73
+ },
74
+ {
75
+ "code": "CS301",
76
+ "name": "Software Design",
77
+ "credits": 4,
78
+ "target": 72,
79
+ "instructor": "Dr. Lena Ortiz",
80
+ "partial": 0,
81
+ "final": 6,
82
+ "chapters": 6,
83
+ "slides": 0,
84
+ "topics": [
85
+ "Requirements Elicitation",
86
+ "UML Class Diagrams",
87
+ "Software Process Models",
88
+ "Design Patterns",
89
+ "Software Testing",
90
+ "Version Control",
91
+ "Project Estimation",
92
+ ],
93
+ },
94
+ {
95
+ "code": "CS302",
96
+ "name": "Web Development",
97
+ "credits": 4,
98
+ "target": 68,
99
+ "instructor": "Prof. Marcus Webb",
100
+ "lab_group": "G1",
101
+ "partial": 2,
102
+ "final": 8,
103
+ "chapters": 4,
104
+ "slides": 0,
105
+ "topics": [
106
+ "HTML Forms",
107
+ "CSS Layout",
108
+ "HTTP Methods",
109
+ "Sessions and Cookies",
110
+ "JavaScript Events",
111
+ "REST APIs",
112
+ "Web Security Basics",
113
+ ],
114
+ },
115
+ {
116
+ "code": "CS303",
117
+ "name": "Operating Systems",
118
+ "credits": 4,
119
+ "target": 65,
120
+ "instructor": "Dr. Yusuf Demir",
121
+ "partial": 2,
122
+ "final": 7,
123
+ "approx": 5,
124
+ "chapters": 2,
125
+ "slides": 1,
126
+ "prep_from": -14,
127
+ "topics": [
128
+ "Process Scheduling",
129
+ "Threads",
130
+ "Mutual Exclusion",
131
+ "Semaphores",
132
+ "Deadlock",
133
+ "Paging",
134
+ "Segmentation",
135
+ "Virtual Memory",
136
+ "Page Replacement",
137
+ "File Systems",
138
+ "Disk Scheduling",
139
+ "I/O Devices",
140
+ "System Calls",
141
+ ],
142
+ },
143
+ {
144
+ "code": "CS304",
145
+ "name": "Computer Networks",
146
+ "credits": 4,
147
+ "target": 70,
148
+ "instructor": "Prof. Anika Rao",
149
+ "partial": 3,
150
+ "final": 10,
151
+ "chapters": 7,
152
+ "slides": 2,
153
+ "topics": [
154
+ "OSI Model",
155
+ "TCP/IP Stack",
156
+ "IP Addressing",
157
+ "Subnetting",
158
+ "Routing Algorithms",
159
+ "Link State Routing",
160
+ "Distance Vector Routing",
161
+ "TCP Congestion Control",
162
+ "TCP Handshake",
163
+ "UDP",
164
+ "DNS",
165
+ "HTTP",
166
+ "Ethernet",
167
+ "ARP",
168
+ "MAC Protocols",
169
+ "Wireless LANs",
170
+ "Network Security",
171
+ "NAT",
172
+ "Error Detection",
173
+ ],
174
+ },
175
+ {
176
+ "code": "CS305",
177
+ "name": "Databases",
178
+ "credits": 3,
179
+ "target": 78,
180
+ "instructor": "Dr. Tomas Varga",
181
+ "lab_group": "G1",
182
+ "partial": 1,
183
+ "final": 7,
184
+ "approx": 3,
185
+ "chapters": 1,
186
+ "slides": 0,
187
+ "topics": [
188
+ "ER Modeling",
189
+ "Relational Algebra",
190
+ "SQL Joins",
191
+ "Normalization",
192
+ "Transactions",
193
+ "Indexing",
194
+ "Query Optimization",
195
+ ],
196
+ },
197
+ {
198
+ "code": "CS306",
199
+ "name": "Algorithms",
200
+ "credits": 3,
201
+ "target": 62,
202
+ "instructor": "Dr. Sofia Lindqvist",
203
+ "partial": 1,
204
+ "final": 8,
205
+ "approx": 1,
206
+ "chapters": 2,
207
+ "slides": 3,
208
+ "topics": [
209
+ "Big-O Notation",
210
+ "Sorting Algorithms",
211
+ "Divide and Conquer",
212
+ "Dynamic Programming",
213
+ "Greedy Algorithms",
214
+ "Graph Traversal",
215
+ "Shortest Paths",
216
+ "Minimum Spanning Trees",
217
+ "Hash Tables",
218
+ "Binary Search Trees",
219
+ ],
220
+ },
221
+ {
222
+ "code": "CS351",
223
+ "name": "Machine Learning",
224
+ "credits": 5,
225
+ "target": 80,
226
+ "instructor": "Prof. Dario Fontaine",
227
+ "no_past_papers": True,
228
+ "chapters": 3,
229
+ "slides": 1,
230
+ "syllabus": [
231
+ "Linear Regression",
232
+ "Logistic Regression",
233
+ "Decision Trees",
234
+ "Overfitting and Regularization",
235
+ "Cross-Validation",
236
+ "Neural Networks",
237
+ "Gradient Descent",
238
+ "Clustering",
239
+ "Dimensionality Reduction",
240
+ ],
241
+ },
242
+ ]
243
+
244
+ # (course, weekday 1 = Monday, start, end, kind, group)
245
+ MEETINGS = [
246
+ ("ENG300", 1, "08:00", "10:00", "lecture", None),
247
+ ("CS301", 1, "10:00", "11:30", "lecture", None),
248
+ ("CS301", 3, "10:00", "11:30", "lecture", None),
249
+ ("CS301", 5, "10:00", "11:30", "lecture", None),
250
+ ("CS302", 1, "13:00", "15:00", "lab", "G1"),
251
+ ("CS302", 1, "15:00", "17:00", "lab", "G1"),
252
+ ("CS302", 2, "08:00", "10:00", "lab", "G1"),
253
+ ("CS302", 2, "10:30", "12:00", "lecture", None),
254
+ ("CS302", 3, "13:00", "15:00", "lab", "G1"),
255
+ ("CS303", 2, "13:00", "14:30", "lecture", None),
256
+ ("CS303", 3, "08:00", "09:30", "lecture", None),
257
+ ("CS303", 5, "08:00", "09:30", "lecture", None),
258
+ ("CS304", 4, "08:00", "09:30", "lecture", None),
259
+ ("CS304", 4, "09:30", "11:00", "lecture", None),
260
+ ("CS304", 5, "11:00", "12:30", "lecture", None),
261
+ ("CS304", 5, "13:00", "15:00", "lab", None),
262
+ ("CS305", 1, "11:30", "13:00", "lab", "G1"),
263
+ ("CS305", 2, "15:00", "17:00", "lab", "G1"),
264
+ ("CS305", 3, "15:00", "17:00", "lab", "G1"),
265
+ ("CS305", 5, "15:00", "16:30", "lecture", None),
266
+ ("CS306", 2, "14:30", "16:00", "lecture", None),
267
+ ("CS306", 2, "16:00", "17:00", "lecture", None),
268
+ ("CS306", 4, "13:00", "14:30", "lecture", None),
269
+ ("CS306", 4, "14:30", "16:00", "lecture", None),
270
+ ("CS351", 4, "11:30", "13:00", "lab", None),
271
+ ("CS351", 4, "16:00", "17:00", "lecture", None),
272
+ ("CS351", 5, "08:00", "10:00", "lecture", None),
273
+ ]
274
+
275
+ # (hours per week, days from today): the declared capacity, insert-only (D-290)
276
+ CAPACITY = [(10, -52), (14.17, -16), (10, -3), (21, 36), (10, 47)]
277
+
278
+ # Days (from today) the plan is asked for, each stamped 08:00 that morning (D-308) - before the
279
+ # hours of that day, so an hour scoped to a shown item reads in_plan.
280
+ PLAN_DAYS = (-44, -39, -34, -29, -24, -19, -15, -11, -7, -4, -2, -1)
281
+
282
+ # The hours: (days from today, minutes, kind, deviation reason). Kind P = scoped to an item the
283
+ # plan in force showed; O = a topic it did not show; C = course level (no scope).
284
+ HOURS = [
285
+ (-40, 60, "P", None),
286
+ (-38, 45, "P", None),
287
+ (-35, 90, "O", None),
288
+ (-33, 50, "P", None),
289
+ (-30, 60, "P", None),
290
+ (-27, 75, "O", "disagreed"),
291
+ (-25, 40, "P", None),
292
+ (-22, 80, "P", None),
293
+ (-20, 55, "O", None),
294
+ (-17, 60, "P", None),
295
+ (-15, 45, "P", None),
296
+ (-13, 70, "P", None),
297
+ (-11, 50, "O", "backlog"),
298
+ (-9, 60, "P", None),
299
+ (-8, 90, "P", None),
300
+ (-6, 45, "O", None),
301
+ (-4, 60, "P", None),
302
+ (-3, 100, "C", None),
303
+ (-2, 50, "P", None),
304
+ (-2, 40, "O", "too-tired"),
305
+ (-1, 75, "P", None),
306
+ (0, 60, "P", None),
307
+ (0, 45, "O", None),
308
+ (0, 40, "C", "external-deadline"),
309
+ ]
310
+
311
+ QUESTIONS = (
312
+ "Explain {t} and give one example.",
313
+ "Compare two approaches to {t}.",
314
+ "Describe the main steps of {t}.",
315
+ "List the advantages and limits of {t}.",
316
+ )
317
+
318
+
319
+ # --- the folder, and the refusal to touch the live one --------------------------------------
320
+
321
+
322
+ def demo_dir() -> Path:
323
+ """Where the demo lives: its own app folder, never the live one."""
324
+ return Path(platformdirs.user_data_dir(APP_NAME, appauthor=False))
325
+
326
+
327
+ def prepare(folder: Path, live: Sequence[Path] = ()) -> Path:
328
+ """Point this process at `folder`, empty. Sets the data and vault folders in the environment
329
+ before anything calls `db_path()`, so no later call can reach the live data or a real vault.
330
+ Refuses a folder that is, or holds, a live data folder (the default one, any in `live`, and
331
+ the one the environment named before this call). Deletes only the old demo database, its
332
+ -wal and -shm, and the papers and materials folders - all inside `folder`. Returns the
333
+ database path."""
334
+ folder = folder.resolve()
335
+ lives = [Path(platformdirs.user_data_dir("studysystem", appauthor=False)), *live]
336
+ named = os.environ.get(DATA_ENV)
337
+ if named:
338
+ lives.append(Path(named))
339
+ for other in lives:
340
+ other = other.resolve()
341
+ if folder == other or (other / "studysystem.db") == folder / "studysystem.db":
342
+ raise StudyError(
343
+ code="demo_refused",
344
+ message=f"{folder} is the live data folder",
345
+ fix="the demo builds its own database in a separate folder; pick another one",
346
+ )
347
+ folder.mkdir(parents=True, exist_ok=True)
348
+ os.environ[DATA_ENV] = str(folder)
349
+ os.environ[VAULT_ENV] = str(folder / "vault") # never created: no export can write here
350
+ path = db_path()
351
+ assert path.parent == folder
352
+ for name in ("studysystem.db", "studysystem.db-wal", "studysystem.db-shm"):
353
+ (folder / name).unlink(missing_ok=True)
354
+ for name in ("papers", "materials", "snapshots"):
355
+ shutil.rmtree(folder / name, ignore_errors=True)
356
+ return path
357
+
358
+
359
+ # --- tiny PDFs ------------------------------------------------------------------------------
360
+
361
+
362
+ def pdf_pages(texts: Sequence[str]) -> bytes:
363
+ """A valid PDF with one page per text, each a text layer of one line (plain words only)."""
364
+ objects: list[bytes] = []
365
+
366
+ def add(body: bytes) -> int:
367
+ objects.append(body)
368
+ return len(objects)
369
+
370
+ add(b"<< /Type /Catalog /Pages 2 0 R >>")
371
+ add(b"") # the page tree, filled in once the pages have numbers
372
+ font = add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>")
373
+ pages = []
374
+ for text in texts:
375
+ draw = f"BT /F1 12 Tf 72 720 Td ({text}) Tj ET".encode()
376
+ stream = add(b"<< /Length %d >>\nstream\n" % len(draw) + draw + b"\nendstream")
377
+ pages.append(
378
+ add(
379
+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents %d 0 R"
380
+ b" /Resources << /Font << /F1 %d 0 R >> >> >>" % (stream, font)
381
+ )
382
+ )
383
+ kids = b" ".join(b"%d 0 R" % p for p in pages)
384
+ objects[1] = b"<< /Type /Pages /Kids [%s] /Count %d >>" % (kids, len(pages))
385
+
386
+ out = b"%PDF-1.4\n"
387
+ offsets = []
388
+ for num, body in enumerate(objects, start=1):
389
+ offsets.append(len(out))
390
+ out += b"%d 0 obj\n" % num + body + b"\nendobj\n"
391
+ xref = len(out)
392
+ out += b"xref\n0 %d\n0000000000 65535 f \n" % (len(objects) + 1)
393
+ out += b"".join(b"%010d 00000 n \n" % o for o in offsets)
394
+ out += b"trailer\n<< /Size %d /Root 1 0 R >>\nstartxref\n%d\n%%%%EOF\n" % (
395
+ len(objects) + 1,
396
+ xref,
397
+ )
398
+ return out
399
+
400
+
401
+ def _write(folder: Path, name: str, texts: Sequence[str]) -> str:
402
+ folder.mkdir(parents=True, exist_ok=True)
403
+ path = folder / name
404
+ path.write_bytes(pdf_pages(texts))
405
+ return str(path)
406
+
407
+
408
+ # --- the seed -------------------------------------------------------------------------------
409
+
410
+
411
+ def _utc(local: datetime.datetime) -> str:
412
+ """A naive local moment as the UTC timestamp string `ids.now()` returns (D-308)."""
413
+ return local.astimezone(datetime.UTC).strftime(study_loop.TIMESTAMP)
414
+
415
+
416
+ def _paper_date(i: int, slot: str, approx: bool) -> tuple[str, str]:
417
+ """(session type, date) of the i-th paper, newest year first: a first and a second session per
418
+ year, 2025 downwards. Just dates - the papers say nothing."""
419
+ year = 2025 - i // 2
420
+ first = i % 2 == 0
421
+ month = ("02" if first else "09") if slot == FINAL else ("03" if first else "10")
422
+ kind = "first" if first else "second"
423
+ return kind, f"{year}-{month}" if approx else f"{year}-{month}-{5 + 2 * i:02d}"
424
+
425
+
426
+ def _items(slot: str, p: int, names: Sequence[str]) -> list[dict]:
427
+ """The transcribed questions of the p-th paper of a slot: six on the final, five on a
428
+ partial, stepping through the topics so the first papers touch every one."""
429
+ n = len(names)
430
+ out = []
431
+ for j in range(6 if slot == FINAL else 5):
432
+ topic_name = names[(p * 2 + j) % n if slot == FINAL else (p + j) % min(n, 6)]
433
+ marks = [10, 15, 20, 10, 15, 20][j]
434
+ out.append(
435
+ {
436
+ "position": j + 1,
437
+ "question": QUESTIONS[(p + j) % 4].format(t=topic_name),
438
+ "answer_key": None,
439
+ "marks": None if (p % 3 == 0 and j % 2 == 1) else marks,
440
+ "topic": {"proposed_name": topic_name},
441
+ }
442
+ )
443
+ return out
444
+
445
+
446
+ def _accept_proposed(engine: Engine, uid: str, code: str) -> dict[str, str]:
447
+ """Accept every proposed topic of the course. Returns {name: topic_id} of its topics."""
448
+ found = topics.get_topics(engine, uid, code)["topics"]
449
+ for t in found:
450
+ if t["status"] == "proposed":
451
+ topics.confirm_topic_proposal(engine, uid, t["id"], "accept")
452
+ return {t["name"]: t["id"] for t in found}
453
+
454
+
455
+ def _papers(engine: Engine, uid: str, spec: dict, work: Path) -> int:
456
+ """Register and transcribe the course's past papers, accept the topics, derive profiles."""
457
+ code, names = spec["code"], spec["topics"]
458
+ count = 0
459
+ for slot, n in ((PARTIAL, spec["partial"]), (FINAL, spec["final"])):
460
+ approx_n = spec.get("approx", 0) if slot == FINAL else 0
461
+ for i in range(n):
462
+ kind, date = _paper_date(i, slot, approx=i >= n - approx_n)
463
+ path = _write(
464
+ work / code / slot,
465
+ f"{code}_{date}_{i}.pdf",
466
+ [f"Invented {slot} paper {code} {date}"],
467
+ )
468
+ paper = past_exams.add_past_exam(engine, uid, code, slot, kind, date, path)
469
+ # Slots with fewer than MIN_PAPERS papers stay registered, untranscribed: the plan
470
+ # then asks for them, as it does for a real course still being set up.
471
+ if n >= profiles.MIN_PAPERS:
472
+ task = start_generation(engine, uid, "transcription", paper["past_exam_id"])
473
+ reply = submit_generation(
474
+ engine,
475
+ uid,
476
+ task.payload["task_id"],
477
+ {"items": _items(slot, i, names)},
478
+ )
479
+ assert reply["status"] == "closed", reply
480
+ count += 1
481
+ _accept_proposed(engine, uid, code)
482
+ for slot, n in ((PARTIAL, spec["partial"]), (FINAL, spec["final"])):
483
+ if n >= profiles.MIN_PAPERS:
484
+ profiles.derive_profile(engine, uid, code, slot)
485
+ return count
486
+
487
+
488
+ def _materials(engine: Engine, uid: str, spec: dict, topic_ids: dict[str, str], work: Path) -> int:
489
+ """Add the course's chapters and slides, tag each to a slice of its topics, write a note for
490
+ every chapter but the last of a course with three or more (so the course keeps one untaught
491
+ chapter, as a real one does mid-term)."""
492
+ code = spec["code"]
493
+ files = [("chapter", n) for n in range(1, spec["chapters"] + 1)] + [
494
+ ("slides", n) for n in range(1, spec["slides"] + 1)
495
+ ]
496
+ ids = list(topic_ids.values())
497
+ per = max(1, math.ceil(len(ids) / len(files)))
498
+ for index, (kind, n) in enumerate(files):
499
+ label = "Chapter" if kind == "chapter" else "Slides"
500
+ topic_name = list(topic_ids)[min(index * per, len(ids) - 1)].replace("/", "-")
501
+ name = f"{code} {label} {n} {topic_name}.pdf"
502
+ path = _write(
503
+ work / code / "materials",
504
+ name,
505
+ [f"{label} {n} of {code} introduces {topic_name} with one worked example"],
506
+ )
507
+ added = materials.add_material(engine, uid, code, path, kind)
508
+ chosen = ids[index * per : (index + 1) * per] or [ids[index % len(ids)]]
509
+ task = start_generation(engine, uid, "tagging", material_id=added["material_id"])
510
+ submit_generation(
511
+ engine, uid, task.payload["task_id"], {"topics": [{"id": t} for t in chosen]}
512
+ )
513
+ last_chapter = kind == "chapter" and n == spec["chapters"]
514
+ if kind == "chapter" and not (spec["chapters"] >= 3 and last_chapter):
515
+ task = start_generation(engine, uid, "note", material_id=added["material_id"])
516
+ body = f"# {label} {n}\n\nKey idea: {topic_name}. Invented demo note."
517
+ submit_generation(
518
+ engine, uid, task.payload["task_id"], {"notes": [{"section": 1, "body": body}]}
519
+ )
520
+ return len(files)
521
+
522
+
523
+ def _hour(engine, uid, shown, entry, k, started_at, minutes, topic_ids):
524
+ """Log one hour of the plan's kind (see HOURS). Returns the minutes logged."""
525
+ _, _, kind, reason = entry
526
+ planned = [c["code"] for c in COURSES if c.get("planned", True) and c["code"] != "ENG300"]
527
+ hint = planned[k % len(planned)]
528
+ scope: dict = {}
529
+ code = hint
530
+ if kind == "P" and shown:
531
+ mine = [i for i in shown if i.get("code") == hint] or shown
532
+ item = mine[k % len(mine)]
533
+ code = item["code"]
534
+ if item.get("setup_key"):
535
+ scope = {"setup_key": item["setup_key"]}
536
+ elif item.get("material_id"):
537
+ scope = {"material_id": item["material_id"]}
538
+ else:
539
+ scope = {"topic_id": item["topic_id"]}
540
+ elif kind == "O" and topic_ids.get(hint):
541
+ # a topic of the course the plan did not show
542
+ seen = {i.get("topic_id") for i in shown}
543
+ free = [t for t in topic_ids[hint].values() if t not in seen]
544
+ if free:
545
+ scope = {"topic_id": free[k % len(free)]}
546
+ study_loop.log_hours(
547
+ engine,
548
+ uid,
549
+ code,
550
+ minutes=minutes,
551
+ started_at=started_at,
552
+ deviation_reason=reason,
553
+ **scope,
554
+ )
555
+ return minutes
556
+
557
+
558
+ def _generated_item(engine: Engine, uid: str) -> int:
559
+ """One practice item generated from CS304's first chapter, on the first topic its task
560
+ offers. Written through the generation contract, as a host would. Returns 1."""
561
+ with engine.connect() as conn:
562
+ first = conn.execute(
563
+ select(material.c.id)
564
+ .join(course, course.c.id == material.c.course_id)
565
+ .where(course.c.code == DIRECTIVE_COURSE, material.c.kind == "chapter")
566
+ .order_by(material.c.id) # ULIDs sort by creation: the first chapter added
567
+ .limit(1)
568
+ ).scalar_one()
569
+ task = start_generation(engine, uid, "practice", material_id=first, count=1)
570
+ topic_id = task.payload["rules"]["topics"][0]["id"]
571
+ item = {
572
+ "question": "A host has address 10.4.17.200/21. Give its network address and the last "
573
+ "usable host address of its subnet.",
574
+ "answer_key": "Network 10.4.16.0; last usable host 10.4.23.254.",
575
+ "topic_id": topic_id,
576
+ "source": "from-material",
577
+ }
578
+ reply = submit_generation(engine, uid, task.payload["task_id"], {"items": [item]})
579
+ assert reply["status"] == "closed", reply
580
+ return 1
581
+
582
+
583
+ def seed(engine: Engine, today: datetime.date | None = None) -> dict:
584
+ """Write the whole demo through the services and check it reads back (`get_state`). Returns a
585
+ summary: counts of what was written. `today` defaults to the machine's date."""
586
+ now_local = datetime.datetime.now().astimezone()
587
+ today = today or now_local.date()
588
+ uid = ensure_user(engine)
589
+
590
+ def day(offset: int) -> datetime.date:
591
+ return today + datetime.timedelta(days=offset)
592
+
593
+ summary: dict = {
594
+ "courses": 0,
595
+ "papers": 0,
596
+ "materials": 0,
597
+ "hours": 0,
598
+ "minutes": 0,
599
+ "plans": 0,
600
+ }
601
+ topic_ids: dict[str, dict[str, str]] = {}
602
+ work = Path(tempfile.mkdtemp(prefix="studysystem-demo-"))
603
+ try:
604
+ for spec in COURSES:
605
+ code = spec["code"]
606
+ courses.add_course(engine, uid, code, spec["name"], SEMESTER, spec.get("planned", True))
607
+ summary["courses"] += 1
608
+ for field in ("credits", "instructor", "lab_group", "hours_per_credit"):
609
+ if field in spec:
610
+ courses.set_course_input(engine, uid, code, field, spec[field])
611
+ if "target" in spec:
612
+ courses.set_course_input(engine, uid, code, "target_grade", spec["target"])
613
+ if spec.get("elective"):
614
+ courses.set_course_input(engine, uid, code, "elective", True)
615
+ if spec.get("no_past_papers"):
616
+ courses.set_course_input(engine, uid, code, "no_past_papers", True)
617
+ if not spec.get("planned", True):
618
+ continue # his timetable only: one final, weight inferred, no date
619
+ assessments.add_assessment(engine, uid, code, PARTIAL, "exam", 30)
620
+ assessments.set_assessment_input(
621
+ engine, uid, code, PARTIAL, "date", day(19).isoformat()
622
+ )
623
+ if "prep_from" in spec:
624
+ prep = day(spec["prep_from"]).isoformat()
625
+ assessments.set_assessment_input(engine, uid, code, PARTIAL, "prep_from", prep)
626
+ assessments.set_assessment_input(engine, uid, code, FINAL, "weight", 70)
627
+ assessments.set_assessment_input(
628
+ engine, uid, code, FINAL, "date", f"~{day(61).isoformat()}"
629
+ )
630
+
631
+ if "topics" in spec:
632
+ summary["papers"] += _papers(engine, uid, spec, work)
633
+ topic_ids[code] = _accept_proposed(engine, uid, code)
634
+ elif "syllabus" in spec:
635
+ syllabus.add_syllabus_topics(engine, uid, code, FINAL, spec["syllabus"])
636
+ topic_ids[code] = _accept_proposed(engine, uid, code)
637
+ if code in topic_ids and spec.get("chapters", 0) + spec.get("slides", 0):
638
+ summary["materials"] += _materials(engine, uid, spec, topic_ids[code], work)
639
+
640
+ # one timetable task for the whole week
641
+ task = start_generation(engine, uid, "timetable")
642
+ meetings = []
643
+ for code, weekday, start, end, kind, group in MEETINGS:
644
+ m = {
645
+ "course_code": code,
646
+ "weekday": weekday,
647
+ "start_time": start,
648
+ "end_time": end,
649
+ "kind": kind,
650
+ }
651
+ if group:
652
+ m["group_label"] = group
653
+ meetings.append(m)
654
+ reply = submit_generation(engine, uid, task.payload["task_id"], {"meetings": meetings})
655
+ assert reply["status"] == "closed", reply
656
+ summary["meetings"] = len(meetings)
657
+
658
+ for hours, offset in CAPACITY:
659
+ capacity.set_capacity(engine, uid, hours, day(offset).isoformat())
660
+
661
+ # one proposed directive, so the Plan page's System work block has a Confirm to show
662
+ # (4.12, D-311) beside CS304's Partial, whose 3 papers leave its past-papers item at 0
663
+ feedback.submit_feedback(
664
+ engine, uid, "format-preference", directive_text=DIRECTIVE, code=DIRECTIVE_COURSE
665
+ )
666
+ summary["directives"] = 1
667
+
668
+ # one generated question on a transcribed CS304 topic, so a walkthrough with trials on
669
+ # has an item to hide among a paper's questions (4.13, D-314)
670
+ summary["generated"] = _generated_item(engine, uid)
671
+
672
+ # Past days, oldest first: the plan of the morning (stamped 08:00), then that day's hours.
673
+ shown: list[dict] = []
674
+ elapsed = now_local.hour * 60 + now_local.minute # minutes of today gone
675
+ by_day: dict[int, list] = {}
676
+ for k, entry in enumerate(HOURS):
677
+ by_day.setdefault(entry[0], []).append((k, entry))
678
+ for offset in range(-44, 1):
679
+ if offset in PLAN_DAYS:
680
+ clock = datetime.datetime.combine(day(offset), datetime.time(8, 0))
681
+ made = plan.get_plan(engine, uid, day(offset), now=_utc(clock))
682
+ shown = [i for lane in made["lanes"].values() for i in lane["items"]]
683
+ summary["plans"] += 1
684
+ for slot_no, (k, entry) in enumerate(by_day.get(offset, [])):
685
+ _, minutes, _, _ = entry
686
+ if offset == 0:
687
+ minutes = min(minutes, elapsed - 2) # a start still today (date alone = now)
688
+ if minutes < 1:
689
+ continue
690
+ started = day(0).isoformat()
691
+ else:
692
+ started = f"{day(offset).isoformat()}T{17 + 2 * slot_no:02d}:00"
693
+ summary["minutes"] += _hour(
694
+ engine, uid, shown, entry, k, started, minutes, topic_ids
695
+ )
696
+ summary["hours"] += 1
697
+ plan.get_plan(engine, uid, today) # today's plan, on the real clock
698
+ summary["plans"] += 1
699
+ finally:
700
+ shutil.rmtree(work, ignore_errors=True)
701
+
702
+ summary["topics"] = {code: len(found) for code, found in topic_ids.items()}
703
+ # self-check: every section of the dashboard's blob builds and passes its schema
704
+ blob = state.get_state(engine, uid, today, importlib.metadata.version("studysystem"))
705
+ summary["state_sections"] = sorted(
706
+ k for k in blob if k not in ("server_version", "generated_at")
707
+ )
708
+ return summary
709
+
710
+
711
+ def build(folder: Path | None = None, live: Sequence[Path] = ()) -> tuple[Engine, dict, Path]:
712
+ """Prepare the demo folder, migrate a fresh database, seed it. Returns (engine, summary,
713
+ database path)."""
714
+ from studysystem.db import migrate
715
+ from studysystem.db.engine import make_engine
716
+
717
+ path = prepare(folder or demo_dir(), live)
718
+ assert data_dir() == path.parent
719
+ engine = make_engine(path)
720
+ migrate.upgrade(engine)
721
+ with intake.in_this_process(): # the PDFs are its own
722
+ return engine, seed(engine), path