Metadata-Version: 2.4
Name: glimsy
Version: 0.1.0
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

# glimsy

The official Python library for managing your own [Glimsy](https://glimsy.app) flashcards through the
Glimsy API: create decks and cards, replace card content (text, images, audio), find copies of cards you
already have, and upload media. The library batches large jobs, walks through pages, keeps to the
request limits and retries temporary failures by itself. Python ≥ 3.11.

> **Status:** beta (0.1.x). 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 yourself, in the Glimsy web app:

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

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

What to know about keys:

- A key is valid for **90 days**. Settings shows whether it is active and when it expires.
- You have **one active key**. Generating a new one replaces (deactivates) the old one.
- You can generate at most **3 keys per day** (the day counts in Polish time); after that the web app
  says the daily limit is reached. Deactivating a key does not give a generation back.
- **Deactivate** a key in the same place when you no longer need it or think it leaked.
- A key acts only on your own data, and never on your learning progress.

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

## Install

```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("Hebrew")

    card = client.cards.create(deck, front="שָׁלוֹם", back="hello", direction="two_way")

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

    for found in client.cards.match([("שלום", "hello")], deck_ids=[deck]):
        print(found.status, found.best)
```

`glimsy.AsyncClient` offers the same methods 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 function or endpoint) |
|---|---|
| See who you are: `client.me()` (account, environment, whether editing is allowed) | Delete anything (cards, decks, media, account) |
| Decks: `list`, `get` (by name or id), `create`, `rename` | Touch learning progress (reviews, FSRS state, due dates, history, statistics) |
| 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 |
| Cards: `list` (all pages), `create`, `create_many`, `update`, `update_many` | Read or change another user's data |
| 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) |
| Media: `media.missing`, `media.upload`, `media.ensure` (uploads only what is missing) | |
| Undo edits of the last 7 days: `changes.list`, `changes.restore`, `changes.restore_batch` | |

Replacing the content of existing cards and changing deck CSS can be switched off on a server;
`client.me().can_edit` tells you whether the server you talk to allows it. Undo works either way.

## 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. Learning progress is never copied nor changed, by an edit or 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)  # put the previous stylesheet back

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)  # write back one change
```

A restore is kept for undo too (`restore(...).undo_batch_id`). 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, again today, due
from earlier days — with `& .giz-card[data-giz-card="new" | "today" | "review"]`. The full reference is
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` and `update_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` says `ok` with the card, or 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 answer got lost. Repeat with that key instead of a fresh 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` takes `idempotency_key=` the same way. `cards.create` has no such argument: repeat 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 limit.** A key may send 60 requests per minute. The client keeps to that by itself: it never
  starts more than `requests_per_minute` requests in any 61 seconds (one second of margin over the
  server's minute) and makes the next call wait instead.
  The limiter is shared by all threads and asyncio tasks that use the same client, so share one client
  in a program. Change or switch it off with `glimsy.Client(requests_per_minute=120)` or
  `glimsy.Client(requests_per_minute=None)`. Separate processes using one key are not coordinated.
  The server's `RateLimit` headers are honoured as well.
- **Retries.** Temporary failures are repeated 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 programs refused together do not come back in the same second. The time limit counts from the
  first send, so waiting in the limiter's queue does not use it up. At most 4 attempts and 90 seconds
  per call by default; a server wait longer than 60 seconds (for example the daily budget) is raised
  at once instead of blocking. Tune it with `glimsy.Client(retry=glimsy.RetryPolicy(...))`;
  `RetryPolicy(max_attempts=1)` turns retries off.
- **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 repeated after any temporary failure.
  Other writes — editing cards, renaming a deck, deck CSS, media upload — are repeated 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 state (for example `cards.list`) before trying again.
- **Daily budget.** Each key also has a daily budget of 10 000 cost units: 1 per plain request, 10 for a
  search, a match or an upload, plus 1 per batch item; a match or search over a large collection costs
  a little more (about 1 unit per 100 cards it reads). When the budget is used up you get
  `DailyLimitError`.

## Errors

Every error is a subclass of `glimsy.GlimsyError`, and `str(error)` says 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` (quote it when you report a problem). An error from creating cards or a deck also
carries `idempotency_key`, the key to repeat it with safely (see "Retrying a failed creation").

| Exception | When |
|---|---|
| `MissingApiKeyError`, `InvalidApiKeyError` | no key found, or the key is not in Glimsy's format (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` | changing existing cards or deck CSS is switched off on this server (`me().can_edit` is false) |
| `PlanLimitError` | your plan does not allow more decks or cards, or audio |
| `PermissionDeniedError` | any other refusal of a valid key (the three above are subclasses) |
| `NotFoundError` | the deck or card does not exist or is not yours (the server does not tell which) |
| `ValidationError` | the request content was refused, e.g. card HTML with forbidden markup or a file too large |
| `RateLimitError` | too many requests per minute 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 half-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 yet")
except glimsy.RateLimitError as error:
    print(f"Slow down, try again in {error.retry_after} s")
```

## License

Apache-2.0.
