Metadata-Version: 2.4
Name: dai-media-sdk
Version: 0.8.0
Summary: Python SDK for D.AI image, video, and audio generation
License-Expression: MIT
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx<1,>=0.27
Requires-Dist: typing-extensions>=4.7
Provides-Extra: test
Requires-Dist: pytest>=8; extra == "test"
Requires-Dist: respx>=0.21; extra == "test"
Provides-Extra: dev
Requires-Dist: ruff>=0.8; extra == "dev"
Requires-Dist: mypy>=1.13; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"
Dynamic: license-file

[简体中文](./README-ZH.md) | English

# dai-media-sdk

Python client for D.AI image, video, and audio generation.

## Install

```bash
pip install dai-media-sdk
```

## Custom endpoint

```python
import os
from dai_media import DaiMediaClient

client = DaiMediaClient(
    api_key=os.environ["DAI_API_KEY"],
    base_url="https://gateway.example.com/dai",
    timeout=90.0,
)
```

The configured path prefix is preserved for every endpoint. The SDK owns the bearer header and ignores custom `Authorization` and `Content-Type` values. API keys are redacted from `repr` and exceptions.

## Typed model ids and parameters

`dai_media.enums` (re-exported from `dai_media`) carries the model ids published by `GET /api/system/public/capability-docs` and the parameter values the backend actually validates. Every request field still accepts a plain string, so nothing breaks — the enums just make the documented values discoverable and typo-resistant.

```python
from dai_media import (
    FLUX_IMAGE_MODELS,          # tuple[str, ...] for a whole capability
    GeminiVideoAspectRatio,     # str Enum: RATIO_16_9, RATIO_9_16
    GeminiVideoModel,           # str Enum: VEO_3_1_FAST, OMNI_FLASH, OMNI_1_1_FLASH, ...
    MODELS_BY_CAPABILITY,       # every capability_code -> model tuple
    OpenAiImageModel,
    OpenAiImageQuality,
)

OpenAiImageModel.GPT_IMAGE_2_5_FLARE   # "gpt-image-2.5-flare" on the wire
GeminiVideoAspectRatio.RATIO_16_9      # "16:9" on the wire
```

Open values are not narrowed. `openai_image.size` keeps accepting `WIDTHxHEIGHT`; it only ships preset tuples (`OPENAI_IMAGE_SIZES`, `OPENAI_IMAGE_FLEX_SIZES`) next to the field. The `gemini_image`, `flux_image` and `novel_image` presets listed below are open as well: the proxy forwards those values unchecked and the accepted subset differs per model, so each field takes the enum member or any string.

| Capability | Model enum | Closed-set parameter enums |
| --- | --- | --- |
| `openai_image` | `OpenAiImageModel` | `OpenAiImageQuality`, `OpenAiImageOutputFormat` |
| `gemini_image` | `GeminiImageModel` | open presets: `GeminiImageAspectRatio`, `GeminiImageSize`, `GeminiImageThinkingLevel` |
| `flux_image` | `FluxImageModel` | open presets: `FluxImageAspectRatio`, `FluxImageSize` |
| `gemini_video` | `GeminiVideoModel` | `GeminiVideoAspectRatio`, `GeminiVideoResolution`, `GeminiVideoGenerationType` |
| `flux_video` | `FluxVideoModel` | `FluxVideoMode`, `FluxVideoResolution` |
| `grok_video` | `GrokVideoModel` | `GrokVideoAspectRatio`, `GrokVideoResolution` |
| `wan_video` | `WanVideoModel` | `WanVideoResolution`, `WanVideoRatio`, `WanVideoMediaType` |
| `happyhorse_video` | `HappyHorseVideoModel` | `HappyHorseVideoResolution`, `HappyHorseRatio`, `HappyHorseAudioSetting`, `HappyHorseMediaType` |
| `midjourney` | `MidjourneyModel` | `MidjourneyMode` |
| `midjourney_video` | `MidjourneyVideoModel` | `MidjourneyVideoResolution` |
| `suno_music` | `SunoMusicModel` | `SunoVocalGender` |
| `novel_image` | `NovelImageModel` | open presets: `NovelImageSampler`, `NovelImageNoiseSchedule` |
| `seedream_image` | `SeedreamImageModel` | — (ids only, no request type yet) |
| `seedance_video` | `SeedanceVideoModel` | — (ids only, no request type yet) |
| `flowmusic_music` | `FlowMusicModel` | — (ids only, no request type yet) |
| `suno_speech` | `SunoSpeechModel` | — (id only, no request type yet) |
| `openai_speech` | `OpenAiSpeechModel` | `OpenAiSpeechStreamFormat` |
| `systemone_decision` | `SystemoneDecisionModel` | — (billed per request, by body-size tier) |

