glimsy 0.1.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 (48) hide show
  1. glimsy-0.1.0/LICENSE +202 -0
  2. glimsy-0.1.0/PKG-INFO +231 -0
  3. glimsy-0.1.0/README.md +204 -0
  4. glimsy-0.1.0/pyproject.toml +96 -0
  5. glimsy-0.1.0/src/glimsy/__init__.py +90 -0
  6. glimsy-0.1.0/src/glimsy/_api/__init__.py +1 -0
  7. glimsy-0.1.0/src/glimsy/_api/calls.py +235 -0
  8. glimsy-0.1.0/src/glimsy/_api/change_calls.py +37 -0
  9. glimsy-0.1.0/src/glimsy/_api/media_files.py +84 -0
  10. glimsy-0.1.0/src/glimsy/_api/parse.py +175 -0
  11. glimsy-0.1.0/src/glimsy/_auth/__init__.py +6 -0
  12. glimsy-0.1.0/src/glimsy/_auth/api_key.py +54 -0
  13. glimsy-0.1.0/src/glimsy/_auth/sources.py +63 -0
  14. glimsy-0.1.0/src/glimsy/_client.py +213 -0
  15. glimsy-0.1.0/src/glimsy/_error_mapping.py +168 -0
  16. glimsy-0.1.0/src/glimsy/_transport/__init__.py +17 -0
  17. glimsy-0.1.0/src/glimsy/_transport/async_transport.py +113 -0
  18. glimsy-0.1.0/src/glimsy/_transport/base_url.py +64 -0
  19. glimsy-0.1.0/src/glimsy/_transport/core.py +112 -0
  20. glimsy-0.1.0/src/glimsy/_transport/cycle.py +77 -0
  21. glimsy-0.1.0/src/glimsy/_transport/rate_limit.py +85 -0
  22. glimsy-0.1.0/src/glimsy/_transport/retry.py +115 -0
  23. glimsy-0.1.0/src/glimsy/_transport/settings.py +74 -0
  24. glimsy-0.1.0/src/glimsy/_transport/sync_transport.py +112 -0
  25. glimsy-0.1.0/src/glimsy/_transport/throttle.py +64 -0
  26. glimsy-0.1.0/src/glimsy/errors.py +212 -0
  27. glimsy-0.1.0/src/glimsy/local/__init__.py +1 -0
  28. glimsy-0.1.0/src/glimsy/local/hebrew.py +35 -0
  29. glimsy-0.1.0/src/glimsy/local/html_fields.py +91 -0
  30. glimsy-0.1.0/src/glimsy/local/query/__init__.py +15 -0
  31. glimsy-0.1.0/src/glimsy/local/query/fields.py +61 -0
  32. glimsy-0.1.0/src/glimsy/local/query/lookups.py +95 -0
  33. glimsy-0.1.0/src/glimsy/local/query/q.py +78 -0
  34. glimsy-0.1.0/src/glimsy/local/query/values.py +29 -0
  35. glimsy-0.1.0/src/glimsy/local/read_only_sql.py +43 -0
  36. glimsy-0.1.0/src/glimsy/local/schema.py +88 -0
  37. glimsy-0.1.0/src/glimsy/local/sqlite_functions.py +64 -0
  38. glimsy-0.1.0/src/glimsy/local/store.py +133 -0
  39. glimsy-0.1.0/src/glimsy/models/__init__.py +31 -0
  40. glimsy-0.1.0/src/glimsy/models/card.py +106 -0
  41. glimsy-0.1.0/src/glimsy/models/changes.py +81 -0
  42. glimsy-0.1.0/src/glimsy/models/inputs.py +48 -0
  43. glimsy-0.1.0/src/glimsy/models/results.py +146 -0
  44. glimsy-0.1.0/src/glimsy/py.typed +0 -0
  45. glimsy-0.1.0/src/glimsy/resources/__init__.py +16 -0
  46. glimsy-0.1.0/src/glimsy/resources/aio.py +262 -0
  47. glimsy-0.1.0/src/glimsy/resources/changes.py +113 -0
  48. glimsy-0.1.0/src/glimsy/resources/sync.py +259 -0
