Metadata-Version: 2.4
Name: glimsy
Version: 0.2.1
Summary: Official Python library for managing your own Glimsy flashcards through the Glimsy API.
Keywords: glimsy,flashcards,spaced-repetition,api,sdk
Author: Glimsy sp. z o.o.
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Education
Classifier: Typing :: Typed
Requires-Dist: httpx>=0.27,<1
Requires-Dist: pydantic>=2.7,<3
Requires-Dist: keyring>=25 ; extra == 'keyring'
Requires-Python: >=3.11
Project-URL: Homepage, https://glimsy.app
Provides-Extra: keyring
Description-Content-Type: text/markdown

<!-- Generated from docs/pypi/*.md by scripts/build_readme.py. Edit those files, not this one. -->
# glimsy

The official Python library for the [Glimsy](https://glimsy.app) API. Use it to manage your own
flashcards from code: create and organise decks, add and update cards (text, images and audio), find
cards you already have, upload media, delete and restore cards and decks, and undo recent changes.

The library splits large jobs into batches, walks through result pages, stays within the request
limits and retries temporary failures for you. It requires Python 3.11 or later.

> **Status:** beta. The public API is stable enough to build on; small changes are still possible
> before 1.0 and are listed in the changelog.

## Getting an API key

You create your key in the Glimsy web app:

1. Sign in at [app.glimsy.app](https://app.glimsy.app) and open **Settings → API key**.
2. Click **Generate key**. The key is shown **only once**, so copy it right away.
3. Store it in your system keychain (recommended):

   ```bash
   pip install "glimsy[keyring]"
   keyring set glimsy api-key   # paste the key when prompted
   ```

About keys:

- Each account has **one active key**. Generating a new key deactivates the previous one.
- A key is valid for **90 days**. Settings shows whether your key is active and when it expires.
- The number of new keys per day is limited (see "Limits" below). Deactivating a key does not
  restore a generation.
- **Deactivate** a key in the same place when you no longer need it or suspect it has leaked.
- A key gives access only to your own data and never to your learning progress.

The library looks for the key in this order: the `api_key=` argument, the `GLIMSY_API_KEY`
environment variable, then the system keychain. Never commit a key to a repository.

## Installation

```bash
pip install "glimsy[keyring]"   # or: pip install glimsy (without keychain support)
```

## Quick start

```python
import glimsy

with glimsy.Client() as client:
    deck = client.decks.get("Geography")

    card = client.cards.create(deck, front="Capital of France", back="Paris", direction="two_way")

    image = client.media.upload("eiffel-tower.png")  # returns a reference for the card HTML
    if client.me().can_edit:
        client.cards.update(card, back=f'Paris <img src="{image.src}">')

    for found in client.cards.match([("Capital of France", "Paris")], deck_ids=[deck]):
        print(found.status, found.best)
```

`glimsy.AsyncClient` provides the same methods for use with `await`:

```python
async with glimsy.AsyncClient() as client:
    decks = await client.decks.list()
```

## What you can and cannot do

| You can | You cannot (no such method or endpoint) |
|---|---|
| Check your account: `client.me()` (account, environment, whether editing is allowed) | Change learning progress (reviews, scheduling state, due dates, history, statistics) |
| Decks: `list`, `get` (by name or id), `create`, `rename`, `delete` (0.2.0) | Delete permanently (deleted cards and decks go to the trash), or delete media or your account |
| Deck card CSS: `decks.get_theme`, `decks.set_css`, `decks.clear_theme` | Change other deck settings (colour, icon, sharing) or apply the app's built-in templates |
| Cards: `list` (all pages), `create`, `create_many`, `update`, `update_many`, `delete` and `delete_many` (0.2.0) | Read or change another user's data |
| Find existing cards: `cards.match` (exact and near matches, ignoring markup and vowel marks), `cards.search` | Create API keys from code (keys are created in the web app) |
| Media: `media.missing`, `media.upload`, `media.ensure` (uploads only what is missing) | |
| Undo changes and deletions from the last 7 days: `changes.list`, `changes.restore`, `changes.restore_batch` | |

Editing and deleting existing cards and decks, and changing deck CSS, can be disabled on a server; `client.me().can_edit`
tells you whether the server you are connected to allows it. Undo is always available.

## Deleting and restoring cards and decks

Available from version 0.2.0. Deleting is a soft delete: the card or deck is moved to the trash and
can be restored for 7 days.

```python
deleted = client.decks.delete(deck)  # moves the deck and its cards to the trash, returns the Deck
client.changes.restore_batch(deleted.undo_batch_id)  # brings the deck back

card = client.cards.delete(card)     # moves one card to the trash, returns the Card

results = client.cards.delete_many(cards)  # any number of cards, sent in batches of 100
for result in results:
    if not result.ok:
        print(result.index, result.error.code, result.error.detail)
```

`delete_many` returns one `ItemResult` per card, in the order you passed them: either `ok`, or the
reason that card was refused. One refused card does not stop the others. A deck or card that does
not exist or belongs to another user raises `NotFoundError` with the code `not_found`; in
`delete_many`, that card is refused with `not_found`. Where deleting is switched off on the server
(`client.me().can_edit` is false), deleting raises `EditsUnavailableError`. A deck with more than
2000 cards cannot be deleted through the API: `decks.delete` raises `DeckTooLargeError` and nothing is
deleted; delete such a deck in the Glimsy app.

`glimsy.AsyncClient` offers the same methods with `await`.

A deletion is undone the same way as an edit (see "Undoing changes" below). `Deck.undo_batch_id`
(from `decks.delete`) and `ItemResult.undo_batch_id` (from `delete_many`, one id per request of up
to 100 cards) name the request to pass to `client.changes.restore_batch`. Deletions are also listed
by `client.changes.list()` with `kind` `"card_delete"` or `"deck_delete"` (`before` is the card's
`{"front", "back"}` or the deck's `{"name"}`), and `client.changes.restore(change)` restores one.

Right after a deletion, the Glimsy app may still be moving the items to the trash. An undo in that
moment raises `DeletionInProgressError` and restores nothing: call it again in a moment
(`error.retry_after` says how many seconds, when the server says). The library does not repeat it on
its own.

## Undoing changes (7 days)

Before every card edit and every deck CSS change made through the API, the server keeps the previous
content for 7 days; from version 0.2.0 the same applies to deleted cards and decks. Learning progress
is never copied or changed, neither by an edit nor by an undo.

```python
results = client.cards.update_many(edits)
for batch_id in {r.undo_batch_id for r in results if r.undo_batch_id}:
    client.changes.restore_batch(batch_id)  # one id per request of up to 100 edits

theme = client.decks.set_css(deck, "& .giz-card { font-size: 1.4em; }")
client.changes.restore_batch(theme.undo_batch_id)  # restore the previous stylesheet

for change in client.changes.list():  # newest first: kind, card, previous content
    print(change.created_at, change.kind, change.card_id, change.before)
client.changes.restore(change)  # restore a single change
```

A restored edit can itself be undone (`restore(...).undo_batch_id`); a restored deletion has nothing
to undo, so its `undo_batch_id` is `None` (delete the card or deck again instead). A change whose card or deck no longer
exists cannot be restored (`NotFoundError`, or `ok=False` for that change in `restore_batch`).

A deck's CSS (at most 6000 characters) can style each card by its study state (new, answered "Again"
today, or due from earlier days) with `& .giz-card[data-giz-card="new" | "today" | "review"]`. The full
reference is in the "?" window of the deck CSS editor in the Glimsy app.

## How the library behaves

You call one method; the library takes care of the API's rules.

- **Batching.** `create_many`, `update_many` and `delete_many` send at most 100 cards per request,
  `cards.match` at most 200 pairs and `media.missing` at most 200 hashes. Any number of items is split
  into such requests and the results are merged back into **one result per item, in the order you
  passed them** (`result.index` is the position in your input). Each `ItemResult` is either `ok` with
  the card, or says why that item was refused; one refused item does not stop the others.
- **Resuming a large creation.** If a request in the middle of `create_many` fails, you get
  `PartialBatchError` with the results that were applied (`error.completed`). Call `create_many` again
  with the same items and `idempotency_key=error.idempotency_key`: parts already created are returned,
  not created twice.
- **Retrying a failed creation.** When a request of `create_many`, `cards.create` or `decks.create`
  fails (`NetworkError`, `ServerError`, `PartialBatchError`, ...), the error carries the key the request
  was sent with in `error.idempotency_key`, even when nothing seems to have been created: the server
  may have saved the cards and only the response was lost. Retry with that key instead of a new one,
  and nothing is created twice:

  ```python
  try:
      results = client.cards.create_many(deck, new)
  except (glimsy.NetworkError, glimsy.ServerError) as error:
      results = client.cards.create_many(deck, new, idempotency_key=error.idempotency_key)
  ```

  `decks.create` accepts `idempotency_key=` in the same way. `cards.create` has no such argument:
  retry it as `client.cards.create_many(deck, [glimsy.NewCard(front, back, direction)],
  idempotency_key=error.idempotency_key)`. To retry later (for example on the next run of a script),
  choose and store your own key and pass it every time.
- **Pages.** `cards.list(deck)` is an iterator over every card of the deck; it fetches pages of 500
  cards (`page_size=` from 1 to 500) only as you iterate.
- **Request rate.** By default the client does not slow itself down: the per-minute limit depends on
  your plan (see https://glimsy.app/en/api/#limits), so a request over it gets HTTP 429 and the library waits
  as long as the server's `Retry-After` asks (see "Retries"). To pace on your side instead, pass a
  cap, for example `glimsy.Client(requests_per_minute=100)`: the client then never starts more than that many requests
  in any 61 seconds (one second of margin over the server's minute) and makes the next call wait. The
  limiter is shared by all threads and asyncio tasks that use the same client, so share one client
  within a program. Separate processes using one key are not coordinated.
- **Retries.** Temporary failures are retried automatically: a lost connection or timeout, HTTP 502,
  503 and 504, and HTTP 429 (too many requests). The library waits as long as the server's
  `Retry-After` asks, plus a small random share that grows with each attempt (exponential backoff with
  jitter), so many clients refused at the same time do not return in the same second. The time limit
  counts from the first attempt, so waiting in the limiter's queue does not use it up. By default there
  are at most 4 attempts and 90 seconds per call; a server wait longer than 60 seconds (for example an
  exhausted daily budget) is raised at once instead of blocking. Tune this with
  `glimsy.Client(retry=glimsy.RetryPolicy(...))`; `RetryPolicy(max_attempts=1)` disables retries.
- **Retries never write twice.** Reads, searches and the writes the server deduplicates (creating a
  deck or cards, which carry one `Idempotency-Key` for all attempts) are retried after any temporary
  failure. Other writes (editing or deleting cards, renaming or deleting a deck, deck CSS, media
  upload) are retried only when the server refused them before doing anything (HTTP 429, or 503
  `rate_limiter_unavailable`). After a
  lost connection or a 502/504 they raise `NetworkError` / `ServerError`, because the first attempt may
  already have been applied; check the current state (for example with `cards.list`) before trying
  again.

## Limits

Access to the API and its limits (requests per minute and the daily budget of cost units) depend on
your Glimsy plan — see https://glimsy.app/en/api/#limits for current details. An account whose plan does
not include the API gets HTTP 403 `plan_required` (`PlanRequiredError`); the key itself stays valid.

The daily budget runs in a 24-hour window that starts with the key's first request; after it ends,
the next request starts a new window. It is counted per key, not per account.

Other limits:

| Limit | Value |
|---|---|
| Active API keys | 1 per account; generating a new key deactivates the previous one |
| New API keys | 3 per account per calendar day; the day starts at midnight Polish time (Europe/Warsaw) |
| Key validity | 90 days from generation |
| Requests per IP address | 300 per minute, counted before the key is checked (an IPv6 address counts as its /64 network) |
| Invalid keys per IP address | after 20 invalid keys within 10 minutes, the address is blocked for up to 10 minutes |
| Undo | changes and deletions can be restored for 7 days |
| Items per request | 100 cards for create, update and delete; 200 pairs for `cards.match`; 200 hashes for `media.missing` (the library splits larger jobs) |
| Deck CSS | 6000 characters |

### How cost units are counted

| Request | Cost units |
|---|---|
| Reading your account, decks, one page of cards or the change list; creating or renaming a deck; checking media hashes; deleting a deck; restoring one change | 1 |
| Creating, updating or deleting cards, restoring a batch of changes | 1 + 1 per item |
| `cards.match` | 10 + 1 per pair, plus the scan (below) |
| `cards.search` | 10, plus the scan (below) |
| Uploading one media file | 10 |

**The scan.** A match or search pays for the cards it reads: 1 unit for each started 100 cards read,
plus 1 unit for each started 10 000 comparisons (cards read × queries). Searching 250 cards once
costs 10 + 3 + 1 = 14 units.

A request refused before its items are counted (for example 409 `deletion_in_progress` or
`deletion_stuck`) costs at most its base cost (1, or 10 for a match, search or upload), never the
per-item part. A `restore_batch` answered 409 `restore_incomplete` has already been charged per item.

### When a limit is reached

The server answers HTTP 429 with a `Retry-After` header. The library waits and retries short waits by
itself; otherwise you get `RateLimitError`, or `DailyLimitError` when the daily budget is used up.
Both carry `retry_after`, the number of seconds until you can continue.

The library does not slow your requests down on its own (since 0.2.0): a fixed client-side cap could
hold a key below what its plan allows. To pace requests on your side anyway, pass
`requests_per_minute`, for example `glimsy.Client(requests_per_minute=100)`.

## Errors

Every error is a subclass of `glimsy.GlimsyError`, and `str(error)` explains in plain words what
happened and what to do. API errors also carry `status`, a stable `code`, the server's `detail` and a
`request_id` (include it when you report a problem). An error from creating cards or a deck also
carries `idempotency_key`, the key to retry it with safely (see "Retrying a failed creation").

| Exception | When |
|---|---|
| `MissingApiKeyError`, `InvalidApiKeyError` | no key was found, or the key is not in Glimsy's format (for example, copied incompletely) |
| `KeyExpiredError` | the key is older than 90 days: generate a new one in Settings → API key |
| `KeyRevokedError` | the key was deactivated (by you, by a newer key, or by Glimsy) |
| `AuthenticationError` | any refused key (the two above are subclasses), e.g. a key for another environment |
| `ApiBlockedError` | Glimsy has blocked API access for this account; contact Glimsy support |
| `EditsUnavailableError` | editing or deleting existing cards and decks, or changing deck CSS, is disabled on this server (`me().can_edit` is false) |
| `PlanRequiredError` | this account's plan does not include API access (HTTP 403 `plan_required`); `str(error)` is the server's explanation; see https://glimsy.app/en/api/#limits |
| `PlanLimitError` | your plan does not allow more decks or cards, or audio; see https://glimsy.app/en/api/#limits |
| `PermissionDeniedError` | any other refusal of a valid key (the four above are subclasses) |
| `NotFoundError` | the deck or card does not exist or is not yours (the server does not say whether it is missing or belongs to someone else) |
| `DeletionInProgressError` | an undo of a deletion came while the Glimsy app is still moving the item to the trash; nothing was restored, try again in a moment (`retry_after` when the server says how long). A `ConflictError`, never retried automatically |
| `DeletionStuckError` | the Glimsy app never finished moving the item to the trash, so waiting will not help: restore it from the trash in the Glimsy app; nothing was restored. A `ConflictError`, never retried automatically |
| `ConflictError` | any other conflict (the two above are subclasses); with `code` `restore_incomplete` the deck is back but some of its cards are still in the trash: send the same restore again to bring them back |
| `ValidationError` | the request content was refused, e.g. card HTML with forbidden markup or a file that is too large |
| `DeckTooLargeError` | the deck has more than 2000 card documents (a two-way card counts twice, cards in the trash count too): delete it in the Glimsy app; nothing was deleted (a `ValidationError`) |
| `RateLimitError` | too many requests even after the automatic retries; `retry_after` says how long to wait |
| `DailyLimitError` | the key's daily budget is used up (a `RateLimitError`; `retry_after` says when it renews) |
| `ServerError`, `NetworkError` | Glimsy failed or could not be reached, even after the automatic retries |
| `PartialBatchError` | a large batch failed part-way; it carries the results that did succeed |

```python
try:
    client.cards.update_many(edits)
except glimsy.KeyExpiredError:
    print("Generate a new key in the Glimsy web app: Settings → API key")
except glimsy.EditsUnavailableError:
    print("Editing is not available on this server")
except glimsy.RateLimitError as error:
    print(f"Too many requests, try again in {error.retry_after} s")
```

## License

Apache-2.0.
