Metadata-Version: 2.5
Name: grammateus-sdk
Version: 0.3.0
Summary: Grammateus SDK for Python
Project-URL: Homepage, https://github.com/aiswiss-davision/sdk-grammateus
Project-URL: Repository, https://github.com/aiswiss-davision/sdk-grammateus
Author: aiswiss-davision
License: MIT
Keywords: grammateus,sdk,translation
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.8
Requires-Dist: httpx<1,>=0.24
Requires-Dist: openpyxl<4,>=3.0
Requires-Dist: pyyaml<7,>=6
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Description-Content-Type: text/markdown

# grammateus-sdk (Python)

Python SDK for Grammateus. Translates PDF and Word documents through the
Grammateus integration API, with a blocking and an asyncio client.

## Install

```bash
pip install grammateus-sdk
```

## Configure

You need an API key with the `translation` scope and the base URL of your
Grammateus deployment. Grammateus is deployed per domain, so there is no
default base URL (an API platform token is the exception, see below).

```bash
export GRAMMATEUS_BASE_URL="https://your-domain.example.com"
export GRAMMATEUS_API_KEY="sk-grammateus-xxxxxxxx.yyyyyyyy"
```

Both can also be passed directly: `GrammateusClient(api_key=..., base_url=...)`,
or kept in a YAML file together with the other settings; see
[Configuration](#configuration).

## Which path the API is published on

`base_url` is the deployment origin; the SDK appends the integration prefix
`/api/api/v1/integration` by default:

| Deployment | Public path | `api_prefix` |
| --- | --- | --- |
| client deployments (e.g. `https://production.grammateus.selabs.ai`) | `/api/api/v1/...` | default |

## API platform tokens

The Grammateus API platform issues tokens of the form
`sk-gram-<8 hex>.<64 hex>` from its admin console
(`https://production.grammateus.selabs.ai/api-platform/`). Such a token picks
two defaults of its own:

| Setting | Default for `sk-gram-` | Default for `sk-grammateus-` |
| --- | --- | --- |
| `base_url` | `https://production.grammateus.selabs.ai` (when `GRAMMATEUS_BASE_URL` is unset) | none, required |
| `api_prefix` | `/api-platform/api/v1/integration` | `/api/api/v1/integration` |

```python
client = GrammateusClient(api_key="sk-gram-xxxxxxxx.yyyy...")  # nothing else needed
```

An explicit `base_url` or `api_prefix`, from code, the environment or the
YAML file, always wins.
Deployment keys (`sk-grammateus-...`) behave exactly as before. Both clients,
blocking and async, apply the same rules.

## Configuration

Every setting can come from four places. The first one that has it wins:

1. an argument in code: `GrammateusClient(timeout=60)`, `translate_documents(..., poll_interval=2)`
2. an environment variable
3. a YAML file
4. the built-in default

Users who only set environment variables need to change nothing.

### The YAML file

```yaml
# grammateus.yaml
api_key: ${GRAMMATEUS_API_KEY}        # the secret stays in the environment
base_url: https://your-domain.example.com
poll_interval: 10
batch:
  max_in_flight: 4
translation:
  target_language: de
  style: exact
download:
  directory: ./translated
```

```python
from grammateus_sdk import GrammateusClient

with GrammateusClient() as client:                    # finds ./grammateus.yaml
    result = client.translation.translate_documents(["contract.pdf"])  # -> de, exact
    client.download_outputs(result)                    # -> ./translated/

client = GrammateusClient.from_config("deploy/grammateus.yaml", timeout=60)
client = GrammateusClient(config_file="deploy/grammateus.yaml")   # the same
```

[`grammateus.example.yaml`](grammateus.example.yaml) lists every key with its
default and a comment. `AsyncGrammateusClient` takes the same `config=`,
`config_file=` and `from_config()`. The settings a client runs with are on
`client.config`, an immutable `SDKConfig`; `load_config()` returns one
without building a client:

```python
from grammateus_sdk import load_config

config = load_config()                 # same lookup as the client
config = load_config("ci.yaml", poll_interval=1)
client = GrammateusClient(config=config)
```

With no file named, the SDK looks in this order and reads the first file it
finds. Finding none is fine: the defaults apply. A file you name that does
not exist is an error.

1. the file in `$GRAMMATEUS_CONFIG`
2. `./grammateus.yaml`, then `./grammateus.yml`, in the working directory
3. `$XDG_CONFIG_HOME/grammateus/config.yaml` (or `config.yml`), by default
   `~/.config/grammateus/config.yaml`

### Every setting

| Setting | Argument | Environment | YAML key | Default |
| --- | --- | --- | --- | --- |
| API key | `api_key=` | `GRAMMATEUS_API_KEY` | `api_key`, `api_key_env` | none, required |
| Base URL | `base_url=` | `GRAMMATEUS_BASE_URL` | `base_url` | platform origin for `sk-gram-`, else required |
| Integration prefix | `api_prefix=` | `GRAMMATEUS_API_PREFIX` | `api_prefix` | by key kind, see [below](#api-platform-tokens) |
| HTTP timeout (s) | `timeout=` | `GRAMMATEUS_TIMEOUT` | `timeout` | 30 |
| Poll interval (s) | `poll_interval=` per call | `GRAMMATEUS_POLL_INTERVAL` | `poll_interval` | 5 |
| Wait for a task (s) | `timeout=` per call | `GRAMMATEUS_WAIT_TIMEOUT` | `wait_timeout` | 1800 |
| Upload link lifetime (s) | `expiry_seconds=` per call | | `upload_link_expiry` | 3600 |
| Tasks at once in a batch | `max_in_flight=` | | `batch.max_in_flight` | 2 |
| Files per batch task | `chunk_size=` | | `batch.chunk_size` | 1 |
| Translation settings | `target_language=`, `source_language=`, `translation_style=`, `method_of_translation=`, `glossary_ids=` or `settings=` | | `translation.target_language`, `.source_language`, `.style`, `.method`, `.glossary_ids` | target required; `auto`, `fluid`, none, `[]` |
| Download directory | `directory=` / `destination=` | | `download.directory` | required |

`GRAMMATEUS_API_PREFIX` and the YAML `api_prefix` take the prefix with or
without its `/integration` tail, so the session form `/api/v1` that
[`create_api_key.py`](examples/create_api_key.py) uses works for the SDK too.
An `api_prefix=` argument is used exactly as given. `timeout=None` still
disables the HTTP timeout, as it always did.

### Keeping the key secret

- Keep the key out of the file. Reference it with `${GRAMMATEUS_API_KEY}`,
  or name the variable that holds it with `api_key_env: MY_TEAM_KEY`.
  `${VAR:-default}` supplies a fallback and `$${` is a literal `${`.
- A literal `api_key:` works, but `chmod 600` the file: on Linux and macOS
  the SDK emits a `ConfigurationWarning` when other users can read a file
  that holds one. Never commit such a file.
- The key is stripped of surrounding whitespace and checked against
  `sk-gram-<prefix>.<secret>` / `sk-grammateus-<prefix>.<secret>` before any
  request. Errors name where the key came from and what is wrong with it,
  never the key itself, and `repr(config)` leaves it out.
- The file is parsed with `yaml.safe_load`, so it cannot construct Python
  objects.

### Mistakes are reported, not ignored

A misspelt key, a wrong type or an out-of-range value raises
`ConfigurationError` naming the file and the key, and an unknown key lists
the allowed ones:

```
grammateus.yaml: timout: unknown key (did you mean 'timeout'?); allowed keys: api_key, ...
grammateus.yaml: batch.chunk_size must be an integer between 1 and 20, got 25
grammateus.yaml: invalid YAML at line 3, column 11: mapping values are not allowed here
grammateus.yaml: base_url: ${DEPLOY_HOST} is not set; export it, or write ${DEPLOY_HOST:-default}
```

A reference to an unset variable only fails when its value is actually used:
`api_key: ${GRAMMATEUS_API_KEY}` is fine without the variable when the key is
passed in code.

## Translate a document

```python
from grammateus_sdk import GrammateusClient

with GrammateusClient() as client:
    result = client.translation.translate_documents(
        ["contract.pdf"],
        target_language="de",
    )
    print(result.status)                       # "FINISH"
    client.download_outputs(result, "./out")   # ./out/<translated>.docx
```

`translate_documents` uploads the files, creates the task and polls until it
finishes. Pass `wait=False` to get the task handle back immediately instead.

## Async

The async client mirrors the blocking one method for method:

```python
import asyncio
from grammateus_sdk import AsyncGrammateusClient

async def main():
    async with AsyncGrammateusClient() as client:
        result = await client.translation.translate_documents(
            ["contract.pdf"], target_language="de"
        )
        await client.download_outputs(result, "./out")

asyncio.run(main())
```

## Step by step

`translate_documents` is a convenience wrapper over four calls you can also
make yourself — useful when the upload and the translation happen in different
processes:

```python
from grammateus_sdk import GrammateusClient, TranslationSettings

with GrammateusClient() as client:
    # 1. Presigned upload to object storage, then activate the files.
    file_ids = client.files.upload(["contract.pdf", "annex.docx"])

    # 2. Queue the translation.
    task = client.translation.create_task(
        file_ids,
        TranslationSettings(
            target_language="de",
            source_language="en-US",
            translation_style="exact",
        ),
        glossary="glossary.xlsx",  # optional: see Glossaries
    )

    # 3. Poll, or check once with get_result().
    result = client.translation.wait_for_result(task.task_id, poll_interval=5)

    # 4. Fetch the translated documents.
    for link in result.output_links:
        client.download(link, "./out")
```

## Progress

Pass `on_progress=` a callable to any long-running method, or hand it a
`ProgressBar` to render one line:

```python
from grammateus_sdk import GrammateusClient, ProgressBar

with GrammateusClient() as client:
    with ProgressBar() as bar:
        result = client.translation.translate_documents(
            ["contract.pdf"], target_language="de", on_progress=bar
        )
        client.download_outputs(result, "./out", on_progress=bar)
```

```
upload     [########################] 100%  3/3  2s  contract.pdf
translate  [\] PROCESSING  1m12s  5f3c...
download   [############------------]  52%  1.1MB/2.1MB  3s  translated.docx
```

The bar rewrites one line on a terminal and prints one line per change when
the stream is not a terminal, so CI logs stay readable. `ProgressBar` takes
`stream`, `width` and `enabled` if you want to force either behaviour.

Three phases are reported, and the SDK knows a different amount about each:

| Phase | Granularity |
| ----- | ----------- |
| `upload` | exact, per file (`2/3`) |
| `translate` | status and elapsed time only |
| `download` | exact, per byte |

**The `translate` phase is indeterminate, and that is an API limitation.** The
backend does compute a percentage, but the API-key result carries only
`task_id`, `status` and `output_file`, so there is nothing to show a real bar
from. The SDK already reads a percentage from the shapes the product uses
elsewhere, so the bar becomes determinate with no SDK change the moment the
integration result exposes one. Until then `result.percent` is `None`.

Upload progress is per file rather than per chunk on purpose: the presigned PUT
is signed with a fixed length, and streaming it would switch to chunked
transfer encoding, which object storage rejects. Downloads are streamed, so
they report real bytes and never have to fit the document in memory.

For your own rendering, the callback receives a `ProgressEvent`:

```python
def report(event):
    if event.is_determinate:
        print(f"{event.phase}: {event.percent:.0f}%")
    else:
        print(f"{event.phase}: {event.status} after {event.elapsed:.0f}s")

client.translation.translate_documents(
    ["contract.pdf"], target_language="de", on_progress=report
)
```

`phase` is one of `PHASE_UPLOAD`, `PHASE_TRANSLATE`, `PHASE_DOWNLOAD`;
`completed` / `total` / `percent` describe the work, `total` and `percent` being
`None` when unknown; `status` is the task status during `translate`; `elapsed`
is seconds since the phase began; `detail` is the file name or task id.

Exceptions from the callback are not caught — keep it cheap and non-throwing.

## Batch jobs

A task holds at most 20 files, so a bigger job becomes several tasks.
`translate_batch` chunks the input, keeps a bounded number of tasks running
and isolates failures:

```python
result = client.translation.translate_batch(
    paths,                        # any number of files
    target_language="de",
    chunk_size=1,                 # see below: one file per task
    max_in_flight=2,              # tasks running at once
    on_task_created=lambda task: store(task.task_id),
    on_progress=bar,
)

print(result.summary())           # "3/4 tasks finished, 1 failed"
result.succeeded, result.failed   # per task
result.unsubmitted                # chunks whose upload or create_task failed
result.output_links               # every output across the batch
```

**One file per task, and that is not a tuning choice.** The API accepts up to
20 `ls_file_id` per task, but the translation worker reads only
`ls_file_path[0]` — its own docstring calls the list "a single input file
path". Send two files and the task still answers `FINISH`, with the second one
missing and no error anywhere. `chunk_size` therefore defaults to 1, and
`translate_documents` raises if you hand it more than one file. Anonymization
does loop over the list; translation does not.

One bad chunk does not end the job: it lands in `unsubmitted` (or in `failed`
if the task itself errored) and the rest carry on.

**Persist the task ids.** A task keeps running on the server after the client
dies, so `on_task_created` is the hook that makes a batch resumable:

```python
result = client.translation.wait_for_batch(saved_task_ids)
```

`max_in_flight` defaults to 2. The API does not rate limit, but the AI workers
are finite, so a job does not finish sooner by flooding them.

`AsyncGrammateusClient` has the same two methods. Each chunk runs its whole
lifecycle as one coroutine held by a semaphore, so the results come back in
input order and nothing needs a scheduler loop.

While a batch polls, a 404 or a rejected key finishes that entry immediately —
polling again cannot change it — while a timeout, a 5xx or a dropped
connection is retried, because the task is still running on the server.

## Translation settings

| Field | Values | Default |
| ----- | ------ | ------- |
| `target_language` | language code (`"de"`) or English name (`"German"`) | required |
| `source_language` | same, or `"auto"` / `"auto-detect"` | `"auto"` |
| `translation_style` | `"exact"`, `"fluid"`, `"creative"` | `"fluid"` |
| `method_of_translation` | `"quick"`, `"full"`, `None` | `None` |
| `glossary_ids` | up to 5 ids of glossaries the key's user already owns; most callers pass `glossary=` instead, see [Glossaries](#glossaries) | `()` |

`translation_style` is the knob that actually changes the output: it sets the
model's sampling temperature — `exact` 0.1 (stays close to the source wording),
`fluid` 0.2 (natural target text), `creative` 0.7 (adapts the wording). Use the
`STYLE_EXACT` / `STYLE_FLUID` / `STYLE_CREATIVE` constants if you prefer not to
hand-write the strings.

`method_of_translation` is part of the API contract but **currently has no
effect** — the value is accepted and stored, and nothing downstream reads it.

## Languages

72 languages. English, Spanish, French, Portuguese and Chinese exist **only as
regional variants**, so a bare `"en"` is rejected:

```python
from grammateus_sdk import LANGUAGES, language_name, normalize_language

normalize_language("German")                   # "de"
normalize_language("English (United States)")  # "en-us"
normalize_language("en-US")                    # "en-us"
normalize_language("en")                       # InvalidRequestError
language_name("zh-cn")                         # "Chinese (Simplified)"
sorted(LANGUAGES)                              # every accepted code
```

Codes and names are matched case-insensitively and normalized to the lowercase
code the API stores. The ten regional ones are `en-us`, `en-gb`, `es-es`,
`es-419`, `fr-fr`, `fr-ca`, `pt-br`, `pt-pt`, `zh-cn`, `zh-tw`.

The SDK carries this list as a snapshot, because the API's
supported-languages endpoint is session-authenticated and an API key cannot
reach it. If your deployment is newer than the SDK, pass
`validate_languages=False` and let the API judge the value:

```python
TranslationSettings(target_language="xx-new", validate_languages=False)
```

## Glossaries

A glossary makes the translation follow your terminology. An API key can
neither list nor create glossaries, so the SDK sends the glossary with the
task: give `glossary=` an Excel or CSV file, or the same rows as dicts.
Nothing has to exist on the server first, and no id is involved.

```python
from pathlib import Path

from grammateus_sdk import GrammateusClient

# Full local paths: a document and a glossary on your machine.
document = Path.home() / "Downloads" / "contract.pdf"
glossary = Path.home() / "Downloads" / "glossary.xlsx"
output = Path.home() / "Downloads" / "out"

with GrammateusClient() as client:
    result = client.translation.translate_documents(
        [document],
        target_language="de",
        source_language="en-US",
        glossary=glossary,
    )
    for link in result.output_links:
        client.download(link, output)
```

### From an Excel or CSV file

The file is read on your machine, with the same rules as the web app's
glossary import, so a file the web app imports works here unchanged. It is
never uploaded; its terms go in the `create_task` request.

| Column header | Meaning |
| ------------- | ------- |
| a language code or name: `en`, `de`, `fr-FR`, `German`, `Allemand`, `Deutsch`, ... | the term in that language |
| `*`, `term`, `key` | a term that is the same in every language, kept as written |
| `note`, `comment` | a note sent to the model with the term's translation; a term kept as written goes without it |
| `do_not_translate`, `dnt`, `keep` | `yes`, `x` or `1` keeps the term untranslated |
| `case_sensitive` | `yes`, `x` or `1` matches the case exactly |
| `forbidden:fr`, `forbidden:it`, ... | wordings not to use in that language, separated by `;` or `\|`; one column per language |

| en | de | fr | it | forbidden:fr | note | do_not_translate | case_sensitive |
| -- | -- | -- | -- | ------------ | ---- | ---------------- | -------------- |
| revenue | Umsatz | chiffre d'affaires | fatturato | revenu | Company sales; 'revenu' is personal income in French | | |
| GDP | BIP | PIB | PIL | | | | yes |
| EBITDA | EBITDA | EBITDA | EBITDA | | | yes | yes |

Every language column works as source and target alike: the same file serves
a translation from English into German and one from German into French.

The first non-empty row is the header, and only the first sheet is read.
`.xlsx`, `.xlsm`, `.csv`, `.tsv` and `.txt` are accepted, up to 5 MB and
10 000 rows. Rows that start with a formula, hold a term longer than 300
characters or have no term at all are skipped. To see what a file yields
before translating anything, read it yourself:

```python
from grammateus_sdk import Glossary

glossary = Glossary.from_file("glossary.xlsx")
glossary.entries   # one dictionary per row, as listed below
glossary.warnings  # what was skipped or ignored, worded as the web app words it
```

A file the import would refuse raises `GlossaryFileError` before anything is
uploaded. `error.code` is the web app's own reason: `no_language_columns`,
`no_valid_terms`, `empty_file`, `unsupported_type`, `too_large`, ...

### From dictionaries, without a file

The same glossary can be built in code. Give one dict per row, keyed by the
column names a file would have; the rows go through exactly the file rules,
so they give the same entries, warnings and errors as the spreadsheet:

```python
glossary = [
    {"en": "revenue", "de": "Umsatz", "fr": "chiffre d'affaires", "it": "fatturato",
     "forbidden:fr": "revenu", "note": "Company sales; 'revenu' is personal income in French"},
    {"en": "GDP", "de": "BIP", "fr": "PIB", "it": "PIL", "case_sensitive": True},
    {"en": "EBITDA", "do_not_translate": True},
]

client.translation.translate_documents(
    [document], target_language="de", glossary=glossary
)
```

A forbidden column may hold a list instead of `"a; b"`, and a flag `True` or
`False` instead of `yes`. Rows read from your own data work the same, for
example `pandas.DataFrame.to_dict("records")`. `Glossary.from_rows(rows)`
builds the glossary without sending it, to look at `entries` and `warnings`;
in its `issues`, `indexes` point into your list.

Two other forms are accepted:

- **Entries**, the form a file is parsed into, with the terms under `terms`:

  ```python
  glossary = [
      {
          "terms": {"en": "contract", "de": "Vertrag"},
          "note": "legal sense",
          "forbidden": {"de": ["Kontrakt"]},
      },
      {"terms": {"*": "Grammateus"}, "do_not_translate": True},
  ]
  ```

  Only `terms` is required; `forbidden`, `note`, `do_not_translate` and
  `case_sensitive` are optional. The entries are checked against the API's
  own rules before any request, so a mistake fails locally.

- **`{term: description}`**, the format the meeting-recording API takes for
  its `glossary`, such as `{"Grammateus": "product name", "SELabs": None}`.
  Each term is kept exactly as written, which suits names, brands and
  acronyms. The description is stored with the glossary, but the translation
  model is not given the note of a term it keeps as written, so it does not
  change the output. The same holds for the note of a `do_not_translate` row.
  A single dict whose keys are column names, such as
  `{"en": "revenue", "de": "Umsatz"}`, is refused: wrap it in a list to make
  it a row.

In every form, languages are codes or names, as in a file header, and a
`note` reaches the model when the entry pins a translation.

### How terms are found in the document

- A term matches in any case unless the row is `case_sensitive`; then `GDP`
  matches and `gdp` does not.
- Endings added to the whole term match as well (`interest rates`,
  `shareholders`, `free kicks`), but a plural that changes the stem does not:
  `subsidy` does not find `subsidies`, nor `penalty` `penalties`. Add such a
  form as a row of its own, with that form in every language.
- Rows that share a term in any language are merged into one entry, later
  values winning, as a web app import merges them.

### Limits

- At most 5000 entries per task: translation reads no more.
- The glossary takes one of a task's five glossary slots, so at most four
  `glossary_ids` can go with it. `glossary_ids` only work for glossaries that
  already belong to the key's user; passing one you do not own gives
  `NotFoundError: Glossary <id> not found`.
- `translate_batch` reads the glossary once and sends it with every task.
- The deployment has to accept `glossary` on `create_task`. An older one
  ignores the field and translates without the glossary.
- The integration result does not return the glossary report, so there is no
  programmatic way to confirm which terms were applied.

## Task statuses

`CREATED`, `QUEUEING`, `PROCESSING`, then `FINISH` or `ERROR`. Use
`result.is_done`, `result.succeeded` and `result.failed` rather than comparing
strings.

The integration result carries the status and the output links only. Progress
percentage, estimated time, previews, extracted output text and the glossary
report exist on the session-authenticated endpoint but are stripped from the
API-key response. See [Progress](#progress).

## Limits

- **Input must be PDF, DOC or DOCX.** The translation product itself also
  handles spreadsheets, presentations, ODF, plain text and images, but the
  integration API deliberately narrows API-key callers to these three.
- At most 20 files per upload batch and per task.
- The API inspects the real bytes, not the file name, so a renamed file is
  refused. A PDF must open, must not be password protected and must stay within
  the deployment's page budget (500 by default).
- Up to 5 glossaries per task, a `glossary=` sent with it counting as one, and
  at most 5000 glossary entries.

## Errors

Everything derives from `GrammateusError`:

| Exception | Raised when |
| --------- | ----------- |
| `ConfigurationError` | no API key or base URL, a malformed key, or a bad config file |
| `InvalidRequestError` | rejected locally, before any call |
| `GlossaryFileError` | a glossary file the web app's import would refuse; `error.code` says why (an `InvalidRequestError`) |
| `AuthenticationError` | 401, bad or expired key |
| `PermissionDeniedError` | 403, the key lacks the `translation` scope |
| `NotFoundError` | 404, no such task, file or glossary |
| `ValidationError` | 400/422, the API rejected the body |
| `FileRefusedError` | 400 file refusal; `error.refusal["code"]` is stable |
| `RateLimitError` | 429 |
| `ServerError` | 5xx |
| `UploadError` / `DownloadError` | object storage transfer failed |
| `TaskFailedError` | the task ended as `ERROR`; `error.result` holds it |
| `TaskTimeoutError` | `wait_for_result` hit its timeout |

`FileRefusedError` is worth branching on, because the reason is machine
readable:

```python
from grammateus_sdk import FileRefusedError

try:
    file_ids = client.files.upload(["contract.pdf"])
except FileRefusedError as error:
    if error.refusal["code"] == "PDF_PASSWORD":
        ...  # ask for an unlocked copy
```

`UPLOAD_REFUSAL_CODES` holds the codes raised while activating an upload
(`UPLOAD_EMPTY_FILE`, `UPLOAD_TYPE_NOT_ALLOWED`, `UPLOAD_EXTENSION_MISMATCH`,
`UPLOAD_DANGEROUS_TEXT`) and `DOCUMENT_REFUSAL_CODES` those raised when the
task inspects the stored document (`PDF_PASSWORD`, `PDF_TOO_MANY_PAGES`,
`OFFICE_PASSWORD`, `FILE_TOO_LARGE`, ...).

## Not covered

These are translation features the product has but an API key cannot reach,
because they live on session-authenticated routes:

| Feature | Endpoint |
| ------- | -------- |
| Text-only translation | `POST /ai/translation/create_text_task` |
| Re-translate a task with new settings | `POST /ai/translation/retranslate` |
| Retry a failed task | `POST /ai/translation/retry` |
| List supported languages | `GET /ai/translation/supported_languages` |
| Create or list glossaries (send one with the task instead, see [Glossaries](#glossaries)) | `/term-glossaries`, `/glossaries` |

Each one needs to be mirrored onto the integration router before the SDK can
offer it.

Two fields are also missing from the integration translation result although
the backend already has them: the **progress percentage** (`progress_state`)
and the **glossary report**. Meeting recording's integration result already
returns a `progress` object, so the pattern exists.

## Examples

### Getting an API key

The SDK only speaks to the API-key routes; creating the key goes through the
session API. [`examples/create_api_key.py`](examples/create_api_key.py) does
that bootstrap step. Credentials come from the environment so they stay out of
shell history and `ps`:

```bash
export GRAMMATEUS_BASE_URL='https://your-domain.example.com'
export GRAMMATEUS_USERNAME='you'
export GRAMMATEUS_PASSWORD='...'
export GRAMMATEUS_API_PREFIX='/api/v1'      # only where the proxy does not strip /api

python examples/create_api_key.py --name my-integration --scope translation
eval "$(python examples/create_api_key.py --name my-integration --export)"

python examples/create_api_key.py --list
python examples/create_api_key.py --revoke sk-grammateus-ab12cd34
```

The full key is returned once and never again. `--export` prints a shell
`export` line so `eval` can set `GRAMMATEUS_API_KEY` without the key passing
through your history.

### Translating

[`examples/translate_document.py`](examples/translate_document.py) is a runnable
walk-through of every translation setting, both call styles and the error
paths:

```bash
export GRAMMATEUS_API_KEY='sk-grammateus-xxxx.yyyy'

python examples/translate_document.py contract.pdf \
    --base-url https://demo.grammateus.selabs.ai \
    --api-prefix /api/v1/integration \
    --target-language German --source-language en-US \
    --style exact --method full --glossary-file glossary.xlsx \
    --mode steps

python examples/translate_document.py --list-languages
```

`--mode simple` calls `translate_documents()` once per file; `--mode steps`
does the same work as `files.upload()` / `create_task()` / `wait_for_result()`
so each API call is visible; `--mode batch` hands every file to
`translate_batch()`. `--target-language` repeats (or takes `de,fr-fr`) for one
run per language. The run ends with one line per file and language, `OK` with
the saved path or `FAILED` with the reason, and exits 1 if any failed.

### Translation job file

The same example takes its job from YAML instead of flags:
[`examples/translation.example.yaml`](examples/translation.example.yaml) lists
every key with the flag it stands for.

```yaml
client:                          # the keys of grammateus.yaml; omit it for the usual lookup
  api_key: ${GRAMMATEUS_API_KEY}
documents: [contracts/*.pdf, reports/q3.docx]   # files or globs, relative to this file
target_languages: [de, fr-fr]    # one run per language; a single string works too
style: fluid
mode: batch                      # simple | steps | batch
output: {directory: "translated/{language}", overwrite: false}
```

```bash
python examples/translate_document.py --config translation.yaml --dry-run
python examples/translate_document.py --config translation.yaml --target-language vi
```

Flags win over environment variables, which win over the file, which wins
over the defaults. `--dry-run` checks the file, expands the globs and prints
the plan without sending anything or needing the key. Errors name the file,
the line and the key (`translation.yaml:14: style must be one of creative,
exact, fluid, got 'bold'`), and unknown keys are rejected with a suggestion.
The loader is [`examples/translation_job.py`](examples/translation_job.py),
part of the example rather than of the package.

## End-to-end scenarios

[`scripts/e2e_translation.py`](scripts/e2e_translation.py) drives the SDK
through 19 numbered translation scenarios against a real deployment: single
PDF and DOCX, steps mode with progress, a 3-file batch, the async client, the
settings, a Vietnamese file name, a ~5 MB PDF, the local refusals (unsupported
extension, empty file, missing path, bad language), wrong / revoked / unscoped
keys, cross-user isolation, usage and timeouts. Each prints `PASS`, `FAIL` or
`SKIP` with its time and a one-line reason; a summary table and
`report.json` follow, and the exit code is non-zero on any failure. Fixtures
are generated at run time; it needs only the SDK and httpx.

```bash
python scripts/e2e_translation.py --fake

export GRAMMATEUS_BASE_URL='https://demo.grammateus.selabs.ai'
export GRAMMATEUS_API_PREFIX='/api/v1/integration'
export GRAMMATEUS_API_KEY='sk-grammateus-xxxxxxxx.yyyy'    # translation scope
export GRAMMATEUS_USERNAME='...' GRAMMATEUS_PASSWORD='...'  # the key's owner: 15, 16, 18
export GRAMMATEUS_USERNAME_2='...' GRAMMATEUS_PASSWORD_2='...'  # another user: 17
python scripts/e2e_translation.py --out ./e2e-out/demo
```

| Flag | Meaning |
| --- | --- |
| `--list` | print the scenarios and exit |
| `--only 1,3,10-14` / `--skip 9` | pick scenarios by number, range or slug |
| `--target direct` | a deployment's integration API (default) |
| `--target platform` | the API platform; 15-18 then use `PLATFORM_ADMIN_USERNAME` / `PLATFORM_ADMIN_PASSWORD` |
| `--out DIR` | where outputs and `report.json` go (default `./e2e-out/<timestamp>`) |
| `--timeout S` | wait per translation (default 900 s) |
| `--fake` | run against the local fake instead of a deployment |
| `--config FILE` | read the settings from YAML, see below |

Scenarios 15-17 create throwaway keys through the session API
(`/login`, `/me/api-keys`, under `GRAMMATEUS_API_PREFIX` minus
`/integration`; override with `GRAMMATEUS_SESSION_PREFIX`). They expire after
one day and are revoked in a `finally` block, also on Ctrl-C; each revocation
is printed as a `cleanup:` line. A scenario whose credentials are not set is
skipped, not failed: 17 needs a second user because keys of one user see each
other's tasks. A full real run creates about 15 translation tasks; use
`--only` for a quicker pass.

### Script settings from YAML

Both test scripts, `e2e_translation.py` and the API platform stress harness
`stress_platform.py`, take `--config FILE.yaml` instead of a long list of
flags and variables. Flags win over environment variables, which win over the
file, which wins over the defaults, so every existing flag and variable keeps
working. One file can drive both:

```yaml
client:                    # the SDK keys, as in grammateus.example.yaml
  api_key: ${GRAMMATEUS_API_KEY}
  base_url: https://demo.grammateus.selabs.ai
  api_prefix: /api/v1/integration
target: direct             # e2e only: direct or platform (--target)
admin: {username: admin, password: "${PLATFORM_ADMIN_PASSWORD}"}
e2e: {only: "1-19", glossary_id: null, large_mb: 5, poll_interval: 5, timeout: 600, out: ./e2e-out}
stress: {only: "a-e", k: 6, max_real_tasks: 20, rate_limit: 120, max_active: 5, max_queued: 50,
         max_upload_bytes: 104857600, expect_ingress_limits: true, soak_minutes: 0, out: ./stress-out}
```

[`scripts/e2e.example.yaml`](scripts/e2e.example.yaml) and
[`scripts/stress.example.yaml`](scripts/stress.example.yaml) list every key
with the flag or variable it stands for. Keep passwords and keys in the
environment through `${VAR}`; a reference to an unset variable only fails
when the run needs that value (the admin password of a `direct` run never
is). Unknown keys and bad values stop the run with exit code 2 before
anything is sent. The scripts read only `--config` and the environment, never
`grammateus.yaml`.

```bash
python scripts/e2e_translation.py --config e2e.yaml
PLATFORM_ADMIN_PASSWORD=... python scripts/stress_platform.py --config stress.yaml --only d
```

## Local development

```bash
cd python
pip install ".[test]"
pytest
```

See the [project docs](../docs/python.md) for more.
