nit-tools 0.1.0__tar.gz → 0.2.0__tar.gz

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 (49) hide show
  1. {nit_tools-0.1.0 → nit_tools-0.2.0}/CHANGELOG.md +7 -1
  2. {nit_tools-0.1.0 → nit_tools-0.2.0}/PKG-INFO +101 -9
  3. {nit_tools-0.1.0 → nit_tools-0.2.0}/README.md +100 -8
  4. {nit_tools-0.1.0 → nit_tools-0.2.0}/docs/api.md +47 -0
  5. {nit_tools-0.1.0 → nit_tools-0.2.0}/examples.py +25 -0
  6. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/__init__.py +3 -1
  7. nit_tools-0.2.0/nit_tools/async_client.py +86 -0
  8. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/client.py +75 -9
  9. nit_tools-0.2.0/nit_tools/insights.py +100 -0
  10. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools.egg-info/PKG-INFO +101 -9
  11. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools.egg-info/SOURCES.txt +3 -0
  12. {nit_tools-0.1.0 → nit_tools-0.2.0}/pyproject.toml +1 -1
  13. nit_tools-0.2.0/tests/test_insights.py +168 -0
  14. {nit_tools-0.1.0 → nit_tools-0.2.0}/.env.example +0 -0
  15. {nit_tools-0.1.0 → nit_tools-0.2.0}/CONTRIBUTING.md +0 -0
  16. {nit_tools-0.1.0 → nit_tools-0.2.0}/LICENSE +0 -0
  17. {nit_tools-0.1.0 → nit_tools-0.2.0}/MANIFEST.in +0 -0
  18. {nit_tools-0.1.0 → nit_tools-0.2.0}/NOTICE +0 -0
  19. {nit_tools-0.1.0 → nit_tools-0.2.0}/SECURITY.md +0 -0
  20. {nit_tools-0.1.0 → nit_tools-0.2.0}/docs/assets/README.md +0 -0
  21. {nit_tools-0.1.0 → nit_tools-0.2.0}/docs/assets/nit-logo.jpg +0 -0
  22. {nit_tools-0.1.0 → nit_tools-0.2.0}/docs/releasing.md +0 -0
  23. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/auth.py +0 -0
  24. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/downloads.py +0 -0
  25. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/errors.py +0 -0
  26. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/models.py +0 -0
  27. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/my_class.py +0 -0
  28. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/reports.py +0 -0
  29. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools/user.py +0 -0
  30. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools.egg-info/dependency_links.txt +0 -0
  31. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools.egg-info/requires.txt +0 -0
  32. {nit_tools-0.1.0 → nit_tools-0.2.0}/nit_tools.egg-info/top_level.txt +0 -0
  33. {nit_tools-0.1.0 → nit_tools-0.2.0}/scripts/check_distribution.py +0 -0
  34. {nit_tools-0.1.0 → nit_tools-0.2.0}/setup.cfg +0 -0
  35. {nit_tools-0.1.0 → nit_tools-0.2.0}/test_script.py +0 -0
  36. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_auth_file.py +0 -0
  37. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_auto_auth.py +0 -0
  38. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_class_detection.py +0 -0
  39. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_client.py +0 -0
  40. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_connect.py +0 -0
  41. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_downloads.py +0 -0
  42. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_errors.py +0 -0
  43. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_local_storage.py +0 -0
  44. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_models.py +0 -0
  45. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_my_class.py +0 -0
  46. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_reports.py +0 -0
  47. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_students.py +0 -0
  48. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_teachers_report.py +0 -0
  49. {nit_tools-0.1.0 → nit_tools-0.2.0}/tests/test_user.py +0 -0
@@ -2,7 +2,13 @@
2
2
 
3
3
  Changes that affect library users are recorded here.
4
4
 
