Metadata-Version: 2.4
Name: tlnw-generate-image
Version: 0.7.0
Summary: Generate illustrations and images dynamically using OpenAI DALL-E and Google Imagen models.
Author-email: Tellers Network <admin@tlnw.uk>
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: openai>=1.0.0
Requires-Dist: requests>=2.25.0
Requires-Dist: pillow>=9.0.0
Requires-Dist: python-dotenv>=0.19.0
Provides-Extra: google
Requires-Dist: google-genai>=1.0.0; extra == "google"

# Tellers Network Image Generation Tool (`tlnw-generate-image`)

`tlnw-generate-image` provides a Python image-generation library and CLI, plus an authenticated web API deployed as a Cloudflare Python Worker. The library and API share the asynchronous, in-memory `generate_image()` function, including model sizing, master prompts, output conversion, WebP copies, and thumbnails. The existing file-based CLI and `tlnw_generate_image.core` API remain available.

Provider adapters retain GPT Image, DALL-E, and Imagen model routing. Availability depends on the provider: [OpenAI has retired DALL-E and GPT Image 1](https://developers.openai.com/api/reference/resources/images/methods/generate), and [Google has shut down Imagen in the Gemini API](https://ai.google.dev/gemini-api/docs/imagen). The default remains `gpt-image-1.5`; no model is silently substituted. Legacy provider failures return an API error.

## Installation
```bash
pip install tlnw-generate-image
```

For the existing Google SDK-based file pipeline, install `tlnw-generate-image[google]`.

## Python library

Set `OPENAI_API_KEY` or `GEMINI_API_KEY` in your process environment, or pass `api_key=` explicitly. Generation raises `ValueError`, `ConfigurationError`, or `ProviderError`; it does not exit the process.

```python
import asyncio
from pathlib import Path
from tlnw_generate_image import generate_image

async def main():
    result = await generate_image(
        "A fox reading beneath a tree",
        model="gpt-image-1.5",
        master_prompt="Watercolor illustration.",
        orientation="landscape",
        quality="high",
        format="PNG",
        webp=True,
        thumbnail=True,
    )
    Path("fox.png").write_bytes(result.image.data)
    Path("fox-thumbnail.webp").write_bytes(result.thumbnail.data)

asyncio.run(main())
```

`GenerationResult` contains `model`, resolved `size`, normalized `quality`, `image`, and optional `webp` and `thumbnail` images. Each image has `data` (bytes), `content_type`, `width`, and `height`. `result.to_dict()` returns the same base64 JSON structure as the API. Reference images are passed as `reference_images=[Path("reference.png").read_bytes()]` for GPT Image models. These interfaces never read server-side paths or write files during generation; the caller chooses where to save results.

## Features
- **Extensible OOP Provider Architecture**: Clean separation of model providers (`DalleProvider`, `GptImageProvider`, `GoogleImagenProvider`) with registry-based dynamic routing.
- **Intelligent Size & Quality Preset Mapping**: Standardizes orientation presets (`landscape`, `portrait`, `square`) and qualities, automatically converting them to provider-native formats: aspect ratios (e.g. `"16:9"`) for Google Imagen, or concrete dimensions (e.g. `"1792x1024"`) for OpenAI.
- **Custom Dimension Resolution & Validation**: Automatically maps exact resolution values (e.g., `1920x1080` or `1536x1024.txt` in file names) to the closest supported native aspect ratios when routing to Imagen. For `gpt-image-2`, it validates custom resolution constraints locally (divisibility by 16, aspect ratios between 1:3 and 3:1, and a maximum resolution edge of 3840px with a minimum edge of 2160px).
- **Auto-resolution of Output Sizing**: Extracts target sizes from prompt filename trailing suffixes (e.g., `-1536x1024.txt`).
- **Prompt Composition**: Concatenates local directory `illustration-master-prompt.txt` automatically with individual scene prompts.
- **Automatic WebP Conversion**: Generates and optimizes WebP formats (`featured.webp` and `thumbnail.webp` with max-dimension constraints).
- **Standardized Output Filenames**: Output filenames are derived from the prompt file base: `<prefix>-prompt.txt` or `<prefix>-prompt-<size>.txt` become `<prefix>.<ext>`.
- **Optional WEBP Copy**: Use `--webp` to create an additional lossless `<prefix>.webp` copy alongside the main output.
- **Thumbnail Generation**: Use `--thumbnail` to create `<prefix>-thumbnail.webp` resized to max 768px with 75% quality.
 - **Dry Run**: Use `--dry-run` to log planned file generation and conversions without API calls or file writes.
 - **Recursive File Patterns**: `--file-pattern` accepts glob patterns including `**` for recursive discovery (e.g. `--file-pattern "**/*-prompt-*.txt" root-folder`).
 

## Usage
Generate illustration for a story folder:
```bash
generate-image /path/to/story_folder --model dall-e-3 --webp --thumbnail
```

Process specific prompt files:
```bash
generate-image --file /path/to/prompt-1536x1024.txt --model imagen-4-ultra
```

Dry-run example (logs planned outputs without API calls or file writes):
```bash
generate-image /path/to/story_folder --dry-run --file-pattern "**/*-prompt-*.txt"
```

## Authenticated web API

The Worker follows [Cloudflare's Python Workers entrypoint and packaging model](https://developers.cloudflare.com/workers/languages/python/): `Default(WorkerEntrypoint)`, the `python_workers` compatibility flag, and dependencies vendored by `pywrangler sync`. Outbound requests use native asynchronous `workers.fetch`; image conversion uses Pillow in memory. Cloudflare-specific imports stay in `worker.py`.

All endpoints require `Authorization: Bearer <token>`. Each environment has a different hardcoded `API_BEARER_TOKEN` under `env.<environment>.vars` in `wrangler.jsonc`, as the initial authentication mechanism. Read or rotate the token there; releases redact it from child-process output. This is a shared token for each environment, with no user database or token issuance endpoint. Missing authentication configuration fails closed.

`POST /v1/images/generations` accepts `Content-Type: application/json`:

```bash
curl https://<worker-url>/v1/images/generations \
  -H "Authorization: Bearer <token-from-selected-wrangler-environment>" \
  -H "Content-Type: application/json" \
  --data '{"prompt":"A fox reading beneath a tree","orientation":"landscape","webp":true,"thumbnail":true}'
```

| JSON option | Default / meaning |
|---|---|
| `prompt` | Required nonempty text; combined prompt limit 32,000 characters |
| `model` | `gpt-image-1.5`; retains GPT Image, DALL-E, and Imagen routing |
| `master_prompt` | Optional text prepended to `prompt` |
| `orientation` | `square`, `landscape`, or `portrait`; default `square` |
| `size` | Optional positive `WIDTHxHEIGHT`; Imagen also accepts a supported aspect ratio |
| `quality` | `low`, `medium`, `high`, `standard`, `hd`, or `auto`; normalized per model |
| `format` | `PNG` (default), `JPEG`, `JPG`, or `WEBP` |
| `webp` | Boolean; add a lossless WebP copy |
| `thumbnail` | Boolean; add a WebP thumbnail, maximum dimension 768 px, quality 75 |
| `reference_images` | Up to four raw base64 PNG/JPEG/WebP strings for GPT Image edits; no paths, URLs, or data-URL prefixes |

The response contains `model`, `size`, `quality`, and `image: {b64_json, content_type, width, height}`. Optional `webp` and `thumbnail` fields have the same image structure. Decode `b64_json` to obtain image bytes. Requests return the completed result; no files or job results are persisted.

`GET /health` returns `{"status":"ok"}` with valid authentication. It verifies API reachability, not provider credentials or model access.

Errors use `{"error":"..."}`: 400 invalid JSON/options, 401 invalid bearer token, 404 unknown route, 405 wrong method, 413 body over 8 MiB, 415 wrong content type, 503 missing API/provider configuration, and 502 provider/network/image failures. Provider response bodies and keys are never returned. Responses use `Cache-Control: no-store`; 401 includes `WWW-Authenticate: Bearer`. Encoded provider images are limited to 20 MiB and 16 megapixels. Browser CORS access is not enabled; use a server-side client or same-origin proxy.

## Development and checks

Prerequisites: Python 3.12+ for tooling (the library still supports Python 3.10+), Node.js 22+, and [uv](https://docs.astral.sh/uv/). The configured compatibility date selects the Python Workers runtime independently of the host Python version. From a fresh checkout:

```bash
npm ci
uv sync --locked --group workers
uv run --locked pytest -q
npm test
```

`uv.lock` pins host/tool dependencies. `workers/pyproject.toml` declares the minimal Worker dependencies (Pillow; the CLI supplies the runtime SDK), and `workers/pylock.toml` pins their Pyodide builds. Provider SDKs remain available to the file-based library/CLI and are imported lazily, so they are not needed in the Worker. To intentionally refresh the Worker lock after changing dependencies or compatibility settings, run `npm run lock:worker`, then review and commit `workers/pylock.toml`. Keep `uv.lock` current with `uv lock` when editing the root `pyproject.toml`.

For local development, put provider credentials in the ignored `.dev.vars.staging` (or `.dev.vars.production`):

```dotenv
OPENAI_API_KEY=<provider-key>
```

Then run `npm run dev -- --env staging`. This builds an isolated snapshot and starts Wrangler locally at `http://localhost:8787`. Authenticate using the staging bearer token from `wrangler.jsonc`. Only the selected `.dev.vars.<environment>` is copied into the development snapshot. Restart this command after source changes; the isolated snapshot does not watch the original sources. The local server holds the release lock until stopped.

## Cloudflare release procedure

Select **staging or production explicitly**; neither is a default. Set `CLOUDFLARE_ACCOUNT_ID` or supply `--account-id <32-character-account-id>`. An account pinned in configuration cannot be overridden with a conflicting CLI account. Authenticate Wrangler using `CLOUDFLARE_API_TOKEN` (CI) or the local Wrangler login flow. Target Workers are `tlnw-generate-image-staging` and `tlnw-generate-image-production` on workers.dev unless you configure environment-specific routes.

Before the first real release, the cloud operator must install at least one provider secret for the selected Worker, using the pinned local Wrangler. For example, after setting the account and Wrangler authentication:

```bash
node node_modules/wrangler/bin/wrangler.js secret put OPENAI_API_KEY --config wrangler.jsonc --env staging
# Optional alternative provider:
node node_modules/wrangler/bin/wrangler.js secret put GEMINI_API_KEY --config wrangler.jsonc --env staging
```

Use `--env production` for production setup. Wrangler may offer to create the named Worker when installing its first secret. Provider keys are separate from the hardcoded API bearer token. A request for a provider whose key is absent returns 503.

These commands are alternatives, each targeting one environment:

```bash
npm run release -- --env staging --account-id <account-id>
npm run release -- --env production --account-id <account-id>
```

Each real release:

1. Validates source target, account, distinct Worker names and bearer tokens. Acquires an exclusive `.release.lock` and creates a fresh `.release/<environment>/build-*` snapshot.
2. Verifies authentication/Worker readiness by listing remote secret names; requires `OPENAI_API_KEY` and/or `GEMINI_API_KEY`. It never reads secret values or installs secrets.
3. Copies shared Python source under the snapshot's `src/` directory, flattens the selected Wrangler environment with `src/worker.py` as its entrypoint, and vendors dependencies from the Worker manifest/lock using the pinned local Python Workers CLI. Build virtual environments stay outside module discovery. Dependency resolution must preserve the committed Pyodide lock.
4. Validates the new target and dependency output, hashes the snapshot, and runs pinned Wrangler `deploy --dry-run` against it.
5. Rechecks source and deployment files, then deploys the same validated snapshot. Flattened configs receive no second `--env`; inherited selectors are cleared and the account is pinned in both config and child environment.

The command stops at the first failure, reports its stage and preserves the child exit code. It releases only its own lock. A preexisting lock blocks a release; it is never deleted automatically. Do not edit inputs or run other builds during release. Snapshots are retained locally for inspection and ignored by Git; they contain the configured bearer token. On deployment failure the remote outcome may be uncertain: inspect the selected Worker before retrying. No automated rollback occurs. The command performs no migrations, resource provisioning, secret installation, or PyPI publication.

| Mode | Actions |
|---|---|
| `--dry-run` | Source preflight and activity printout only; no subprocess, lock, build, or network |
| `--check` | Fresh build, target validation, and Wrangler bundle dry-run; no remote secret listing or deployment |
| no mode flag | Remote preflight, fresh build, validation, bundle check, and live deployment |

The modes are mutually exclusive. `--check` verifies local bundling, not cloud credentials, provider access, or successful image generation. A local check can use a synthetic account ID:

```bash
npm run release -- --env staging --account-id 00000000000000000000000000000000 --dry-run
npm run release -- --env staging --account-id 00000000000000000000000000000000 --check
```

For review, developers run the Python/Node tests and optional local bundle check above; no UI check, migration, secret setup, or deployment is required. After an authorized live deployment, the cloud operator checks `GET /health` with the selected token (expect 200), repeats without a token (expect 401), then optionally sends the generation request above with a provider key/model available to that environment (expect base64 image output; this incurs provider usage).
