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, and Google has shut down Imagen in the Gemini API. The default remains gpt-image-1.5; no model is silently substituted. Legacy provider failures return an API error.
Installation
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.
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.,
1920x1080or1536x1024.txtin file names) to the closest supported native aspect ratios when routing to Imagen. Forgpt-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.txtautomatically with individual scene prompts. - Automatic WebP Conversion: Generates and optimizes WebP formats (
featured.webpandthumbnail.webpwith max-dimension constraints). - Standardized Output Filenames: Output filenames are derived from the prompt file base:
<prefix>-prompt.txtor<prefix>-prompt-<size>.txtbecome<prefix>.<ext>. - Optional WEBP Copy: Use
--webpto create an additional lossless<prefix>.webpcopy alongside the main output. - Thumbnail Generation: Use
--thumbnailto create<prefix>-thumbnail.webpresized to max 768px with 75% quality. - Dry Run: Use
--dry-runto log planned file generation and conversions without API calls or file writes. - Recursive File Patterns:
--file-patternaccepts glob patterns including**for recursive discovery (e.g.--file-pattern "**/*-prompt-*.txt" root-folder).
Usage
Generate illustration for a story folder:
generate-image /path/to/story_folder --model dall-e-3 --webp --thumbnail
Process specific prompt files:
generate-image --file /path/to/prompt-1536x1024.txt --model imagen-4-ultra
Dry-run example (logs planned outputs without API calls or file writes):
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: 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:
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. The configured compatibility date selects the Python Workers runtime independently of the host Python version. From a fresh checkout:
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):
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:
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:
npm run release -- --env staging --account-id <account-id>
npm run release -- --env production --account-id <account-id>
Each real release:
- Validates source target, account, distinct Worker names and bearer tokens. Acquires an exclusive
.release.lockand creates a fresh.release/<environment>/build-*snapshot. - Verifies authentication/Worker readiness by listing remote secret names; requires
OPENAI_API_KEYand/orGEMINI_API_KEY. It never reads secret values or installs secrets. - Copies shared Python source under the snapshot's
src/directory, flattens the selected Wrangler environment withsrc/worker.pyas 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. - Validates the new target and dependency output, hashes the snapshot, and runs pinned Wrangler
deploy --dry-runagainst it. - 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:
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).
Metadata
Release files for tlnw-generate-image 0.7.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tlnw_generate_image-0.7.0.tar.gz | 32.3 kB | With provenance | Details for tlnw_generate_image-0.7.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tlnw_generate_image-0.7.0-py3-none-any.whl | Python 3 | none | any | Details for tlnw_generate_image-0.7.0-py3-none-any.whl |
Total release size: 58.6 kB
Release files / tlnw_generate_image-0.7.0.tar.gz
| Download URL | tlnw_generate_image-0.7.0.tar.gz |
|---|---|
| Size | 32.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
7756e2f4d4f7b6403ce98d22f1223a4df8a5312152d11de0ae9199bd04977d92
|
|
BLAKE2b-256 checksum How to use checksums |
59ed872c7cbc8807bd6c6cd1dbfe5ed4a746ab126db7539f54465f06efe50e13
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.
Transparency logRelease files / tlnw_generate_image-0.7.0-py3-none-any.whl
| Download URL | tlnw_generate_image-0.7.0-py3-none-any.whl |
|---|---|
| Size | 26.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4247bfda97ac8e4f6293ec8c221e47fb742424a8508e74b8ff56638272fdae97
|
|
BLAKE2b-256 checksum How to use checksums |
7b892fe1a92864857380a777552476eb727f59f040e00a6a8fb31f857dbda0ca
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.
Transparency logSecurity for tlnw-generate-image 0.7.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for tlnw_generate_image-0.7.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 27, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.