5
- ## Unreleased
5
+ ## 0.2.0 — 2026-12-05
6
+
7
+ - Add configurable in-memory diary caching and explicit refresh. Diary reads now
8
+ reuse responses for 60 seconds by default; set `cache_ttl=0` to disable caching.
9
+ - Add snapshot-based homework, mark, and attachment change tracking.
10
+ - Add per-subject grade statistics and half-period comparisons.
11
+ - Add AsyncNITClient with serialized worker execution and async class access.
6
12
 
7
13
  ## 0.1.0
8
14
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nit-tools
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Python client for the NIT school diary
5
5
  Author: deltaaa00
6
6
  License-Expression: Apache-2.0
@@ -37,6 +37,7 @@ Dynamic: license-file
37
37
 
38
38
  # nit-tools
39
39
 
40
+ [![PyPI](https://img.shields.io/pypi/v/nit-tools)](https://pypi.org/project/nit-tools/)
40
41
  [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)](#installation)
41
42
  [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-52796F)](https://github.com/deltaaa00/NIT-Tools/blob/main/LICENSE)
42
43
  [![API: student only](https://img.shields.io/badge/API-student%20only-D28B26)](https://github.com/deltaaa00/NIT-Tools/blob/main/docs/api.md)
@@ -44,7 +45,9 @@ Dynamic: license-file
44
45
 
45
46
  An unofficial Python client for the **student-facing NIT electronic diary**.
46
47
  Read lessons, homework, marks, classmates, teachers, and profiles; download
47
- homework attachments; and create Excel reports.
48
+ homework attachments; and create Excel reports. Use `NITClient` in synchronous
49
+ scripts or `AsyncNITClient` in bots and async applications. Both support diary
50
+ caching, change tracking, and grade statistics.
48
51
 
49
52
  **Independent project:** nit-tools is not affiliated with, endorsed by, or
50
53
  maintained by NIT or the operators of nit.school. The official service is
@@ -62,12 +65,27 @@ or applicable law.
62
65
  **Student API only.** Teacher account workflows are not implemented. Support
63
66
  for the teacher API may be considered in the future.
64
67
 
68
+ ## Features
69
+
70
+ | Task | API |
71
+ | --- | --- |
72
+ | Read a typed diary day, homework, and marks | `get_day()`, `get_homework()`, `get_marks()` |
73
+ | Reuse diary responses or fetch fresh data | `cache_ttl`, `get_day(..., refresh=True)`, `clear_cache()` |
74
+ | Detect homework, grade, and attachment changes | `get_changes()` |
75
+ | Calculate per-subject grade statistics | `get_statistics()` |
76
+ | Export grade journals and people to Excel | `export_marks()`, `export_user()`, class export methods |
77
+ | Read teachers and classmates | `my_class().get_teachers()`, `my_class().get_students()` |
78
+ | Download homework files | `download_homework()` |
79
+ | Use the library without blocking an async application | `AsyncNITClient` |
80
+
65
81
  ## Contents
66
82
 
67
83
  - [Installation](#installation)
68
84
  - [Quick start](#quick-start)
69
85
  - [Authentication and saved sessions](#authentication-and-saved-sessions)
70
86
  - [Diary, homework, and marks](#diary-homework-and-marks)
87
+ - [Caching, changes, and statistics](#caching-changes-and-statistics)
88
+ - [Async applications](#async-applications)
71
89
  - [Excel reports](#excel-reports)
72
90
  - [Teachers and classmates](#teachers-and-classmates)
73
91
  - [User profiles](#user-profiles)
@@ -83,7 +101,25 @@ and GitHub release checks.
83
101
 
84
102
  ## Installation
85
103
 
86
- Requires **Python 3.10+**. From a checkout or downloaded copy of this repository:
104
+ Requires **Python 3.10+**. Install from PyPI:
105
+
106
+ ```sh
107
+ pip install nit-tools
108
+ python -m playwright install chromium
109
+ ```
110
+
111
+ Upgrade an existing installation:
112
+
113
+ ```sh
114
+ pip install --upgrade nit-tools
115
+ ```
116
+
117
+ Version **0.2.0** adds caching, change tracking, grade statistics, and the async
118
+ client. Existing synchronous methods remain available. Diary reads now reuse
119
+ responses for 60 seconds by default; use `refresh=True` for an immediate update,
120
+ or `cache_ttl=0` to preserve request-on-every-read behavior.
121
+
122
+ Alternatively, install from a checkout or downloaded copy of this repository:
87
123
 
88
124
  ```sh
89
125
  python -m venv .venv
@@ -99,8 +135,7 @@ library locally.
99
135
  Playwright authentication is always included. Installing the Python package
100
136
  does not install its Chromium browser; the separate Playwright command above
101
137
  is required for fresh login. Reading an existing saved session does not launch
102
- a browser. This documentation does not assume that a public PyPI package has
103
- already been published.
138
+ a browser.
104
139
 
105
140
  ## Quick start
106
141
 
@@ -234,7 +269,7 @@ without attachments. `get_marks()` returns **lessons containing mark records**,
234
269
  including attendance-only records. `mark.point` remains a string such as `"10"`
235
270
  or `""`; `mark.absence` remains the API code, including zero.
236
271
 
237
- Every client helper fetches data. To reuse a fetched day without another request,
272
+ Diary helpers reuse cached responses for 60 seconds by default. To filter an already fetched day,
238
273
  call `day.get_lessons()`, `day.get_homework()`, or `day.get_marks()` instead.
239
274
 
240
275
  ### A period
@@ -256,6 +291,64 @@ For the original response, call `get_diary(datetime.date(...))`. `get_days()`
256
291
  returns every day from a single response; neither method assumes a fixed week
257
292
  length. Modeled days, lessons, and marks expose `.raw` for additional API fields.
258
293
 
294
+ ## Caching, changes, and statistics
295
+
296
+ Diary responses are cached **in memory**, per user, school, and date, for
297
+ 60 seconds. Returned data is copied so local edits cannot corrupt the cache.
298
+ Set `cache_ttl=0` on `NITClient.connect()` or the constructor to disable caching.
299
+ Errors are never cached; reauthentication clears cached responses.
300
+
301
+ ```python
302
+ day = client.get_day("2026-11-30")
303
+ fresh_day = client.get_day("2026-11-30", refresh=True)
304
+ client.clear_cache()
305
+
306
+ # First call establishes a baseline; subsequent calls return differences.
307
+ client.get_changes("2026-11-30")
308
+ # Poll again later, for example from your application's scheduler.
309
+ for change in client.get_changes("2026-11-30"):
310
+ print(change.subject, change.kind, change.action, change.before, change.after)
311
+
312
+ for stats in client.get_statistics("2026-11-01", "2026-11-30"):
313
+ print(stats.subject, stats.count, stats.average, stats.change)
314
+ ```
315
+
316
+ `get_changes()` always refreshes. It reports added, updated, and removed
317
+ homework, mark records, and attachments. Renewed signed attachment URLs are
318
+ ignored. Failed requests and omitted dates preserve the previous baseline.
319
+ Snapshots last only for this client instance; they are not saved to disk.
320
+ Lessons are matched by number and subject; moving a lesson appears as removals
321
+ and additions. Marks without IDs are matched by their position.
322
+
323
+ Statistics include grade count, numeric count, average, minimum, maximum, and
324
+ averages for the two calendar halves of the requested period. `change` is the
325
+ second-half average minus the first-half average, or `None` when either half
326
+ has no numeric grades. Attendance-only records are excluded; text grades count
327
+ but do not affect averages. These are unweighted descriptive statistics.
328
+
329
+ ## Async applications
330
+
331
+ ```python
332
+ from nit_tools import AsyncNITClient
333
+
334
+ async def read_diary(email, password):
335
+ async with await AsyncNITClient.connect(
336
+ email=email, password=password, require_class_id=True,
337
+ ) as client:
338
+ day = await client.get_day("2026-11-30")
339
+ teachers = await client.my_class().get_teachers()
340
+ return day, teachers
341
+ ```
342
+
343
+ Client methods are awaited, including exports, downloads, statistics, and change
344
+ tracking. `my_class()` returns a proxy immediately; await its methods.
345
+ `from_auth()` and the token constructor also work without awaiting creation.
346
+ Each client uses one worker thread and serializes calls, including requests
347
+ whose caller was cancelled. Cancellation does not interrupt an in-flight HTTP
348
+ request or browser login. Use an async context manager or `await client.aclose()`
349
+ to wait for pending work and release the worker. This is a threaded async
350
+ adapter around the Requests client, not a separate HTTP transport.
351
+
259
352
  ## Excel reports
260
353
 
261
354
  ### Grades: `summary` and `detailed`
@@ -465,9 +558,8 @@ Avoid sharing `.raw` contents or generated reports in public diagnostics.
465
558
  They do not certify live service availability, pagination behavior, or all
466
559
  account configurations. Period results reflect records returned by the diary;
467
560
  they are not a completeness guarantee for every official journal column.
468
- - **Execution:** the client is synchronous. Call it from an appropriate worker
469
- when integrating with an async server; Playwright's synchronous login cannot
470
- run inside an active asyncio event loop on the same thread.
561
+ - **Execution:** `NITClient` is synchronous. Use `AsyncNITClient` in an async
562
+ application; it moves blocking operations and browser login into a worker.
471
563
 
472
564
  ## Development
473
565
 
@@ -6,6 +6,7 @@
6
6
 
7
7
  # nit-tools
8
8
 
9
+ [![PyPI](https://img.shields.io/pypi/v/nit-tools)](https://pypi.org/project/nit-tools/)
9
10
  [![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)](#installation)
10
11
  [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-52796F)](https://github.com/deltaaa00/NIT-Tools/blob/main/LICENSE)
11
12
  [![API: student only](https://img.shields.io/badge/API-student%20only-D28B26)](https://github.com/deltaaa00/NIT-Tools/blob/main/docs/api.md)
@@ -13,7 +14,9 @@
13
14
 
14
15
  An unofficial Python client for the **student-facing NIT electronic diary**.
15
16
  Read lessons, homework, marks, classmates, teachers, and profiles; download
16
- homework attachments; and create Excel reports.
17
+ homework attachments; and create Excel reports. Use `NITClient` in synchronous
18
+ scripts or `AsyncNITClient` in bots and async applications. Both support diary
19
+ caching, change tracking, and grade statistics.
17
20
 
18
21
  **Independent project:** nit-tools is not affiliated with, endorsed by, or
19
22
  maintained by NIT or the operators of nit.school. The official service is
@@ -31,12 +34,27 @@ or applicable law.
31
34
  **Student API only.** Teacher account workflows are not implemented. Support
32
35
  for the teacher API may be considered in the future.
33
36
 
37
+ ## Features
38
+
39
+ | Task | API |
40
+ | --- | --- |
41
+ | Read a typed diary day, homework, and marks | `get_day()`, `get_homework()`, `get_marks()` |
42
+ | Reuse diary responses or fetch fresh data | `cache_ttl`, `get_day(..., refresh=True)`, `clear_cache()` |
43
+ | Detect homework, grade, and attachment changes | `get_changes()` |
44
+ | Calculate per-subject grade statistics | `get_statistics()` |
45
+ | Export grade journals and people to Excel | `export_marks()`, `export_user()`, class export methods |
46
+ | Read teachers and classmates | `my_class().get_teachers()`, `my_class().get_students()` |
47
+ | Download homework files | `download_homework()` |
48
+ | Use the library without blocking an async application | `AsyncNITClient` |
49
+
34
50
  ## Contents
35
51
 
36
52
  - [Installation](#installation)
37
53
  - [Quick start](#quick-start)
38
54
  - [Authentication and saved sessions](#authentication-and-saved-sessions)
39
55
  - [Diary, homework, and marks](#diary-homework-and-marks)
56
+ - [Caching, changes, and statistics](#caching-changes-and-statistics)
57
+ - [Async applications](#async-applications)
40
58
  - [Excel reports](#excel-reports)
41
59
  - [Teachers and classmates](#teachers-and-classmates)
42
60
  - [User profiles](#user-profiles)
@@ -52,7 +70,25 @@ and GitHub release checks.
52
70
 
53
71
  ## Installation
54
72
 
55
- Requires **Python 3.10+**. From a checkout or downloaded copy of this repository:
73
+ Requires **Python 3.10+**. Install from PyPI:
74
+
75
+ ```sh
76
+ pip install nit-tools
77
+ python -m playwright install chromium
78
+ ```
79
+
80
+ Upgrade an existing installation:
81
+
82
+ ```sh
83
+ pip install --upgrade nit-tools
84
+ ```
85
+
86
+ Version **0.2.0** adds caching, change tracking, grade statistics, and the async
87
+ client. Existing synchronous methods remain available. Diary reads now reuse
88
+ responses for 60 seconds by default; use `refresh=True` for an immediate update,
89
+ or `cache_ttl=0` to preserve request-on-every-read behavior.
90
+
91
+ Alternatively, install from a checkout or downloaded copy of this repository:
56
92
 
57
93
  ```sh
58
94
  python -m venv .venv
@@ -68,8 +104,7 @@ library locally.
68
104
  Playwright authentication is always included. Installing the Python package
69
105
  does not install its Chromium browser; the separate Playwright command above
70
106
  is required for fresh login. Reading an existing saved session does not launch
71
- a browser. This documentation does not assume that a public PyPI package has
72
- already been published.
107
+ a browser.
73
108
 
74
109
  ## Quick start
75
110
 
@@ -203,7 +238,7 @@ without attachments. `get_marks()` returns **lessons containing mark records**,
203
238
  including attendance-only records. `mark.point` remains a string such as `"10"`
204
239
  or `""`; `mark.absence` remains the API code, including zero.
205
240
 
206
- Every client helper fetches data. To reuse a fetched day without another request,
241
+ Diary helpers reuse cached responses for 60 seconds by default. To filter an already fetched day,
207
242
  call `day.get_lessons()`, `day.get_homework()`, or `day.get_marks()` instead.
208
243
 
209
244
  ### A period
@@ -225,6 +260,64 @@ For the original response, call `get_diary(datetime.date(...))`. `get_days()`
225
260
  returns every day from a single response; neither method assumes a fixed week
226
261
  length. Modeled days, lessons, and marks expose `.raw` for additional API fields.
227
262
 
263
+ ## Caching, changes, and statistics
264
+
265
+ Diary responses are cached **in memory**, per user, school, and date, for
266
+ 60 seconds. Returned data is copied so local edits cannot corrupt the cache.
267
+ Set `cache_ttl=0` on `NITClient.connect()` or the constructor to disable caching.
268
+ Errors are never cached; reauthentication clears cached responses.
269
+
270
+ ```python
271
+ day = client.get_day("2026-11-30")
272
+ fresh_day = client.get_day("2026-11-30", refresh=True)
273
+ client.clear_cache()
274
+
275
+ # First call establishes a baseline; subsequent calls return differences.
276
+ client.get_changes("2026-11-30")
277
+ # Poll again later, for example from your application's scheduler.
278
+ for change in client.get_changes("2026-11-30"):
279
+ print(change.subject, change.kind, change.action, change.before, change.after)
280
+
281
+ for stats in client.get_statistics("2026-11-01", "2026-11-30"):
282
+ print(stats.subject, stats.count, stats.average, stats.change)
283
+ ```
284
+
285
+ `get_changes()` always refreshes. It reports added, updated, and removed
286
+ homework, mark records, and attachments. Renewed signed attachment URLs are
287
+ ignored. Failed requests and omitted dates preserve the previous baseline.
288
+ Snapshots last only for this client instance; they are not saved to disk.
289
+ Lessons are matched by number and subject; moving a lesson appears as removals
290
+ and additions. Marks without IDs are matched by their position.
291
+
292
+ Statistics include grade count, numeric count, average, minimum, maximum, and
293
+ averages for the two calendar halves of the requested period. `change` is the
294
+ second-half average minus the first-half average, or `None` when either half
295
+ has no numeric grades. Attendance-only records are excluded; text grades count
296
+ but do not affect averages. These are unweighted descriptive statistics.
297
+
298
+ ## Async applications
299
+
300
+ ```python
301
+ from nit_tools import AsyncNITClient
302
+
303
+ async def read_diary(email, password):
304
+ async with await AsyncNITClient.connect(
305
+ email=email, password=password, require_class_id=True,
306
+ ) as client:
307
+ day = await client.get_day("2026-11-30")
308
+ teachers = await client.my_class().get_teachers()
309
+ return day, teachers
310
+ ```
311
+
312
+ Client methods are awaited, including exports, downloads, statistics, and change
313
+ tracking. `my_class()` returns a proxy immediately; await its methods.
314
+ `from_auth()` and the token constructor also work without awaiting creation.
315
+ Each client uses one worker thread and serializes calls, including requests
316
+ whose caller was cancelled. Cancellation does not interrupt an in-flight HTTP
317
+ request or browser login. Use an async context manager or `await client.aclose()`
318
+ to wait for pending work and release the worker. This is a threaded async
319
+ adapter around the Requests client, not a separate HTTP transport.
320
+
228
321
  ## Excel reports
229
322
 
230
323
  ### Grades: `summary` and `detailed`
@@ -434,9 +527,8 @@ Avoid sharing `.raw` contents or generated reports in public diagnostics.
434
527
  They do not certify live service availability, pagination behavior, or all
435
528
  account configurations. Period results reflect records returned by the diary;
436
529
  they are not a completeness guarantee for every official journal column.
437
- - **Execution:** the client is synchronous. Call it from an appropriate worker
438
- when integrating with an async server; Playwright's synchronous login cannot
439
- run inside an active asyncio event loop on the same thread.
530
+ - **Execution:** `NITClient` is synchronous. Use `AsyncNITClient` in an async
531
+ application; it moves blocking operations and browser login into a worker.
440
532
 
441
533
  ## Development
442
534
 
@@ -332,3 +332,50 @@ Argument errors and ambiguous class-teacher selection use `ValueError`.
332
332
  Pagination inconsistency uses `RuntimeError`. Filesystem failures propagate
333
333
  as `OSError` subclasses. Permission failures are not automatically treated as
334
334
  expired tokens. No retry loop is installed for 403, 429, or 5xx errors.
335
+
336
+
337
+ ## Diary cache and change tracking
338
+
339
+ `NITClient(..., cache_ttl=60)` and `NITClient.connect(..., cache_ttl=60)`
340
+ configure an in-memory diary cache in seconds. Zero disables it; negative and
341
+ non-finite values are rejected. `get_diary(day, refresh=False)`,
342
+ `get_days(day, refresh=False)`, and `get_day(day, refresh=False)` accept
343
+ `refresh=True` to bypass it. `clear_cache()` clears responses, not snapshots.
344
+ Multi-day responses seed the cache for each returned date.
345
+
346
+ `get_changes(day) -> list[DiaryChange]` fetches fresh data and compares it with
347
+ its last successful in-memory snapshot for that user, school, and date.
348
+ The first call returns `[]`. Errors propagate; omitted dates do not reset the
349
+ baseline. `DiaryChange` exposes `date`, `subject`, `lesson_number`, `kind`
350
+ (`homework`, `marks`, `attachments`), `action` (`added`, `updated`, `removed`),
351
+ `before`, and `after`. Attachment values are filenames; refreshed signed URLs
352
+ are ignored. Snapshots are not persisted across client instances.
353
+
354
+ ## Grade statistics
355
+
356
+ `get_statistics(start, end, subject=None, *, request_delay=0.5)` returns
357
+ `list[GradeStatistics]`, sorted by subject. Inclusive dates and subject filtering
358
+ follow `get_marks_between()`. Each result exposes `subject`, `count`,
359
+ `numeric_count`, `average`, `minimum`, `maximum`, `first_half_average`,
360
+ `second_half_average`, and `change`. Counts exclude attendance-only entries;
361
+ text grades contribute only to `count`. Only finite numeric values affect
362
+ statistics. Empty numeric groups return `None` for numeric summaries.
363
+ The first half ends at `start + (end - start) // 2`; `change` is the second-half
364
+ mean minus the first-half mean, or `None` if either is missing. No grades yield
365
+ an empty list. These are unweighted means, not official grades.
366
+
367
+ ## AsyncNITClient
368
+
369
+ `AsyncNITClient` accepts the same token constructor arguments as `NITClient`.
370
+ `AsyncNITClient.from_auth(auth, **kwargs)` returns an instance synchronously;
371
+ `await AsyncNITClient.connect(...)` performs login in a worker.
372
+ Await public client methods, for example `await client.get_day(day)` and
373
+ `await client.export_marks(start, end)`. Read identity attributes normally.
374
+ `client.my_class(class_id=None)` returns a proxy with awaitable methods.
375
+
376
+ Calls use a single worker per client, preserving serialization of authentication,
377
+ cache, and snapshot changes. Cancellation cannot terminate blocking work;
378
+ subsequent calls remain queued behind that work. `async with client` and
379
+ `await client.aclose()` wait for queued work and close the worker. Calls after
380
+ closure raise `RuntimeError`. This adapter uses Requests and the existing sync
381
+ Playwright implementation in a worker; it adds no HTTP dependency.
@@ -17,6 +17,31 @@ from pathlib import Path
17
17
  from nit_tools import AuthResult, NITClient, Teacher, login
18
18
 
19
19
 
20
+ def inspect_diary(client: NITClient, day: date | str) -> None:
21
+ """Read a cached day, establish a baseline, and poll for later changes."""
22
+ print(client.get_day(day))
23
+ client.get_changes(day)
24
+ # Call again later in your application's polling schedule.
25
+ for change in client.get_changes(day):
26
+ print(change.subject, change.kind, change.action)
27
+
28
+
29
+ def grade_statistics(client: NITClient, start: date | str, end: date | str) -> None:
30
+ """Print descriptive grade statistics for an inclusive period."""
31
+ for stats in client.get_statistics(start, end):
32
+ print(stats.subject, stats.count, stats.average, stats.change)
33
+
34
+
35
+ async def async_diary(day: date | str):
36
+ """Read a diary without blocking the application's event loop."""
37
+ from nit_tools import AsyncNITClient
38
+
39
+ async with await AsyncNITClient.connect(
40
+ email=os.environ.get("NIT_EMAIL"), password=os.environ.get("NIT_PASSWORD"),
41
+ ) as client:
42
+ return await client.get_day(day)
43
+
44
+
20
45
  def diary_with_token(day: date) -> dict:
21
46
  """Fetch the diary using an existing access token."""
22
47
  client = NITClient(
@@ -1,3 +1,5 @@
1
+ from .async_client import AsyncNITClient
2
+ from .insights import DiaryChange, GradeStatistics
1
3
  from .client import NITClient, NITError
2
4
  from .auth import AuthResult, LoginError, auto_auth, load_auth, login, save_auth
3
5
  from .models import Attachment, DiaryDay, Lesson, Mark, MarkRecord
@@ -8,7 +10,7 @@ from .errors import (
8
10
  NotFoundError, RateLimitError, ServerError,
9
11
  )
10
12
 
11
- __all__ = ["NITClient", "NITError", "AuthResult", "LoginError", "login", "auto_auth", "load_auth", "save_auth",
13
+ __all__ = ["AsyncNITClient", "DiaryChange", "GradeStatistics", "NITClient", "NITError", "AuthResult", "LoginError", "login", "auto_auth", "load_auth", "save_auth",
12
14
  "Attachment", "DiaryDay", "Lesson", "Mark", "MarkRecord", "ClassReference", "MyClass", "Teacher", "Student",
13
15
  "UserProfile", "UserRelation", "UserSchool", "AuthenticationError", "AccessDeniedError",
14
16
  "NotFoundError", "RateLimitError", "ServerError", "NetworkError", "InvalidResponseError"]
@@ -0,0 +1,86 @@
1
+ """Async access to the synchronous client through a serialized worker thread."""
2
+
3
+ import asyncio
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from functools import partial
6
+
7
+ from .client import NITClient
8
+
9
+
10
+ class _AsyncProxy:
11
+ def __init__(self, owner, target):
12
+ self._owner = owner
13
+ self._target = target
14
+
15
+ def __getattr__(self, name):
16
+ if name.startswith('_'):
17
+ raise AttributeError(name)
18
+ value = getattr(self._target, name)
19
+ if not callable(value):
20
+ return value
21
+
22
+ async def call(*args, **kwargs):
23
+ return await self._owner._run(value, *args, **kwargs)
24
+ return call
25
+
26
+
27
+ class AsyncNITClient:
28
+ """Await client operations without blocking an application's event loop.
29
+
30
+ Calls on one client run sequentially, including after caller cancellation.
31
+ Use separate clients for independent accounts. Close with an async context
32
+ manager or await aclose() to release the worker thread.
33
+ """
34
+
35
+ def __init__(self, token: str, school_id: str | int, user_id: str, **kwargs):
36
+ self._initialize(NITClient(token, school_id, user_id, **kwargs))
37
+
38
+ def _initialize(self, client):
39
+ self._client = client
40
+ self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix='nit-tools')
41
+ self._closed = False
42
+
43
+ @classmethod
44
+ def from_auth(cls, auth, **kwargs):
45
+ result = cls.__new__(cls)
46
+ result._initialize(NITClient.from_auth(auth, **kwargs))
47
+ return result
48
+
49
+ @classmethod
50
+ async def connect(cls, *args, **kwargs):
51
+ result = cls.__new__(cls)
52
+ # Run browser login in the same worker used by later reauthentication.
53
+ result._initialize(None)
54
+ try:
55
+ result._client = await result._run(NITClient.connect, *args, **kwargs)
56
+ except BaseException:
57
+ await result.aclose()
58
+ raise
59
+ return result
60
+
61
+ async def _run(self, function, *args, **kwargs):
62
+ if self._closed:
63
+ raise RuntimeError('AsyncNITClient is closed')
64
+ loop = asyncio.get_running_loop()
65
+ return await loop.run_in_executor(self._executor, partial(function, *args, **kwargs))
66
+
67
+ def __getattr__(self, name):
68
+ return getattr(_AsyncProxy(self, self._client), name)
69
+
70
+ def my_class(self, class_id=None):
71
+ """Return a class proxy whose methods can be awaited."""
72
+ return _AsyncProxy(self, self._client.my_class(class_id))
73
+
74
+ async def aclose(self):
75
+ """Wait for pending work and release the serialized worker."""
76
+ if not self._closed:
77
+ self._closed = True
78
+ await asyncio.to_thread(self._executor.shutdown, wait=True)
79
+
80
+ async def __aenter__(self):
81
+ if self._closed:
82
+ raise RuntimeError('AsyncNITClient is closed')
83
+ return self
84
+
85
+ async def __aexit__(self, *exc):
86
+ await self.aclose()