glimsy-0.1.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
glimsy-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,231 @@
1
+ Metadata-Version: 2.4
2
+ Name: glimsy
3
+ Version: 0.1.0
4
+ Summary: Official Python library for managing your own Glimsy flashcards through the Glimsy API.
5
+ Keywords: glimsy,flashcards,spaced-repetition,api,sdk
6
+ Author: Glimsy sp. z o.o.
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Programming Language :: Python :: 3.14
18
+ Classifier: Topic :: Education
19
+ Classifier: Typing :: Typed
20
+ Requires-Dist: httpx>=0.27,<1
21
+ Requires-Dist: pydantic>=2.7,<3
22
+ Requires-Dist: keyring>=25 ; extra == 'keyring'
23
+ Requires-Python: >=3.11
24
+ Project-URL: Homepage, https://glimsy.app
25
+ Provides-Extra: keyring
26
+ Description-Content-Type: text/markdown
27
+
28
+ # glimsy
29
+
30
+ The official Python library for managing your own [Glimsy](https://glimsy.app) flashcards through the
31
+ Glimsy API: create decks and cards, replace card content (text, images, audio), find copies of cards you
32
+ already have, and upload media. The library batches large jobs, walks through pages, keeps to the
33
+ request limits and retries temporary failures by itself. Python ≥ 3.11.
34
+
35
+ > **Status:** beta (0.1.x). The public API is stable enough to build on; small changes are still
36
+ > possible before 1.0 and are listed in the changelog.
37
+
38
+ ## Getting an API key
39
+
40
+ You create your key yourself, in the Glimsy web app:
41
+
42
+ 1. Sign in at [glimsy.app](https://glimsy.app) and open **Settings → API key**.
43
+ 2. Click **Generate key**. The key is shown **once**: copy it right away, it cannot be displayed again.
44
+ 3. Store it in your system keychain (recommended):
45
+
46
+ ```bash
47
+ pip install "glimsy[keyring]"
48
+ keyring set glimsy api-key # paste the key when asked
49
+ ```
50
+
51
+ What to know about keys:
52
+
53
+ - A key is valid for **90 days**. Settings shows whether it is active and when it expires.
54
+ - You have **one active key**. Generating a new one replaces (deactivates) the old one.
55
+ - You can generate at most **3 keys per day** (the day counts in Polish time); after that the web app
56
+ says the daily limit is reached. Deactivating a key does not give a generation back.
57
+ - **Deactivate** a key in the same place when you no longer need it or think it leaked.
58
+ - A key acts only on your own data, and never on your learning progress.
59
+
60
+ The library looks for the key in this order: the `api_key=` argument, the `GLIMSY_API_KEY` environment
61
+ variable, the system keychain. Never commit a key to a repository.
62
+
63
+ ## Install
64
+
65
+ ```bash
66
+ pip install "glimsy[keyring]" # or: pip install glimsy (without keychain support)
67
+ ```
68
+
69
+ ## Quick start
70
+
71
+ ```python
72
+ import glimsy
73
+
74
+ with glimsy.Client() as client:
75
+ deck = client.decks.get("Hebrew")
76
+
77
+ card = client.cards.create(deck, front="שָׁלוֹם", back="hello", direction="two_way")
78
+
79
+ image = client.media.upload("peace.png") # returns a reference for the card HTML
80
+ if client.me().can_edit:
81
+ client.cards.update(card, back=f'hello <img src="{image.src}">')
82
+
83
+ for found in client.cards.match([("שלום", "hello")], deck_ids=[deck]):
84
+ print(found.status, found.best)
85
+ ```
86
+
87
+ `glimsy.AsyncClient` offers the same methods with `await`:
88
+
89
+ ```python
90
+ async with glimsy.AsyncClient() as client:
91
+ decks = await client.decks.list()
92
+ ```
93
+
94
+ ## What you can and cannot do
95
+
96
+ | You can | You cannot (no such function or endpoint) |
97
+ |---|---|
98
+ | See who you are: `client.me()` (account, environment, whether editing is allowed) | Delete anything (cards, decks, media, account) |
99
+ | Decks: `list`, `get` (by name or id), `create`, `rename` | Touch learning progress (reviews, FSRS state, due dates, history, statistics) |
100
+ | Deck card CSS: `decks.get_theme`, `decks.set_css`, `decks.clear_theme` | Change other deck settings (colour, icon, sharing) or pick the app's ready-made templates |
101
+ | Cards: `list` (all pages), `create`, `create_many`, `update`, `update_many` | Read or change another user's data |
102
+ | Find copies: `cards.match` (Hebrew niqqud and final letters ignored), `cards.search` | Create API keys from code (you create your key in the web app) |
103
+ | Media: `media.missing`, `media.upload`, `media.ensure` (uploads only what is missing) | |
104
+ | Undo edits of the last 7 days: `changes.list`, `changes.restore`, `changes.restore_batch` | |
105
+
106
+ Replacing the content of existing cards and changing deck CSS can be switched off on a server;
107
+ `client.me().can_edit` tells you whether the server you talk to allows it. Undo works either way.
108
+
109
+ ## Undoing changes (7 days)
110
+
111
+ Before every card edit and every deck CSS change made through the API, the server keeps the previous
112
+ content for 7 days. Learning progress is never copied nor changed, by an edit or by an undo.
113
+
114
+ ```python
115
+ results = client.cards.update_many(edits)
116
+ for batch_id in {r.undo_batch_id for r in results if r.undo_batch_id}:
117
+ client.changes.restore_batch(batch_id) # one id per request of up to 100 edits
118
+
119
+ theme = client.decks.set_css(deck, "& .giz-card { font-size: 1.4em; }")
120
+ client.changes.restore_batch(theme.undo_batch_id) # put the previous stylesheet back
121
+
122
+ for change in client.changes.list(): # newest first: kind, card, previous content
123
+ print(change.created_at, change.kind, change.card_id, change.before)
124
+ client.changes.restore(change) # write back one change
125
+ ```
126
+
127
+ A restore is kept for undo too (`restore(...).undo_batch_id`). A change whose card or deck no longer
128
+ exists cannot be restored (`NotFoundError`, or `ok=False` for that change in `restore_batch`).
129
+
130
+ A deck's CSS (at most 6000 characters) can style each card by its study state — new, again today, due
131
+ from earlier days — with `& .giz-card[data-giz-card="new" | "today" | "review"]`. The full reference is
132
+ the "?" window of the deck CSS editor in the Glimsy app.
133
+
134
+ ## How the library behaves
135
+
136
+ You call one method; the library takes care of the API's rules.
137
+
138
+ - **Batching.** `create_many` and `update_many` send at most 100 cards per request, `cards.match` at
139
+ most 200 pairs and `media.missing` at most 200 hashes. Any number of items is split into such requests
140
+ and the results are merged back into **one result per item, in the order you passed them**
141
+ (`result.index` is the position in your input). Each `ItemResult` says `ok` with the card, or why that
142
+ item was refused; one refused item does not stop the others.
143
+ - **Resuming a large creation.** If a request in the middle of `create_many` fails, you get
144
+ `PartialBatchError` with the results that were applied (`error.completed`). Call `create_many` again
145
+ with the same items and `idempotency_key=error.idempotency_key`: parts already created are returned,
146
+ not created twice.
147
+ - **Retrying a failed creation.** When a request of `create_many`, `cards.create` or `decks.create`
148
+ fails (`NetworkError`, `ServerError`, `PartialBatchError`, ...), the error carries the key the request
149
+ was sent with, in
150
+ `error.idempotency_key`, even when nothing seems to have been created: the server may have saved the
151
+ cards and only the answer got lost. Repeat with that key instead of a fresh one, and nothing is
152
+ created twice:
153
+
154
+ ```python
155
+ try:
156
+ results = client.cards.create_many(deck, new)
157
+ except (glimsy.NetworkError, glimsy.ServerError) as error:
158
+ results = client.cards.create_many(deck, new, idempotency_key=error.idempotency_key)
159
+ ```
160
+
161
+ `decks.create` takes `idempotency_key=` the same way. `cards.create` has no such argument: repeat it
162
+ as `client.cards.create_many(deck, [glimsy.NewCard(front, back, direction)],
163
+ idempotency_key=error.idempotency_key)`.
164
+ To retry later (for example on the next run of a script), choose and store your own key and pass it
165
+ every time.
166
+ - **Pages.** `cards.list(deck)` is an iterator over every card of the deck; it fetches pages of 500 cards
167
+ (`page_size=` from 1 to 500) only as you iterate.
168
+ - **Request limit.** A key may send 60 requests per minute. The client keeps to that by itself: it never
169
+ starts more than `requests_per_minute` requests in any 61 seconds (one second of margin over the
170
+ server's minute) and makes the next call wait instead.
171
+ The limiter is shared by all threads and asyncio tasks that use the same client, so share one client
172
+ in a program. Change or switch it off with `glimsy.Client(requests_per_minute=120)` or
173
+ `glimsy.Client(requests_per_minute=None)`. Separate processes using one key are not coordinated.
174
+ The server's `RateLimit` headers are honoured as well.
175
+ - **Retries.** Temporary failures are repeated automatically: a lost connection or timeout, HTTP 502,
176
+ 503 and 504, and HTTP 429 (too many requests). The library waits as long as the server's `Retry-After`
177
+ asks, plus a small random share that grows with each attempt (exponential backoff with jitter), so
178
+ many programs refused together do not come back in the same second. The time limit counts from the
179
+ first send, so waiting in the limiter's queue does not use it up. At most 4 attempts and 90 seconds
180
+ per call by default; a server wait longer than 60 seconds (for example the daily budget) is raised
181
+ at once instead of blocking. Tune it with `glimsy.Client(retry=glimsy.RetryPolicy(...))`;
182
+ `RetryPolicy(max_attempts=1)` turns retries off.
183
+ - **Retries never write twice.** Reads, searches and the writes the server deduplicates (creating a deck
184
+ or cards, which carry one `Idempotency-Key` for all attempts) are repeated after any temporary failure.
185
+ Other writes — editing cards, renaming a deck, deck CSS, media upload — are repeated only when the
186
+ server refused them before doing anything (HTTP 429, or 503 `rate_limiter_unavailable`). After a lost
187
+ connection or a 502/504 they raise `NetworkError` / `ServerError`, because the first attempt may
188
+ already have been applied; check the state (for example `cards.list`) before trying again.
189
+ - **Daily budget.** Each key also has a daily budget of 10 000 cost units: 1 per plain request, 10 for a
190
+ search, a match or an upload, plus 1 per batch item; a match or search over a large collection costs
191
+ a little more (about 1 unit per 100 cards it reads). When the budget is used up you get
192
+ `DailyLimitError`.
193
+
194
+ ## Errors
195
+
196
+ Every error is a subclass of `glimsy.GlimsyError`, and `str(error)` says in plain words what happened
197
+ and what to do. API errors also carry `status`, a stable `code`, the server's `detail` and a
198
+ `request_id` (quote it when you report a problem). An error from creating cards or a deck also
199
+ carries `idempotency_key`, the key to repeat it with safely (see "Retrying a failed creation").
200
+
201
+ | Exception | When |
202
+ |---|---|
203
+ | `MissingApiKeyError`, `InvalidApiKeyError` | no key found, or the key is not in Glimsy's format (copied incompletely) |
204
+ | `KeyExpiredError` | the key is older than 90 days: generate a new one in Settings → API key |
205
+ | `KeyRevokedError` | the key was deactivated (by you, by a newer key, or by Glimsy) |
206
+ | `AuthenticationError` | any refused key (the two above are subclasses), e.g. a key for another environment |
207
+ | `ApiBlockedError` | Glimsy has blocked API access for this account; contact Glimsy support |
208
+ | `EditsUnavailableError` | changing existing cards or deck CSS is switched off on this server (`me().can_edit` is false) |
209
+ | `PlanLimitError` | your plan does not allow more decks or cards, or audio |
210
+ | `PermissionDeniedError` | any other refusal of a valid key (the three above are subclasses) |
211
+ | `NotFoundError` | the deck or card does not exist or is not yours (the server does not tell which) |
212
+ | `ValidationError` | the request content was refused, e.g. card HTML with forbidden markup or a file too large |
213
+ | `RateLimitError` | too many requests per minute even after the automatic retries; `retry_after` says how long to wait |
214
+ | `DailyLimitError` | the key's daily budget is used up (a `RateLimitError`; `retry_after` says when it renews) |
215
+ | `ServerError`, `NetworkError` | Glimsy failed or could not be reached even after the automatic retries |
216
+ | `PartialBatchError` | a large batch failed half-way; it carries the results that did succeed |
217
+
218
+ ```python
219
+ try:
220
+ client.cards.update_many(edits)
221
+ except glimsy.KeyExpiredError:
222
+ print("Generate a new key in the Glimsy web app: Settings → API key")
223
+ except glimsy.EditsUnavailableError:
224
+ print("Editing is not available on this server yet")
225
+ except glimsy.RateLimitError as error:
226
+ print(f"Slow down, try again in {error.retry_after} s")
227
+ ```
228
+
229
+ ## License
230
+
231
+ Apache-2.0.
glimsy-0.1.0/README.md ADDED
@@ -0,0 +1,204 @@
1
+ # glimsy
2
+
3
+ The official Python library for managing your own [Glimsy](https://glimsy.app) flashcards through the
4
+ Glimsy API: create decks and cards, replace card content (text, images, audio), find copies of cards you
5
+ already have, and upload media. The library batches large jobs, walks through pages, keeps to the
6
+ request limits and retries temporary failures by itself. Python ≥ 3.11.
7
+
8
+ > **Status:** beta (0.1.x). The public API is stable enough to build on; small changes are still
9
+ > possible before 1.0 and are listed in the changelog.
10
+
11
+ ## Getting an API key
12
+
13
+ You create your key yourself, in the Glimsy web app:
14
+
15
+ 1. Sign in at [glimsy.app](https://glimsy.app) and open **Settings → API key**.
16
+ 2. Click **Generate key**. The key is shown **once**: copy it right away, it cannot be displayed again.
17
+ 3. Store it in your system keychain (recommended):
18
+
19
+ ```bash
20
+ pip install "glimsy[keyring]"
21
+ keyring set glimsy api-key # paste the key when asked
22
+ ```
23
+
24
+ What to know about keys:
25
+
26
+ - A key is valid for **90 days**. Settings shows whether it is active and when it expires.
27
+ - You have **one active key**. Generating a new one replaces (deactivates) the old one.
28
+ - You can generate at most **3 keys per day** (the day counts in Polish time); after that the web app
29
+ says the daily limit is reached. Deactivating a key does not give a generation back.
30
+ - **Deactivate** a key in the same place when you no longer need it or think it leaked.
31
+ - A key acts only on your own data, and never on your learning progress.
32
+
33
+ The library looks for the key in this order: the `api_key=` argument, the `GLIMSY_API_KEY` environment
34
+ variable, the system keychain. Never commit a key to a repository.
35
+
36
+ ## Install
37
+
38
+ ```bash
39
+ pip install "glimsy[keyring]" # or: pip install glimsy (without keychain support)
40
+ ```
41
+
42
+ ## Quick start
43
+
44
+ ```python
45
+ import glimsy
46
+
47
+ with glimsy.Client() as client:
48
+ deck = client.decks.get("Hebrew")
49
+
50
+ card = client.cards.create(deck, front="שָׁלוֹם", back="hello", direction="two_way")
51
+
52
+ image = client.media.upload("peace.png") # returns a reference for the card HTML
53
+ if client.me().can_edit:
54
+ client.cards.update(card, back=f'hello <img src="{image.src}">')
55
+
56
+ for found in client.cards.match([("שלום", "hello")], deck_ids=[deck]):
57
+ print(found.status, found.best)
58
+ ```
59
+
60
+ `glimsy.AsyncClient` offers the same methods with `await`:
61
+
62
+ ```python
63
+ async with glimsy.AsyncClient() as client:
64
+ decks = await client.decks.list()
65
+ ```
66
+
67
+ ## What you can and cannot do
68
+
69
+ | You can | You cannot (no such function or endpoint) |
70
+ |---|---|
71
+ | See who you are: `client.me()` (account, environment, whether editing is allowed) | Delete anything (cards, decks, media, account) |
72
+ | Decks: `list`, `get` (by name or id), `create`, `rename` | Touch learning progress (reviews, FSRS state, due dates, history, statistics) |
73
+ | Deck card CSS: `decks.get_theme`, `decks.set_css`, `decks.clear_theme` | Change other deck settings (colour, icon, sharing) or pick the app's ready-made templates |
74
+ | Cards: `list` (all pages), `create`, `create_many`, `update`, `update_many` | Read or change another user's data |
75
+ | Find copies: `cards.match` (Hebrew niqqud and final letters ignored), `cards.search` | Create API keys from code (you create your key in the web app) |
76
+ | Media: `media.missing`, `media.upload`, `media.ensure` (uploads only what is missing) | |
77
+ | Undo edits of the last 7 days: `changes.list`, `changes.restore`, `changes.restore_batch` | |
78
+
79
+ Replacing the content of existing cards and changing deck CSS can be switched off on a server;
80
+ `client.me().can_edit` tells you whether the server you talk to allows it. Undo works either way.
81
+
82
+ ## Undoing changes (7 days)
83
+
84
+ Before every card edit and every deck CSS change made through the API, the server keeps the previous
85
+ content for 7 days. Learning progress is never copied nor changed, by an edit or by an undo.
86
+
87
+ ```python
88
+ results = client.cards.update_many(edits)
89
+ for batch_id in {r.undo_batch_id for r in results if r.undo_batch_id}:
90
+ client.changes.restore_batch(batch_id) # one id per request of up to 100 edits
91
+
92
+ theme = client.decks.set_css(deck, "& .giz-card { font-size: 1.4em; }")
93
+ client.changes.restore_batch(theme.undo_batch_id) # put the previous stylesheet back
94
+
95
+ for change in client.changes.list(): # newest first: kind, card, previous content
96
+ print(change.created_at, change.kind, change.card_id, change.before)
97
+ client.changes.restore(change) # write back one change
98
+ ```
99
+
100
+ A restore is kept for undo too (`restore(...).undo_batch_id`). A change whose card or deck no longer
101
+ exists cannot be restored (`NotFoundError`, or `ok=False` for that change in `restore_batch`).
102
+
103
+ A deck's CSS (at most 6000 characters) can style each card by its study state — new, again today, due
104
+ from earlier days — with `& .giz-card[data-giz-card="new" | "today" | "review"]`. The full reference is
105
+ the "?" window of the deck CSS editor in the Glimsy app.
106
+
107
+ ## How the library behaves
108
+
109
+ You call one method; the library takes care of the API's rules.
110
+
111
+ - **Batching.** `create_many` and `update_many` send at most 100 cards per request, `cards.match` at
112
+ most 200 pairs and `media.missing` at most 200 hashes. Any number of items is split into such requests
113
+ and the results are merged back into **one result per item, in the order you passed them**
114
+ (`result.index` is the position in your input). Each `ItemResult` says `ok` with the card, or why that
115
+ item was refused; one refused item does not stop the others.
116
+ - **Resuming a large creation.** If a request in the middle of `create_many` fails, you get
117
+ `PartialBatchError` with the results that were applied (`error.completed`). Call `create_many` again
118
+ with the same items and `idempotency_key=error.idempotency_key`: parts already created are returned,
119
+ not created twice.
120
+ - **Retrying a failed creation.** When a request of `create_many`, `cards.create` or `decks.create`
121
+ fails (`NetworkError`, `ServerError`, `PartialBatchError`, ...), the error carries the key the request
122
+ was sent with, in
123
+ `error.idempotency_key`, even when nothing seems to have been created: the server may have saved the
124
+ cards and only the answer got lost. Repeat with that key instead of a fresh one, and nothing is
125
+ created twice:
126
+
127
+ ```python
128
+ try:
129
+ results = client.cards.create_many(deck, new)
130
+ except (glimsy.NetworkError, glimsy.ServerError) as error:
131
+ results = client.cards.create_many(deck, new, idempotency_key=error.idempotency_key)
132
+ ```
133
+
134
+ `decks.create` takes `idempotency_key=` the same way. `cards.create` has no such argument: repeat it
135
+ as `client.cards.create_many(deck, [glimsy.NewCard(front, back, direction)],
136
+ idempotency_key=error.idempotency_key)`.
137
+ To retry later (for example on the next run of a script), choose and store your own key and pass it
138
+ every time.
139
+ - **Pages.** `cards.list(deck)` is an iterator over every card of the deck; it fetches pages of 500 cards
140
+ (`page_size=` from 1 to 500) only as you iterate.
141
+ - **Request limit.** A key may send 60 requests per minute. The client keeps to that by itself: it never
142
+ starts more than `requests_per_minute` requests in any 61 seconds (one second of margin over the
143
+ server's minute) and makes the next call wait instead.
144
+ The limiter is shared by all threads and asyncio tasks that use the same client, so share one client
145
+ in a program. Change or switch it off with `glimsy.Client(requests_per_minute=120)` or
146
+ `glimsy.Client(requests_per_minute=None)`. Separate processes using one key are not coordinated.
147
+ The server's `RateLimit` headers are honoured as well.
148
+ - **Retries.** Temporary failures are repeated automatically: a lost connection or timeout, HTTP 502,
149
+ 503 and 504, and HTTP 429 (too many requests). The library waits as long as the server's `Retry-After`
150
+ asks, plus a small random share that grows with each attempt (exponential backoff with jitter), so
151
+ many programs refused together do not come back in the same second. The time limit counts from the
152
+ first send, so waiting in the limiter's queue does not use it up. At most 4 attempts and 90 seconds
153
+ per call by default; a server wait longer than 60 seconds (for example the daily budget) is raised
154
+ at once instead of blocking. Tune it with `glimsy.Client(retry=glimsy.RetryPolicy(...))`;
155
+ `RetryPolicy(max_attempts=1)` turns retries off.
156
+ - **Retries never write twice.** Reads, searches and the writes the server deduplicates (creating a deck
157
+ or cards, which carry one `Idempotency-Key` for all attempts) are repeated after any temporary failure.
158
+ Other writes — editing cards, renaming a deck, deck CSS, media upload — are repeated only when the
159
+ server refused them before doing anything (HTTP 429, or 503 `rate_limiter_unavailable`). After a lost
160
+ connection or a 502/504 they raise `NetworkError` / `ServerError`, because the first attempt may
161
+ already have been applied; check the state (for example `cards.list`) before trying again.
162
+ - **Daily budget.** Each key also has a daily budget of 10 000 cost units: 1 per plain request, 10 for a
163
+ search, a match or an upload, plus 1 per batch item; a match or search over a large collection costs
164
+ a little more (about 1 unit per 100 cards it reads). When the budget is used up you get
165
+ `DailyLimitError`.
166
+
167
+ ## Errors
168
+
169
+ Every error is a subclass of `glimsy.GlimsyError`, and `str(error)` says in plain words what happened
170
+ and what to do. API errors also carry `status`, a stable `code`, the server's `detail` and a
171
+ `request_id` (quote it when you report a problem). An error from creating cards or a deck also
172
+ carries `idempotency_key`, the key to repeat it with safely (see "Retrying a failed creation").
173
+
174
+ | Exception | When |
175
+ |---|---|
176
+ | `MissingApiKeyError`, `InvalidApiKeyError` | no key found, or the key is not in Glimsy's format (copied incompletely) |
177
+ | `KeyExpiredError` | the key is older than 90 days: generate a new one in Settings → API key |
178
+ | `KeyRevokedError` | the key was deactivated (by you, by a newer key, or by Glimsy) |
179
+ | `AuthenticationError` | any refused key (the two above are subclasses), e.g. a key for another environment |
180
+ | `ApiBlockedError` | Glimsy has blocked API access for this account; contact Glimsy support |
181
+ | `EditsUnavailableError` | changing existing cards or deck CSS is switched off on this server (`me().can_edit` is false) |
182
+ | `PlanLimitError` | your plan does not allow more decks or cards, or audio |
183
+ | `PermissionDeniedError` | any other refusal of a valid key (the three above are subclasses) |
184
+ | `NotFoundError` | the deck or card does not exist or is not yours (the server does not tell which) |
185
+ | `ValidationError` | the request content was refused, e.g. card HTML with forbidden markup or a file too large |
186
+ | `RateLimitError` | too many requests per minute even after the automatic retries; `retry_after` says how long to wait |
187
+ | `DailyLimitError` | the key's daily budget is used up (a `RateLimitError`; `retry_after` says when it renews) |
188
+ | `ServerError`, `NetworkError` | Glimsy failed or could not be reached even after the automatic retries |
189
+ | `PartialBatchError` | a large batch failed half-way; it carries the results that did succeed |
190
+
191
+ ```python
192
+ try:
193
+ client.cards.update_many(edits)
194
+ except glimsy.KeyExpiredError:
195
+ print("Generate a new key in the Glimsy web app: Settings → API key")
196
+ except glimsy.EditsUnavailableError:
197
+ print("Editing is not available on this server yet")
198
+ except glimsy.RateLimitError as error:
199
+ print(f"Slow down, try again in {error.retry_after} s")
200
+ ```
201
+
202
+ ## License
203
+
204
+ Apache-2.0.