`grok_image` has no public catalogue entry (the proxy rewrites `model` upstream), so `GrokImageRequest.model` stays a plain string while `aspect_ratio` is enumerated. Range constants (`GROK_VIDEO_LENGTH_RANGE`, `FLUX_VIDEO_DURATION_RANGE`, `WAN_VIDEO_DURATION_RANGE`, `HAPPYHORSE_DURATIONS`, `OPENAI_SPEECH_MAX_INPUT_CHARS`) cover integer parameters instead of enums.

`openai_speech` (OpenAI-shaped `POST /v1/audio/speech`, billed per input character) publishes 5 model ids. `stream_format` is the only closed set — the proxy rejects anything but `audio` (`OpenAiSpeechStreamFormat`). `voice` and `response_format` stay open strings: `OPENAI_SPEECH_VOICES` maps each model to its published voice presets (`csm-1b` 2, both ElevenLabs tiers 5, `kokoro-82m` 12, `voxtral-mini-tts-3-0` 4) and `OPENAI_SPEECH_RESPONSE_FORMATS` lists `mp3` (default) / `opus` / `aac` / `flac` / `wav` / `pcm`. `OPENAI_SPEECH_CSM_1B_MAX_INPUT_CHARS` (200) records the tighter upstream cap on `csm-1b`. Call it through `client.audio.speech(OpenAiSpeechRequest(...))` — see [Speech (text to speech)](#speech-text-to-speech).

`HappyHorseRequest.parameters` accepts the typed `HappyHorseParameters`, which types the published dropdowns. Pass a dict instead when you need a field the gateway does not publish; both forms serialize identically.

```python
from dai_media import (
    HappyHorseInput,
    HappyHorseParameters,
    HappyHorseRatio,
    HappyHorseRequest,
    HappyHorseVideoModel,
    HappyHorseVideoResolution,
)

job = client.videos.happyhorse.text_to_video(
    HappyHorseRequest(
        model=HappyHorseVideoModel.T2V_1_1,
        input=HappyHorseInput(prompt="A glass greenhouse at sunrise"),
        parameters=HappyHorseParameters(
            resolution=HappyHorseVideoResolution.P1080,  # "1080P"
            ratio=HappyHorseRatio.RATIO_16_9,  # "16:9", the published default
            duration=5,  # HAPPYHORSE_DURATIONS: 3/5/7/10/15
        ),
    )
)
```

## OAuth 2.1 / OIDC

`OAuthClient` and `AsyncOAuthClient` drive D.AI as an identity provider: discovery, PKCE authorization URLs, code exchange, refresh rotation, revocation and userinfo. The browser redirect, the loopback callback server and token storage belong to the host application; `examples/oauth-demo` in the D.AI repository is a complete Bun reference implementation.

```python
from dai_media import OAuthClient

with OAuthClient(
    "ddc_xxx",
    issuer="https://dai.itbug.shop",
    redirect_uri="http://127.0.0.1:48150/callback",
) as oauth:
    # 1. Send the browser to request.url; keep state and code_verifier.
    request = oauth.authorization_url(consent=True)

    # 2. Back at the callback: exchange the code, then read the profile.
    tokens = oauth.exchange_code(code, request.code_verifier)
    user = oauth.userinfo(tokens.access_token)

    # 3. Rotate and revoke.
    rotated = oauth.refresh(tokens.refresh_token or "", scope="openid")
    oauth.revoke(rotated.access_token)
```

Public clients are PKCE-only. Pass `client_secret` for a confidential client and token/revocation calls switch to HTTP Basic. `id_token` is returned raw; verify its RS256 signature with the issuer JWKS in the host application. OAuth access tokens are identity-only today (userinfo); they do not yet authenticate the media API.

## Image

```python
from dai_media import OpenAiImageModel, OpenAiImageRequest

with DaiMediaClient(api_key=os.environ["DAI_API_KEY"]) as client:
    result = client.images.openai.generate(
        OpenAiImageRequest(
            prompt="A glass greenhouse at sunrise",
            model=OpenAiImageModel.GPT_IMAGE_2_5_FLARE,
        )
    )
    print(result.images[0].url)
```

For **GPT Image 2.5（经济·非官方）**, explicitly use the async-job method (also available on `AsyncDaiMediaClient`):

```python
with DaiMediaClient(api_key=os.environ["DAI_API_KEY"]) as client:
    job = client.images.openai.gpt_generate(
        OpenAiImageRequest(
            model=OpenAiImageModel.GPT_IMAGE_2_5,
            prompt="Draw a glass greenhouse at sunrise",
            n=1,
        )
    )
    result = client.jobs.wait(job)
    print(result.assets)
```

This lower-cost unofficial channel may differ in latency, reliability, and output from official flare/sunburst. It supports one image only (`n` omitted or `1`); omit `size`, `quality`, `aspect_ratio`, `response_format`, `background`, and `output_format`, which are rejected rather than ignored. Official `generate` calls and defaults never switch to economy automatically; keep `OpenAiImageModel.GPT_IMAGE_2_5_FLARE` / `OpenAiImageModel.GPT_IMAGE_2_5_SUNBURST` on `generate`.

Gemini, Flux and Novel image requests take typed presets for their open fields (`GeminiImageRequest` also takes the boolean `google_search` / `image_search`; `NovelTextToImageRequest` the boolean `quality_toggle`). Unset fields are left out of the body, and `False` is sent as `false`. Per-model subsets are in the enum docstrings: `GeminiImageAspectRatio` `1:4` / `4:1` / `1:8` / `8:1` are not accepted by `gemini-3-pro-image-preview`, `GeminiImageSize.PX512` is for `gemini-3.1-flash-image(-preview)` only, and `GeminiImageThinkingLevel` has no value for the pro model.

```python
from dai_media import (
    FluxImageAspectRatio,
    FluxImageRequest,
    GeminiImageModel,
    GeminiImageRequest,
    GeminiImageSize,
    GeminiImageThinkingLevel,
    NovelImageNoiseSchedule,
    NovelImageSampler,
    NovelTextToImageRequest,
)

GeminiImageRequest(
    model=GeminiImageModel.GEMINI_NANO_BANANA_2_1,
    prompt="A glass greenhouse at sunrise",
    image_size=GeminiImageSize.K2,
    thinking_level=GeminiImageThinkingLevel.MEDIUM,
    google_search=True,
)
FluxImageRequest(prompt="A glass greenhouse", aspect_ratio=FluxImageAspectRatio.RATIO_16_9)
NovelTextToImageRequest(
    prompt="A glass greenhouse",
    sampler=NovelImageSampler.EULER_ANCESTRAL,
    noise_schedule=NovelImageNoiseSchedule.KARRAS,
    quality_toggle=True,
)
```

Grok image generation and editing are asynchronous and share the same job handle:

```python
from dai_media import GrokImageRequest, GrokImageEditRequest

with DaiMediaClient(api_key=os.environ["DAI_API_KEY"]) as client:
    job = client.images.grok.generate(
        GrokImageRequest(prompt="A glass greenhouse at sunrise", aspect_ratio="16:9")
    )
    result = client.jobs.wait(job)
    print(result.status, result.url, [asset.url for asset in result.assets])
```

Use `client.images.grok.edits(GrokImageEditRequest(..., images=(source_url,)))` for image edits.

## Job results

Every async submission returns a `MediaJobHandle` (`job_id` plus the submit `raw`). Poll it with `client.jobs.fetch(handle)` or block with `client.jobs.wait(handle, WaitOptions(...))`. Both call `GET /api/ai/jobs/{job_id}` (`refresh=true` by default; pass `refresh=False` to reuse the persisted snapshot) and return a `MediaJobResult` exposing the unified fields:

`job_id`, `kind` (`image` | `video` | `audio`), `status` (`submitted` | `running` | `succeeded` | `failed` | `canceled` | `expired`), `state` (normalized terminal class), `progress_pct`, `capability_code`, `model_code`, `url`, `asset_id`, `assets` (tuple of `JobAsset`), `text`, `transcript`, `elapsed_ms`, `settled_usd`, `error_message`, `refresh_error`, `request_id`, and `raw`.

Only `succeeded` jobs carry `url`/`assets`; failures carry `error_message`. `settled_usd` is `None` until the job reaches a terminal status. A non-null `refresh_error` means the upstream refresh failed and the rest of the payload is the last persisted snapshot.

## Video and audio jobs

```python
from dai_media import GeminiVideoAspectRatio, GeminiVideoModel, GeminiVideoRequest, WaitOptions

with DaiMediaClient(
    api_key=os.environ["DAI_API_KEY"],
    base_url="https://gateway.example.com/dai",
) as client:
    job = client.videos.gemini.generate(
        GeminiVideoRequest(
            prompt="A glass greenhouse at sunrise",
            model=GeminiVideoModel.VEO_3_1_FAST,
            aspect_ratio=GeminiVideoAspectRatio.RATIO_16_9,
        )
    )
    result = client.jobs.wait(job, WaitOptions(poll_interval=2.0, max_wait=1200.0))
    print(result.state, result.assets)
```

`GeminiVideoModel.OMNI_1_1_FLASH` is billed per clip: `720p` (default) / `1080p` / `4k` resolutions, 4/6/8/10 second durations (default 6), `generation_type="frame"` (1 image) or `"reference"` (1 or 3 images), and at most one `reference_videos` entry (`GEMINI_VIDEO_MAX_REFERENCE_VIDEOS`). It does not support `extend` or `negative_prompt`.

`GeminiVideoModel.OMNI_1_2_FLASH` adds `360p` on top of the same `4k` resolution, 3–15 second durations, and the `edit`/`extend` generation types plus `negative_prompt`.

Grok Imagine Video 1.5 requires exactly one public source image URL:

```python
from dai_media import GrokVideoAspectRatio, GrokVideoRequest, GrokVideoResolution

with DaiMediaClient(api_key=os.environ["DAI_API_KEY"]) as client:
    job = client.videos.grok.generate(
        GrokVideoRequest(
            prompt="The subject turns toward the sunrise",
            refer_images=("https://cdn.example.com/source.png",),
            aspect_ratio=GrokVideoAspectRatio.RATIO_16_9,
            video_length=5,
            resolution_name=GrokVideoResolution.P720,
        )
    )
    result = client.jobs.wait(job)
    print(result.state, result.assets)
```

Use `AsyncDaiMediaClient` for async applications; its resource methods and `jobs.wait` have the same contract. Suno music uses `client.audio.suno.music(...)` with `mv=SunoMusicModel.CHIRP_V5`.

## Speech (text to speech)

`client.audio.speech(...)` calls `POST /v1/audio/speech` and returns the whole audio clip in one shot — v1 is not streaming. The endpoint has no JSON body on success, so the billing metadata rides on response headers and the SDK returns it next to the bytes:

```python
from dai_media import (
    OPENAI_SPEECH_VOICES,
    DaiMediaClient,
    OpenAiSpeechModel,
    OpenAiSpeechRequest,
)

with DaiMediaClient(api_key=os.environ["DAI_API_KEY"], timeout=120.0) as client:
    result = client.audio.speech(
        OpenAiSpeechRequest(
            model=OpenAiSpeechModel.KOKORO_82M,
            input="A glass greenhouse at sunrise.",
            voice=OPENAI_SPEECH_VOICES["kokoro-82m"][0],  # af_bella
        )
    )
    print(result.content_type, result.characters, result.usage_id)
    with open("speech.mp3", "wb") as audio:
        audio.write(result.bytes)
```

`SpeechResult` carries `bytes`, `content_type`, `characters` (`x-dai-characters`, the billed input character count), `usage_id` (`x-dai-usage-id`, the usage log id) and `request_id`. Everything except `bytes` is `None` when that header is missing. A non-2xx answer is still the JSON error envelope, so it raises `ApiError` instead of handing error text back as audio.

The request is never retried for you: the upstream bills once it dispatches, so a retry would double charge. `stream_format` only accepts `"audio"` (`OpenAiSpeechStreamFormat.AUDIO`); the `input` caps stay server-side (`OPENAI_SPEECH_MAX_INPUT_CHARS` 4096, `OPENAI_SPEECH_CSM_1B_MAX_INPUT_CHARS` 200 on `csm-1b`) so an over-long `input` comes back as a 400 rather than a client-side exception. `AsyncDaiMediaClient.audio.speech` is the awaitable twin, and `examples/openai_speech.py` is a runnable version of the snippet above.

## Decisions (Jev)

`client.decisions.create(...)` calls `POST /api/ai/systemone/v1/decisions`, which forwards to TypeSafe Jev. Jev is not a chat model: you send a text `state` plus 1 to 64 `questions` and get probabilities back, and the backend bills each request as one unit instead of per token.

```python
from dai_media import DaiMediaClient

with DaiMediaClient(api_key=os.environ["DAI_API_KEY"]) as client:
    result = client.decisions.create(
        state="I was charged twice.",
        questions={
            "billing": {"type": "noul", "instructions": "Is this a billing issue?"},
            "refund": {"type": "noul"},
        },
    )
    print(result["answers"]["billing"]["noul"], result["usage"]["input_tokens"])
```

The result is a plain dict typed as `DecisionResult`: `model`, `answers` (each with the question `type` and its `noul` probability, `None` for question types that carry no probability), and `usage` (`input_tokens`, `output_tokens`). `DecisionQuestion`, `DecisionAnswer` and `DecisionUsage` type the nested pieces. `model` defaults to `jev` server-side, so pass `SystemoneDecisionModel.JEV` (or any raw string) only when another decision model is published; `SYSTEMONE_DECISION_MODELS` is the catalogue set. The request body stays under 30,000 bytes. `AsyncDaiMediaClient.decisions.create` is the awaitable twin.

## Model catalog and parameter helpers

`client.catalog.models()` calls the public `GET /api/system/public/gateway-models` and returns `CatalogModel` objects, each with its `parameters` (`CatalogParameter`: `key`, `label`, `kind`, `required`, `options`, `default_value`, `min`/`max`/`step`, `value_type`, `role`, `open`). Build model pickers and forms from it instead of a compiled-in list; `AsyncDaiMediaClient.catalog.models()` is the awaitable twin. `value_type` is `None` where the server has not verified the JSON type, and an unknown value is read as `None`.

Three helpers work on a `CatalogModel` or a list of `CatalogParameter`: `parameter_defaults(model)` returns the typed default of every parameter that has one, `coerce_parameter(parameter, value)` converts one form input (returns a `CoercedParameter` with `status` `"value"`, `"absent"` or `"invalid"`), and `validate_parameters(model, values)` returns `.values` (accepted, typed) and `.issues` (`ParameterIssue(key, code)` with `code` `required`, `type`, `not_allowed` or `out_of_range`). They cover the form side only; the typed request classes still build the request body. The rules are shared by all SDKs (`sdks/spec/model-params.md`).

```python
from dai_media import DaiMediaClient, parameter_defaults, validate_parameters

with DaiMediaClient(api_key=os.environ["DAI_API_KEY"]) as client:
    model = next(m for m in client.catalog.models() if m.model_code == "gpt-image-2")
    form = {**parameter_defaults(model), "quality": "high"}  # fill a UI from model.parameters
    result = validate_parameters(model, form)
    print(result.values, [(i.key, i.code) for i in result.issues])
```

## Errors and security

`ApiError` includes HTTP status, D.AI message, upstream type/code, `x-request-id`, and a bounded body preview. Billed POST requests are never automatically retried. Do not put an account-owned long-lived API key in a browser or public mobile binary; use a backend or a scoped token service.
