Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
release(v4.19.14): FLUX 3 Klein image generation
mrbizarro43c2b9abd7ed
diff --git a/.gitignore b/.gitignoreindex 939bb0a..b9c2f00 100644--- a/.gitignore+++ b/.gitignore@@ -169,3 +169,6 @@ state_studio/yue2-mlxnode_modules++# FLUX 3 has a separate MLX environment.+/flux3-worker/diff --git a/README.md b/README.mdindex dccc173..a6b91b5 100644--- a/README.md+++ b/README.md@@ -14,11 +14,11 @@Phosphene is a free, open-source AI video generator that runs locally on a Mac with M1, M2, M3, M4 or M5.It runs **LTX-2.5** and **MiniMax H3 (Hailuo H3)** for text-to-video and image-to-video with sound in the same pass,-**YuE2** for songs from lyrics, and **Qwen-Image-Edit** and **FLUX.2** for images. It installs with one click through Pinokio+**YuE2** for songs from lyrics, and **FLUX 3 Klein**, **Qwen-Image-Edit** and **FLUX.2** for images. It installs with one click through Pinokioand is built on Apple's MLX: no CUDA, no cloud GPU, no API key, no credits and no watermark.Your prompts, pictures and videos never leave your Mac.-**Current release: v4.19.13.** Made by Mr Bizarro.+**Current release: v4.19.14.** Made by Mr Bizarro.## Why Phosphene@@ -68,7 +68,7 @@ Its licence excludes the EU, UK, South Korea and US.### Remix your own footage-- **Motion Control:** copy the motion, camera move and pose of a clip you give it while your prompt paints a new subject and scene.+- **Motion Control:** copy the motion, camera move and pose of a clip you give it while your prompt paints a new subject and scene ([guide](docs/MOTION_CONTROL.md)).- **Ingredients:** compose 2–8 reference pictures (a character, a prop, a place) into one clip.- **Colorize:** turn black-and-white footage into colour.@@ -88,8 +88,9 @@ Make another take, cover a song, or get the score. About 11 GB, installed inside</p><p align="center"><sub>“Neon Mile”, a Music Studio song sung with MiniMax H3, and “The bust sings”, LTX-2.5 lip-sync</sub></p>-### AI image editing with Qwen-Image-Edit and FLUX.2+### AI images with FLUX 3 Klein, Qwen-Image-Edit and FLUX.2+New in 4.19.14: FLUX 3 Klein by Black Forest Labs makes an image from a sentence in about 50 seconds on an M4 Max, or edits the reference pictures you give it.Qwen-Image-Edit and FLUX.2 (via mflux) make images and edit them in words, like “make the jacket red”,with up to three reference pictures. Ideogram 4 puts readable words on a picture. Send any still straight to video.@@ -151,6 +152,7 @@ Phosphene installs with one click through Pinokio (pinokio.computer), a free appTo update, press **Update** in Pinokio, then restart Phosphene.The [docs](https://phosphene.video/docs/?utm_source=github&utm_medium=readme&utm_campaign=repo&utm_content=docs) have the step-by-step install, troubleshooting and every feature in detail.+To install by hand instead, follow the [manual install](docs/MANUAL_INSTALL.md).Linux on Apple Silicon (`docs/LINUX.md`) is maintained by @joshuaswarren on a best-effort basis.## What's coming@@ -217,6 +219,7 @@ Contributors are credited in the release notes. See CONTRIBUTING.md.- Lightricks for LTX-Video 2.x, and @dgrauet for ltx-2-mlx, the MLX port Phosphene builds on.- MiniMax for Hailuo H3, and Apple ML research for MLX.- LightX2V for lightx2v v1.3, the adapter for Best on High; TaoLive (TaoMate-H3) and @kijai for the 3-step Fast adapter.+- Black Forest Labs for FLUX 3 Klein, and mflux-community for its MLX conversions.- @filipstrand for mflux; Multimodal Art Projection for YuE2 and @vanch007 for its MLX port.- mlx-community for Gemma on MLX, and @cocktailpeanut for Pinokio.diff --git a/VERSION b/VERSIONindex 85f7360..5f89740 100644--- a/VERSION+++ b/VERSION@@ -1 +1 @@-4.19.13+4.19.14diff --git a/data/flux3_models.json b/data/flux3_models.jsonnew file mode 100644index 0000000..bcb7379--- /dev/null+++ b/data/flux3_models.json@@ -0,0 +1,444 @@+{+ "distilled-q8": {+ "repo": "mflux-community/flux-3-image-klein-mflux-q8",+ "revision": "7e46237dea3999a9792959f5e000aeb1b9f9e7df",+ "bytes": 9918472341,+ "files": [+ {+ "path": "README.md",+ "size": 2844,+ "sha256": null+ },+ {+ "path": "manifest.json",+ "size": 78,+ "sha256": null+ },+ {+ "path": "text_encoder/0.safetensors",+ "size": 2145931485,+ "sha256": "600652856574e9f347866a481ab03ecf8a99086e7a84d0fcea5c1be339ea9032"+ },+ {+ "path": "text_encoder/1.safetensors",+ "size": 1699235116,+ "sha256": "04fd5c383b8b41c3e0882c93d0def127370aa985847f24678945defdd6723707"+ },+ {+ "path": "text_encoder/chat_template.jinja",+ "size": 5292,+ "sha256": null+ },+ {+ "path": "text_encoder/model.safetensors.index.json",+ "size": 45636,+ "sha256": null+ },+ {+ "path": "text_encoder/tokenizer.json",+ "size": 11422650,+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"+ },+ {+ "path": "text_encoder/tokenizer_config.json",+ "size": 692,+ "sha256": null+ },+ {+ "path": "transformer/0.safetensors",+ "size": 2134962964,+ "sha256": "35978e837374f61578ff7ab5cbb7084e24f2ff2fb03b5f2c11e007f1d34a7c4a"+ },+ {+ "path": "transformer/1.safetensors",+ "size": 2145827275,+ "sha256": "c163baf4a4ab7ea8920a666557c8e711eb5077b8e5120a0c44af08ace7e4f1ee"+ },+ {+ "path": "transformer/2.safetensors",+ "size": 1614802516,+ "sha256": "70c523328bec015552c712e803ff4982b712bf2876c368151b7dbde0eaa5026c"+ },+ {+ "path": "transformer/model.safetensors.index.json",+ "size": 61760,+ "sha256": null+ },+ {+ "path": "vae/0.safetensors",+ "size": 166156486,+ "sha256": "94068882f83f537035d4353c19a8fa0d0b9d0294ee3ad8834ef5e1eecc960861"+ },+ {+ "path": "vae/model.safetensors.index.json",+ "size": 17547,+ "sha256": null+ }+ ]+ },+ "distilled-q6": {+ "repo": "mflux-community/flux-3-image-klein-mflux-q6",+ "revision": "ace05578b60f0185b0c1212d23fb13616d88d6c7",+ "bytes": 7626137483,+ "files": [+ {+ "path": "README.md",+ "size": 2844,+ "sha256": null+ },+ {+ "path": "manifest.json",+ "size": 78,+ "sha256": null+ },+ {+ "path": "text_encoder/0.safetensors",+ "size": 2141676588,+ "sha256": "f7b4b822cfa46ce3f90104c46d2131a93d0b4904bfcf4386c6c2eabd2ae002fc"+ },+ {+ "path": "text_encoder/1.safetensors",+ "size": 798847236,+ "sha256": "1782697b7872c06f32aeb8ef104d4e5dae7c130982700a775b616e66f2c53d81"+ },+ {+ "path": "text_encoder/chat_template.jinja",+ "size": 5292,+ "sha256": null+ },+ {+ "path": "text_encoder/model.safetensors.index.json",+ "size": 45636,+ "sha256": null+ },+ {+ "path": "text_encoder/tokenizer.json",+ "size": 11422650,+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"+ },+ {+ "path": "text_encoder/tokenizer_config.json",+ "size": 692,+ "sha256": null+ },+ {+ "path": "transformer/0.safetensors",+ "size": 2131045447,+ "sha256": "c4527024102c044a51ee7b3baab90e9f50fcabdeab2a47e4c4dd037fd9de8b3e"+ },+ {+ "path": "transformer/1.safetensors",+ "size": 2139354166,+ "sha256": "dc9f263a727653cc6dd4c9f002dcdfb6a2ccbed893016bf2b36b225718e34fd9"+ },+ {+ "path": "transformer/2.safetensors",+ "size": 238025357,+ "sha256": "61de173e22c8f76af20e96b5037d53355b7ce8b256bee0d07c7b254f0d87dc5d"+ },+ {+ "path": "transformer/model.safetensors.index.json",+ "size": 61760,+ "sha256": null+ },+ {+ "path": "vae/0.safetensors",+ "size": 165632190,+ "sha256": "c386146c9a2a5a0f12da2a7a184b8b8352f4ec88c00d58dc0c94d536a0247116"+ },+ {+ "path": "vae/model.safetensors.index.json",+ "size": 17547,+ "sha256": null+ }+ ]+ },+ "distilled-q4": {+ "repo": "mflux-community/flux-3-image-klein-mflux-q4",+ "revision": "79c0034de040c460e9685bf0127f40af042a2abe",+ "bytes": 5333802766,+ "files": [+ {+ "path": "README.md",+ "size": 2956,+ "sha256": null+ },+ {+ "path": "manifest.json",+ "size": 78,+ "sha256": null+ },+ {+ "path": "text_encoder/0.safetensors",+ "size": 2035881396,+ "sha256": "d6621c1001e0d81a0bb5a9405610fe78d3aff1658ded8a851ef2d4906c300e84"+ },+ {+ "path": "text_encoder/chat_template.jinja",+ "size": 5292,+ "sha256": null+ },+ {+ "path": "text_encoder/model.safetensors.index.json",+ "size": 45636,+ "sha256": null+ },+ {+ "path": "text_encoder/tokenizer.json",+ "size": 11422650,+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"+ },+ {+ "path": "text_encoder/tokenizer_config.json",+ "size": 692,+ "sha256": null+ },+ {+ "path": "transformer/0.safetensors",+ "size": 2144245413,+ "sha256": "2960aeb9ae939b9a61e0e500586e649e60b79688ff94f5f8d3387a9dc274bbdf"+ },+ {+ "path": "transformer/1.safetensors",+ "size": 977011458,+ "sha256": "82c98e6e30cd3acdfb7d975358db76206a9cee8f3de22ff725f9668bf8833880"+ },+ {+ "path": "transformer/model.safetensors.index.json",+ "size": 61760,+ "sha256": null+ },+ {+ "path": "vae/0.safetensors",+ "size": 165107888,+ "sha256": "9c3376cde5b6f5166fbd4cead9d9e5d84f11702e2865149a2828378a14671b4b"+ },+ {+ "path": "vae/model.safetensors.index.json",+ "size": 17547,+ "sha256": null+ }+ ]+ },+ "base-q8": {+ "repo": "mflux-community/flux-3-image-klein-base-mflux-q8",+ "revision": "f4555b2367dcad19c4dee1ddfb45ec1aeccdb857",+ "bytes": 9907608869,+ "files": [+ {+ "path": "README.md",+ "size": 3071,+ "sha256": null+ },+ {+ "path": "manifest.json",+ "size": 78,+ "sha256": null+ },+ {+ "path": "text_encoder/0.safetensors",+ "size": 2145931485,+ "sha256": "600652856574e9f347866a481ab03ecf8a99086e7a84d0fcea5c1be339ea9032"+ },+ {+ "path": "text_encoder/1.safetensors",+ "size": 1699235116,+ "sha256": "04fd5c383b8b41c3e0882c93d0def127370aa985847f24678945defdd6723707"+ },+ {+ "path": "text_encoder/chat_template.jinja",+ "size": 5292,+ "sha256": null+ },+ {+ "path": "text_encoder/model.safetensors.index.json",+ "size": 45636,+ "sha256": null+ },+ {+ "path": "text_encoder/tokenizer.json",+ "size": 11422650,+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"+ },+ {+ "path": "text_encoder/tokenizer_config.json",+ "size": 692,+ "sha256": null+ },+ {+ "path": "transformer/0.safetensors",+ "size": 2124099655,+ "sha256": "80928b5749afe060017fd68516c4d02126aef389170d7c71d68ead5d7b93dcdb"+ },+ {+ "path": "transformer/1.safetensors",+ "size": 2145827275,+ "sha256": "f8492ea3c3c0f21c08f79b411509e736788a3a41b61391655709058abd9b630c"+ },+ {+ "path": "transformer/2.safetensors",+ "size": 1614802516,+ "sha256": "54a7767a81b161d11230726b79d6a9c5b6c42929721e731028d7c938fca35fef"+ },+ {+ "path": "transformer/model.safetensors.index.json",+ "size": 61370,+ "sha256": null+ },+ {+ "path": "vae/0.safetensors",+ "size": 166156486,+ "sha256": "94068882f83f537035d4353c19a8fa0d0b9d0294ee3ad8834ef5e1eecc960861"+ },+ {+ "path": "vae/model.safetensors.index.json",+ "size": 17547,+ "sha256": null+ }+ ]+ },+ "base-q6": {+ "repo": "mflux-community/flux-3-image-klein-base-mflux-q6",+ "revision": "2fcf00e02258e86b599e553db5b2234ae819c7c3",+ "bytes": 7617829897,+ "files": [+ {+ "path": "README.md",+ "size": 3071,+ "sha256": null+ },+ {+ "path": "manifest.json",+ "size": 78,+ "sha256": null+ },+ {+ "path": "text_encoder/0.safetensors",+ "size": 2141676588,+ "sha256": "f7b4b822cfa46ce3f90104c46d2131a93d0b4904bfcf4386c6c2eabd2ae002fc"+ },+ {+ "path": "text_encoder/1.safetensors",+ "size": 798847236,+ "sha256": "1782697b7872c06f32aeb8ef104d4e5dae7c130982700a775b616e66f2c53d81"+ },+ {+ "path": "text_encoder/chat_template.jinja",+ "size": 5292,+ "sha256": null+ },+ {+ "path": "text_encoder/model.safetensors.index.json",+ "size": 45636,+ "sha256": null+ },+ {+ "path": "text_encoder/tokenizer.json",+ "size": 11422650,+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"+ },+ {+ "path": "text_encoder/tokenizer_config.json",+ "size": 692,+ "sha256": null+ },+ {+ "path": "transformer/0.safetensors",+ "size": 2122738024,+ "sha256": "61a546b670faba54520c562f8932466e6ca8f653d6ee7b88c8a5eb19e212f85e"+ },+ {+ "path": "transformer/1.safetensors",+ "size": 2139354166,+ "sha256": "f6febea718c82966c2086205b9740934daa0c3e01ac6ab32a367b023dbc2136b"+ },+ {+ "path": "transformer/2.safetensors",+ "size": 238025357,+ "sha256": "2562fcd7e81e89327bbd52812c3f43507485354bf21f68f2dbbbb419706c68c9"+ },+ {+ "path": "transformer/model.safetensors.index.json",+ "size": 61370,+ "sha256": null+ },+ {+ "path": "vae/0.safetensors",+ "size": 165632190,+ "sha256": "c386146c9a2a5a0f12da2a7a184b8b8352f4ec88c00d58dc0c94d536a0247116"+ },+ {+ "path": "vae/model.safetensors.index.json",+ "size": 17547,+ "sha256": null+ }+ ]+ },+ "base-q4": {+ "repo": "mflux-community/flux-3-image-klein-base-mflux-q4",+ "revision": "2c418dea6a9de1e4f545ace0a974312cdc6a68a9",+ "bytes": 5328051020,+ "files": [+ {+ "path": "README.md",+ "size": 3071,+ "sha256": null+ },+ {+ "path": "manifest.json",+ "size": 78,+ "sha256": null+ },+ {+ "path": "text_encoder/0.safetensors",+ "size": 2035881396,+ "sha256": "d6621c1001e0d81a0bb5a9405610fe78d3aff1658ded8a851ef2d4906c300e84"+ },+ {+ "path": "text_encoder/chat_template.jinja",+ "size": 5292,+ "sha256": null+ },+ {+ "path": "text_encoder/model.safetensors.index.json",+ "size": 45636,+ "sha256": null+ },+ {+ "path": "text_encoder/tokenizer.json",+ "size": 11422650,+ "sha256": "be75606093db2094d7cd20f3c2f385c212750648bd6ea4fb2bf507a6a4c55506"+ },+ {+ "path": "text_encoder/tokenizer_config.json",+ "size": 692,+ "sha256": null+ },+ {+ "path": "transformer/0.safetensors",+ "size": 2143802722,+ "sha256": "484985806f2d4a6937b17cf90dbe623724fe7be32d631a9907056ae290a12a14"+ },+ {+ "path": "transformer/1.safetensors",+ "size": 971702678,+ "sha256": "693207ae0190d8665e5cc86a7a98bba898a19d918053f79a5d752993a39d2025"+ },+ {+ "path": "transformer/model.safetensors.index.json",+ "size": 61370,+ "sha256": null+ },+ {+ "path": "vae/0.safetensors",+ "size": 165107888,+ "sha256": "9c3376cde5b6f5166fbd4cead9d9e5d84f11702e2865149a2828378a14671b4b"+ },+ {+ "path": "vae/model.safetensors.index.json",+ "size": 17547,+ "sha256": null+ }+ ]+ }+}diff --git a/docs/CHANGELOG_4.19.14.md b/docs/CHANGELOG_4.19.14.mdnew file mode 100644index 0000000..1008a92--- /dev/null+++ b/docs/CHANGELOG_4.19.14.md@@ -0,0 +1,9 @@+# Phosphene 4.19.14++- New in Images: **FLUX 3 Klein by Black Forest Labs.** Make an image from a sentence, or add reference pictures and describe the change you want.+- After the first run, each image takes about 50 seconds on an M4 Max with 64 GB. Choose **Animate** on any image to turn it into a video.+- Your first image sets up FLUX 3: about 1 GB for the engine plus the model (7.6 GB at Q6, 9.9 GB at Q8, 5.3 GB at Q4). Stop cancels setup; the next run picks up where it left off.+- FLUX 3 asks you to accept its licence once, before anything downloads. Commercial use of the images is allowed below USD 5 million in yearly revenue; read the terms on first use.+- Needs 32 GB of memory or more. A 24 GB Mac can use Q4 at a small size with one reference.++In Pinokio, press Update, then restart Phosphene. Nothing downloads until you choose FLUX 3.\ No newline at end of filediff --git a/docs/FLUX3.md b/docs/FLUX3.mdnew file mode 100644index 0000000..a6cc323--- /dev/null+++ b/docs/FLUX3.md@@ -0,0 +1,56 @@+# FLUX 3 Klein++Local, free image generation and reference editing with **FLUX 3 Klein by Black Forest Labs**. Added in Phosphene 4.19.14.++In Images, choose FLUX 3 Q8 / Standard. With empty reference slots it makes an image from text; with references it edits or combines them. Describe the whole target scene, including the change. Standard uses the distilled checkpoint at 16 steps. Base Quality is a separate checkpoint with 50 steps and guidance 3.5; it takes longer and is not guaranteed to improve every prompt.++Q8 is the default quality. Q6 reduces the download and memory use; Q4 is for smaller Macs. The first Generate installs the worker and selected weights, showing progress in the job log and Now card. Stop cancels setup, downloads or generation. A later Generate resumes missing downloads. Completed images use the existing gallery sidecar and Animate action for image-to-video.++## Requirements and size++Apple Silicon, macOS 14 or later. Use 32 GB RAM or more for Q8/Q6. A 24 GB Mac can use Q4 at a small size with at most one reference. The UI has three reference slots; the API accepts up to ten on larger Macs. Canvases are limited to one megapixel, with dimensions divisible by 16. Close other memory-heavy apps before rendering.++| Weights | Standard download | Base download | Upstream peak RAM at 1024 square |+|---|---:|---:|---:|+| Q8 | 9.92 GB | 9.91 GB | 22.8 GB |+| Q6 | 7.63 GB | 7.62 GB | 20.6 GB |+| Q4 | 5.33 GB | 5.33 GB | 18.5 GB |++GB in this table means decimal GB. RAM figures are upstream measurements for distilled generation on a 64 GB M4 Pro, not Phosphene measurements. References add memory pressure. While installing or downloading, the worker keeps 5 GiB of the disk free, checks each destination volume and budgets another 3 GiB for its environment. Once installed, rendering only needs room for the new image. Pinned package wheels total about 264 MB to download, excluding Python itself. The environment's actual installed size still needs a fresh-install measurement.++## Isolation and downloads++The studio's existing dependency pins and FLUX.1/Qwen workers are unchanged. FLUX 3 uses Python 3.12, mflux 0.23.0 and MLX 0.32.4 in `flux3-worker/env`. Its complete dependency set is pinned in `scripts/pinokio/flux3_requirements.txt`. The panel reuses its existing installer PATH preparation, scrubs inherited Python/MPS settings and calls `scripts/pinokio/flux3_env.py`. Installation is locked across processes and every first use checks package versions without importing MLX into the studio.++The six mflux-community conversions are public, ungated derivatives of the official Klein models. Repository revisions, file sizes and weight hashes are recorded in `data/flux3_models.json`. Only that pinned file list is fetched. Downloads do not send a Hugging Face token. The worker verifies weight hashes before loading and passes the Base identity explicitly, so a snapshot's hash directory cannot be mistaken for the distilled model.++The worker follows `HF_HUB_CACHE`, then `HF_HOME`, then the normal Hugging Face cache. `PHOSPHENE_FLUX3_ROOT` can place its environment on another volume. No existing weights or outputs are removed. Library images record the checkpoint revision, precision, credit, elapsed render time, MLX peak and process RSS peak. Multi-candidate batches reload the model per image to keep memory bounded; RSS is the process high-water mark to that point.++FLUX.1 and Qwen LoRAs do not apply to FLUX 3. LoRA controls are unavailable for this worker.++## Model licence++The app remains MIT. The model weights use the **FLUX Kommunity License v1.0**, accepted separately before download or use. Commercial output generation requires gross annualized revenue below USD 5 million including affiliates, subject to the full terms. Other commercial terms come directly from Black Forest Labs.++Review outputs before sharing or displaying them, and disclose AI generation where required by law. The full licence and the required attribution notice are kept in [licenses/FLUX-Kommunity-1.0.txt](licenses/FLUX-Kommunity-1.0.txt) and [licenses/FLUX3-NOTICE.txt](licenses/FLUX3-NOTICE.txt), and copied next to downloaded weights. Recipients receive model rights directly from Black Forest Labs. The conversions are modified community models, not official Black Forest Labs products.++## Validation status++Measured on an M4 Max with 64 GB through the studio's own Generate path, launched with Pinokio's environment (2026-10-29), Standard Q6, 16 steps:++| Step | Measured |+|---|---|+| First Generate: engine install, 7.63 GB download, render | 178 s wall |+| Worker environment on disk | 1.1 GB |+| 1280 x 720 image, model loaded per image | 51-52 s (MLX peak 12.1 GB) |+| 1024 x 768 or 768 x 1024 image | 43-46 s (MLX peak 10.3 GB) |+| Reference edit, one reference, 1280 x 720 | 110 s (MLX peak 12.1 GB) |++The worker process stayed under 5.5 GB resident; the MLX peak is the figure to plan memory by. Q8 and Base Quality use the same code path but were not rendered on the test Mac for lack of disk space.++## Sources++- [mflux 0.23.0 FLUX 3 guide](https://github.com/mflux-community/mflux/blob/v.0.23.0/src/mflux/models/flux3/README.md)+- [Pinned mflux dependency manifest](https://github.com/mflux-community/mflux/blob/v.0.23.0/pyproject.toml)+- [mflux-community Q8 conversion](https://huggingface.co/mflux-community/flux-3-image-klein-mflux-q8)+- [Black Forest Labs licence](https://huggingface.co/black-forest-labs/flux-3-image-klein/blob/main/LICENSE.md)diff --git a/docs/licenses/FLUX-Kommunity-1.0.txt b/docs/licenses/FLUX-Kommunity-1.0.txtnew file mode 100644index 0000000..f04ec9f--- /dev/null+++ b/docs/licenses/FLUX-Kommunity-1.0.txt@@ -0,0 +1,123 @@+FLUX Kommunity License v.1.0+++++Black Forest Labs Inc. (“we” or “our” or “Company”) is pleased to make the weights, parameters, and inference code for the FLUX Model (as defined below) freely available for your non-commercial and non-production use or commercial use as a Qualifying User as set forth in this FLUX Kommunity License (“License”). “FLUX Model” includes, individually and collectively, the models denoted as “FLUX x”, where “x” denotes the FLUX Model version number, and made available under the License, as indicated by a license notice that is included in or attached to the work, and their elements which includes algorithms, software, checkpoints, parameters, source code (inference code, evaluation code, and if applicable, fine-tuning code) and any other materials associated with the FLUX AI models made available by Company under this License, including if any, the technical documentation, manuals, and instructions for the use and operation thereof. Note that we may also make available certain elements of what is included in the definition of “FLUX Model” under a separate license, such as the inference code, and nothing in this License will be deemed to restrict or limit any other licenses granted by us in such elements.+++By downloading, accessing, using, Distributing (as defined below), or creating a Derivative (as defined below) of the FLUX Model, you agree to the terms of this License. If you do not agree to this License, then you do not have any rights to access, use, Distribute or create a Derivative of the FLUX Model and you must immediately cease using the FLUX Model. If you are agreeing to be bound by the terms of this License on behalf of your employer or other entity, you represent and warrant to us that you have full legal authority to bind your employer or such entity to this License. If you do not have the requisite authority, you may not accept the License or access the FLUX Model on behalf of your employer or other entity.+++1. Definitions.+++a. “Derivative” means any (i) modified version of the FLUX Model (including but not limited to any customized or fine-tuned version thereof), (ii) work based on the FLUX Model, (iii) any other machine learning model created by transferring the patterns of the weights, parameters, operational patterns, or Output of the FLUX Model or any Derivative thereof to another model, such that the latter model exhibits behavior similar to FLUX Model or its Derivatives, including by distillation methods, methods using intermediate data representations, or methods based on training using synthetic-data Outputs generated by FLUX Model or Derivatives, or (iv) any other derivative work thereof. For the avoidance of doubt, Outputs are not considered Derivatives under this License.+++b. “Distribution” or “Distribute” or “Distributing” means providing or making available, by any means, a copy of the FLUX Model and/or the Derivatives as the case may be.+++c. “Non-Commercial Purpose” means any of the following uses, but only so far as you do not receive any direct or indirect payment arising from the use of the FLUX Model, Derivatives, or Content Filters (as defined below): (i) personal use for research, experimentation, and testing for the benefit of public knowledge, personal study, private entertainment, hobby projects, or otherwise not directly or indirectly connected to any commercial activities, business operations, or employment responsibilities; (ii) use by commercial or for-profit entities for testing, evaluation, or non-commercial research and development in a non-production environment; and (iii) use by any charitable organization for charitable purposes, or for testing or evaluation. For clarity, use (a) for revenue-generating activity (including but not limited to in a production environment), (b) in direct interactions with or that has impact on end users, or (c) to train, fine tune, or distill other models for commercial use, in each case, is not a Non-Commercial Purpose.+++d. “Output” means any result of operating or otherwise using the FLUX Model or Derivatives, including but not limited to images, audio, video, or action-prediction outputs. For the avoidance of doubt, Output does not include any components of the FLUX Model, including any fine-tuned versions of the FLUX Model, the weights, or parameters.+++e. “Qualifying User” means you, if at any time you together with your affiliates’ gross annualized revenue is less than US$5,000,000.+++f. “Robotics Uses” means any production robotic system, autonomous machine, embodied AI system, cyber-physical system, or other physical AI applications, including for the purpose of generating action-predictions, motion planning, or control signals for any physical device or equipment.+++g. “you” or “your” means the individual or entity entering into this License with Company.+++2. License Grant.+++a. License. Subject to your compliance with this License, Company grants you a non-exclusive, worldwide, non-transferable, non-sublicensable, revocable, royalty free, and limited license to access, use, create Derivatives of, and Distribute the FLUX Model and Derivatives solely for: (i) your Non-Commercial Purposes, including non-commercial Robotics Uses; and (ii) solely if you are a Qualifying User, use Outputs, including Outputs from Derivatives, for commercial purposes, and you may access and use the FLUX Model and Derivatives in a production environment solely for the purpose of generating such Outputs, except as expressly prohibited herein. The foregoing license is personal to you, and you may not assign or sublicense this License or any other rights or obligations under this License without Company’s prior written consent; any such assignment or sublicense will be void and will automatically and immediately terminate this License. Any restrictions set forth herein regarding the FLUX Model also apply to any Derivative you create or that are created on your behalf.+++b. Non-Commercial Use Only. You may only access, use, Distribute, or create Derivatives of the FLUX Model or Derivatives for Non-Commercial Purposes, except as set forth in Section 2.a. If you want to use a FLUX Model or a Derivative for any purpose that is not expressly authorized under this License, such as for a commercial activity, you must request a license from Company, which Company may grant to you in Company’s sole discretion and which additional use may be subject to a fee, royalty or other revenue share. Please see https://bfl.ai/licensing if you would like a commercial license.+++c. Reserved Rights. The grant of rights expressly set forth in this License are the complete grant of rights to use the FLUX Model, and no other licenses are granted, whether by waiver, estoppel, implication, equity, or otherwise. Company and its licensors reserve all rights not expressly granted by this License.+++d. Outputs. We claim no ownership rights in and to the Outputs. You are solely responsible for the Outputs you generate and their subsequent uses in accordance with this License.+++e. You may access, use, Distribute, or create Output of the FLUX Model or Derivatives pursuant to Section 2.a as a Qualifying User if you: (i) (A) implement and maintain content filtering measures (“Content Filters”) for your use of the FLUX Model or Derivatives to prevent the creation, display, transmission, generation, or dissemination of unlawful, unsafe or infringing content, which may include Content Filters that we may make available for use with the FLUX Model (“Provided Content Filters”), or (B) ensure Output undergoes review for unlawful or infringing content before public or non-public distribution, display, transmission or dissemination; and (ii) ensure Output includes disclosures (or other indications) that the Output was generated or modified using artificial intelligence technologies to the extent required under applicable law.+++3. Distribution. Subject to this License, you may Distribute copies of the FLUX Model and/or Derivatives made by you, under the following conditions:+++a. you must make available a copy of this License to third-party recipients of the FLUX Model and/or Derivatives you Distribute, and specify that any rights to use the FLUX Model and/or Derivatives shall be directly granted by Company to said third-party recipients pursuant to this License;+++b. you must prominently display the following notice alongside the Distribution of the FLUX Model or Derivative (such as via a “Notice” text file distributed as part of such FLUX Model or Derivative) (the “Attribution Notice”):+++“This FLUX Model is licensed by Black Forest Labs Inc. under the FLUX Kommunity License. Copyright Black Forest Labs Inc. IN NO EVENT SHALL BLACK FOREST LABS INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH USE OF THIS MODEL.”+++c. in the case of Distribution of Derivatives made by you: (i) you must also include in the Attribution Notice a statement that you have modified the applicable FLUX Model; (ii) any terms and conditions you impose on any third-party recipients relating to Derivatives made by or for you shall neither limit such third-party recipients’ use of the FLUX Model or any Derivatives made by or for Company in accordance with this License nor conflict with any of its terms and conditions and must include disclaimer of warranties and limitation of liability provisions that are at least as protective of Company as those set forth herein; and (iii) you must not misrepresent or imply, through any means, that the Derivatives made by or for you and/or any modified version of the FLUX Model you Distribute under your name and responsibility is an official product of the Company or has been endorsed, approved or validated by the Company, unless you are authorized by Company to do so in writing.+++4. Restrictions. You will not, and will not permit, assist or cause any third party to:+++a. use, modify, copy, reproduce, create Derivatives of, or Distribute the FLUX Model (or any Derivative thereof, or any data produced by the FLUX Model), in whole or in part, (i) for any commercial or production purposes (except as set forth in Section 2.a), (ii) military purposes, (iii) purposes of surveillance, including any research or development relating to surveillance, (iv) biometric processing, (v) in any manner that infringes, misappropriates, or otherwise violates (or is likely to infringe, misappropriate, or otherwise violate) any third party’s legal rights, including rights of publicity or “digital replica” rights, (vi) in any unlawful, unsafe, fraudulent, defamatory, or abusive activity, (vii) to generate unlawful content, including child sexual abuse material, or non-consensual intimate images; or (viii) in any manner that violates any applicable law and any privacy or security laws, rules, regulations, directives, or governmental requirements (including the General Data Privacy Regulation (Regulation (EU) 2016/679), the California Consumer Privacy Act, any and all laws governing the processing of biometric information, and the EU Artificial Intelligence Act (Regulation (EU) 2024/1689), as well as all amendments and successor laws to any of the foregoing);+++b. use the FLUX Model, any Derivatives, or any Output or results from the FLUX Model or Derivative to improve any other artificial intelligence model that performs any function similar to a FLUX Model or Derivative;+++c. alter or remove copyright and other proprietary notices which appear on or in any portion of the FLUX Model;+++d. utilize any equipment, device, software, or other means to circumvent or remove any security or protection used by Company in connection with the FLUX Model, or to circumvent or remove any usage restrictions, or to enable functionality disabled by FLUX Model;+++e. offer or impose any terms on the FLUX Model that alter, restrict, or are inconsistent with the terms of this License;+++f. violate any applicable U.S. and non-U.S. export control and trade sanctions laws (“Export Laws”) in connection with your use or Distribution of any FLUX Model;+++g. directly or indirectly Distribute, export, or otherwise transfer FLUX Model (i) to any individual, entity, or country prohibited by Export Laws; (ii) to anyone on U.S. or non-U.S. government restricted parties lists; (iii) for any purpose prohibited by Export Laws, including nuclear, chemical or biological weapons, or missile technology applications; (iv) use or download FLUX Model if you or they are (a) located in a comprehensively sanctioned jurisdiction, (b) currently listed on any U.S. or non-U.S. restricted parties list, or (c) for any purpose prohibited by Export Laws; and (v) will not disguise your location through IP proxying or other methods.+++5. DISCLAIMERS. THE FLUX MODEL AND PROVIDED CONTENT FILTERS ARE PROVIDED “AS IS” AND “WITH ALL FAULTS” WITH NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. COMPANY EXPRESSLY DISCLAIMS ALL REPRESENTATIONS AND WARRANTIES, EXPRESS OR IMPLIED, WHETHER BY STATUTE, CUSTOM, USAGE OR OTHERWISE AS TO ANY MATTERS RELATED TO THE FLUX MODEL AND PROVIDED CONTENT FILTERS, INCLUDING BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, SATISFACTORY QUALITY, OR NON-INFRINGEMENT. COMPANY MAKES NO WARRANTIES OR REPRESENTATIONS THAT THE FLUX MODEL AND PROVIDED CONTENT FILTERS WILL BE ERROR FREE OR FREE OF VIRUSES OR OTHER HARMFUL COMPONENTS, OR PRODUCE ANY PARTICULAR RESULTS.+++6. LIMITATION OF LIABILITY. TO THE FULLEST EXTENT PERMITTED BY LAW, IN NO EVENT WILL COMPANY BE LIABLE TO YOU OR YOUR EMPLOYEES, AFFILIATES, USERS, OFFICERS OR DIRECTORS (A) UNDER ANY THEORY OF LIABILITY, WHETHER BASED IN CONTRACT, TORT, NEGLIGENCE, STRICT LIABILITY, WARRANTY, OR OTHERWISE UNDER THIS LICENSE, OR (B) FOR ANY INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, PUNITIVE OR SPECIAL DAMAGES OR LOST PROFITS, EVEN IF COMPANY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THE FLUX MODEL, ITS CONSTITUENT COMPONENTS, PROVIDED CONTENT FILTERS, AND ANY OUTPUT (COLLECTIVELY, “MODEL MATERIALS”) ARE NOT DESIGNED OR INTENDED FOR USE IN ANY APPLICATION OR SITUATION WHERE FAILURE OR FAULT OF THE MODEL MATERIALS COULD REASONABLY BE ANTICIPATED TO LEAD TO SERIOUS INJURY OF ANY PERSON, INCLUDING POTENTIAL DISCRIMINATION OR VIOLATION OF AN INDIVIDUAL’S PRIVACY RIGHTS, OR TO SEVERE PHYSICAL, PROPERTY (SUCH AS MACHINERY OR OTHER EQUIPMENT), OR ENVIRONMENTAL DAMAGE (EACH, A “HIGH-RISK USE”). IF YOU ELECT TO USE ANY OF THE MODEL MATERIALS FOR A HIGH-RISK USE, YOU DO SO AT YOUR OWN RISK. YOU AGREE TO DESIGN AND IMPLEMENT APPROPRIATE DECISION-MAKING AND RISK-MITIGATION PROCEDURES AND POLICIES IN CONNECTION WITH A HIGH-RISK USE SUCH THAT EVEN IF THERE IS A FAILURE OR FAULT IN ANY OF THE MODEL MATERIALS, THE SAFETY OF PERSONS OR PROPERTY AFFECTED BY THE ACTIVITY STAYS AT A LEVEL THAT IS REASONABLE, APPROPRIATE, AND LAWFUL FOR THE FIELD OF THE HIGH-RISK USE.+++7. INDEMNIFICATION. You will indemnify, defend and hold harmless Company and our subsidiaries and affiliates, and each of our respective shareholders, directors, officers, employees, agents, successors, and assigns (collectively, the “Company Parties”) from and against any losses, liabilities, damages, fines, penalties, and expenses (including reasonable attorneys’ fees) incurred by any Company Party in connection with any claim, demand, allegation, lawsuit, proceeding, or investigation (collectively, “Claims”) arising out of or related to (a) your access to or use of the FLUX Model (including in connection with any Output, results or data generated from such access or use, or from your access or use of any Content Filters), including any High-Risk Use; (b) your Content Filters, including your failure to implement any Content Filters where required by this License such as in Section 2(e); (c) your violation of this License; or (d) your violation, misappropriation or infringement of any rights of another (including intellectual property or other proprietary rights and privacy rights). You will promptly notify the Company Parties of any such Claims, and cooperate with Company Parties in defending such Claims. You will also grant the Company Parties sole control of the defense or settlement, at Company’s sole option, of any Claims. This indemnity is in addition to, and not in lieu of, any other indemnities or remedies set forth in a written agreement between you and Company or the other Company Parties.+++8. Termination; Survival.+++a. This License will automatically terminate upon any breach by you of the terms of this License.+++b. We may terminate this License, in whole or in part, at any time upon notice (including electronic) to you.+++c. If you initiate any legal action or proceedings against Company or any other entity (including a cross-claim or counterclaim in a lawsuit), alleging that the FLUX Model, any Derivative, or Provided Content Filters, or any part thereof, infringe upon intellectual property or other rights owned or licensable by you, then any licenses granted to you under this License will immediately terminate as of the date such legal action or claim is filed or initiated.+++d. Upon termination of this License, you must cease all use, access or Distribution of the FLUX Model, any Derivatives, and any Provided Content Filters. The following sections survive termination of this License: 2(c), 2(d), 4-11.+++9. Third Party Materials. The FLUX Model and Provided Content Filters may contain third-party software or other components (including free and open source software) (all of the foregoing, “Third Party Materials”), which are subject to the license terms of the respective third-party licensors. Your dealings or correspondence with third parties and your use of or interaction with any Third Party Materials are solely between you and the third party. Company does not control or endorse, and makes no representations or warranties regarding, any Third Party Materials, and your access to and use of such Third Party Materials are at your own risk.+++10. Trademarks. You have not been granted any trademark license as part of this License and may not use any name, logo or trademark associated with Company without the prior written permission of Company, except to the extent necessary to make the reference required in the Attribution Notice as specified above or as is reasonably necessary in describing the FLUX Model and its creators.+++11. General. This License will be governed and construed under the laws of the State of Delaware without regard to conflicts of law provisions. If any provision or part of a provision of this License is unlawful, void or unenforceable, that provision or part of the provision is deemed severed from this License, and will not affect the validity and enforceability of any remaining provisions. The failure of Company to exercise or enforce any right or provision of this License will not operate as a waiver of such right or provision. This License does not confer any third-party beneficiary rights upon any other person or entity. This License, together with the documentation, contains the entire understanding between you and Company regarding the subject matter of this License, and supersedes all other written or oral agreements and understandings between you and Company regarding such subject matter.diff --git a/docs/licenses/FLUX3-NOTICE.txt b/docs/licenses/FLUX3-NOTICE.txtnew file mode 100644index 0000000..c993ed2--- /dev/null+++ b/docs/licenses/FLUX3-NOTICE.txt@@ -0,0 +1,13 @@+FLUX 3 Klein by Black Forest Labs++This FLUX Model is licensed by Black Forest Labs Inc. under the FLUX Kommunity License. Copyright Black Forest Labs Inc. IN NO EVENT SHALL BLACK FOREST LABS INC. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH USE OF THIS MODEL.++Rights to use this model are granted directly by Black Forest Labs Inc. to each recipient under the accompanying FLUX Kommunity License v1.0, not by Phosphene.++The downloaded models were converted and quantized by mflux-community. They are modified versions of FLUX 3 Image Klein or Klein Base, not official Black Forest Labs products. Phosphene does not modify these weights. The app's MIT licence does not replace the model licence.++Source: https://huggingface.co/black-forest-labs/flux-3-image-klein+Base: https://huggingface.co/black-forest-labs/flux-3-image-klein-base+Conversions: https://huggingface.co/mflux-community+Licence: https://huggingface.co/black-forest-labs/flux-3-image-klein/blob/main/LICENSE.md+The Qwen3-VL text encoder and mflux inference code have separate Apache-2.0 and MIT licences, respectively.diff --git a/flux3_engine.py b/flux3_engine.pynew file mode 100644index 0000000..6e660aa--- /dev/null+++ b/flux3_engine.py@@ -0,0 +1,277 @@+"""FLUX 3's isolated worker contract. No MLX or mflux imports in the studio."""+from __future__ import annotations++import json+import hashlib+import os+from pathlib import Path+import platform+import queue+import re+import secrets+import shutil+import subprocess+import sys+import threading+import time++ROOT = Path(__file__).resolve().parent+CREDIT = "FLUX 3 Klein by Black Forest Labs"+LICENCE_URL = "https://huggingface.co/black-forest-labs/flux-3-image-klein/blob/main/LICENSE.md"+# Free space FLUX 3 leaves untouched while it GROWS the disk (worker install,+# weight downloads). Rendering with everything installed writes one small PNG,+# so it only needs output headroom: a full reserve there refused every image+# on a Mac that had installed FLUX 3 and then had under the reserve free.+RESERVE = 5 * 1024**3+OUTPUT_HEADROOM = 64 * 1024**2+INSTALL_BUDGET = 3 * 1024**3+PACKS = json.loads((ROOT / "data/flux3_models.json").read_text())+PRESETS = {+ f"flux3_{variant}_q{q}": {"variant": variant, "quantize": q,+ "steps": 50 if variant == "base" else 16,+ "guidance": 3.5 if variant == "base" else None,+ "label": f"{CREDIT} / {'Base Quality' if variant == 'base' else 'Standard'} / Q{q}"}+ for variant in ("distilled", "base") for q in (8, 6, 4)+}+++def worker_root():+ return Path(os.environ.get("PHOSPHENE_FLUX3_ROOT") or ROOT / "flux3-worker").expanduser().resolve()+++def worker_python():+ return worker_root() / "env/bin/python"+++def requirements_digest():+ return hashlib.sha256((ROOT / "scripts/pinokio/flux3_requirements.txt").read_bytes()).hexdigest()+++def worker_ready():+ try:+ return worker_python().is_file() and (worker_root() / ".ready").read_text().strip() == requirements_digest()+ except OSError:+ return False+++def clean_env(base=None):+ source = os.environ if base is None else base+ stripped = {"VIRTUAL_ENV", "PYTHONPATH", "PYTHONHOME", "PYTHONSTARTUP",+ "__PYVENV_LAUNCHER__", "PYTORCH_ENABLE_MPS_FALLBACK",+ "PYTORCH_MPS_FAST_MATH", "TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD"}+ env = {k: v for k, v in source.items() if k not in stripped+ and not k.startswith(("Malloc", "MFLUX_"))}+ env.update(PYTHONUNBUFFERED="1", HF_HUB_DISABLE_TELEMETRY="1",+ HF_HUB_DISABLE_PROGRESS_BARS="0", MLX_ENABLE_TF32="0")+ return env+++def cache_root(env=None):+ env = os.environ if env is None else env+ return Path(env.get("HF_HUB_CACHE") or+ Path(env.get("HF_HOME") or Path.home() / ".cache/huggingface") / "hub").expanduser()+++def pack_for(config):+ key = f"{config.flux3_variant}-q{config.mflux_quantize}"+ if key not in PACKS:+ raise ValueError("FLUX 3 needs Standard or Base Quality and Q8, Q6 or Q4.")+ return PACKS[key]+++def snapshot_path(pack, env=None):+ return cache_root(env) / ("models--" + pack["repo"].replace("/", "--")) / "snapshots" / pack["revision"]+++def cached_bytes(pack, env=None):+ snap = snapshot_path(pack, env)+ total = 0+ for item in pack["files"]:+ try:+ if (snap / item["path"]).stat().st_size == item["size"]:+ total += item["size"]+ except OSError:+ pass+ return total+++def downloaded_bytes(pack, env=None):+ """Completed files plus resumable Hub blobs; never count a partial as ready."""+ snap = snapshot_path(pack, env)+ blobs = snap.parent.parent / "blobs"+ total = cached_bytes(pack, env)+ for item in pack["files"]:+ try:+ if (snap / item["path"]).stat().st_size == item["size"]:+ continue+ except OSError:+ pass+ digest = item.get("sha256")+ if digest:+ total += min(item["size"], partial_blob_bytes(blobs, digest))+ return total+++def partial_blob_bytes(blobs, digest):+ """Largest in-flight blob for this file. huggingface_hub 1.x writes+ `<etag>.<uuid8>.incomplete` (older hubs `<etag>.incomplete`); counting+ only the old name showed 0.00 GB for the whole download."""+ best = 0+ try:+ for part in Path(blobs).glob(digest + "*.incomplete"):+ try:+ best = max(best, part.stat().st_size)+ except OSError:+ pass+ except OSError:+ pass+ return best+++def require_space(path, extra=0, reserve=RESERVE):+ path = Path(path)+ while not path.exists():+ path = path.parent+ free = shutil.disk_usage(path).free+ if free < reserve + extra:+ why = (f", keeping {reserve / 1024**3:.0f} GB free for your Mac" if reserve >= 1024**3 else "")+ raise RuntimeError(f"FLUX 3 needs {(reserve + extra) / 1024**3:.1f} GB free here "+ f"({free / 1024**3:.1f} GB available){why}. "+ "Free space or choose another model location, then retry.")+++def ram_need(config):+ pack_for(config)+ return {4: 18.5, 6: 20.6, 8: 22.8}[config.mflux_quantize]+++def validate(config, width, height, refs, total_gb=None):+ pack_for(config)+ if total_gb is None:+ if platform.system() != "Darwin" or platform.machine() != "arm64":+ raise RuntimeError("FLUX 3 requires an Apple Silicon Mac.")+ total_gb = int(subprocess.check_output(["/usr/sbin/sysctl", "-n", "hw.memsize"])) / 1024**3+ floor = 24 if config.mflux_quantize == 4 else 32+ if total_gb < floor:+ raise ValueError(f"FLUX 3 Q{config.mflux_quantize} needs a {floor} GB Mac. "+ "Q4 is available on 24 GB Macs; 32 GB or more is recommended.")+ if width % 16 or height % 16 or width * height > 1024**2:+ raise ValueError("FLUX 3 supports up to 1024 x 1024 pixels, in multiples of 16.")+ if len(refs) > 10:+ raise ValueError("FLUX 3 supports up to ten reference images.")+ if total_gb < 32 and (width * height > 768**2 or len(refs) > 1):+ raise ValueError("On a 24 GB Mac, use Q4, a small image size and at most one reference.")+++def status(engine, total_gb):+ recipe = PRESETS[engine]+ pack = PACKS[f"{recipe['variant']}-q{recipe['quantize']}"]+ complete = cached_bytes(pack)+ done = downloaded_bytes(pack)+ floor = 24 if recipe["quantize"] == 4 else 32+ return dict(engine=engine, repo_id=pack["repo"], cached=complete == pack["bytes"],+ partial=done > 0 and complete < pack["bytes"], partial_gb=done / 1e9,+ family_installed=True, worker_installed=worker_ready(),+ lazy_install=True, download_gb=pack["bytes"] / 1e9,+ ram_need_gb={4: 18.5, 6: 20.6, 8: 22.8}[recipe["quantize"]],+ mac_gb_needed=floor, fits_mac=total_gb >= floor,+ sec_per_image=0, cold_start_sec=0, samples_source="unmeasured",+ gated=False, license_url=LICENCE_URL)+++def _redact(line):+ return re.sub(r"hf_[A-Za-z0-9]+", "[redacted]", line)+++def _run(cmd, env, on_log, request=None, timeout=7200, guard=()):+ """Stream progress and share the studio's cancellation registry, including install."""+ import image_engine+ events = queue.Queue()+ proc = subprocess.Popen(cmd, cwd=ROOT, env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT,+ text=True, errors="replace", start_new_session=True)+ try:+ image_engine._register_active_proc(proc)+ except BaseException:+ proc.stdin.close()+ proc.stdout.close()+ raise+ tail, receipts = [], []+ def read():+ try:+ for line in proc.stdout:+ events.put(line.rstrip())+ finally:+ events.put(None)+ threading.Thread(target=read, daemon=True).start()+ started = time.monotonic()+ try:+ if request is not None:+ proc.stdin.write(json.dumps(request) + "\n")+ proc.stdin.close()+ while True:+ check = image_engine._CANCEL_CHECK+ if check and check():+ raise image_engine.ImageJobCancelled("FLUX 3 stopped.")+ if time.monotonic() - started > timeout:+ raise RuntimeError("FLUX 3 timed out. Retry with a smaller image or fewer references.")+ for path, reserve in guard:+ require_space(path, reserve=reserve)+ try:+ line = events.get(timeout=0.25)+ except queue.Empty:+ continue+ if line is None:+ break+ if line.startswith("FLUX3_RESULT "):+ receipts.append(json.loads(line[len("FLUX3_RESULT "):]))+ else:+ line = _redact(line)+ tail = (tail + [line])[-15:]+ if on_log:+ on_log(line)+ rc = proc.wait(timeout=10)+ if rc < 0:+ raise image_engine.ImageJobCancelled("FLUX 3 stopped.")+ if rc:+ raise RuntimeError("FLUX 3 did not finish: " + "\n".join(tail))+ return receipts+ finally:+ if proc.poll() is None:+ import signal+ try:+ os.killpg(proc.pid, signal.SIGKILL)+ except ProcessLookupError:+ pass+ proc.wait(timeout=10)+ image_engine._unregister_active_proc(proc)+ proc.stdout.close()+++def generate(prompt, n, width, height, output_dir, base_seed, config, refs, on_log, install_env=None):+ validate(config, width, height, refs)+ env = clean_env(install_env)+ pack = pack_for(config)+ # The reserve guards GROWTH only: nothing to fetch or install, no reserve.+ missing = pack["bytes"] - downloaded_bytes(pack, env)+ if missing > 0:+ require_space(cache_root(env), missing)+ require_space(output_dir, OUTPUT_HEADROOM, reserve=0)+ installing = not worker_ready()+ if installing and not worker_python().is_file():+ require_space(worker_root(), INSTALL_BUDGET)+ # The bootstrap checks exact package versions without importing MLX.+ _run([sys.executable, "-S", str(ROOT / "scripts/pinokio/flux3_env.py"), str(worker_root())], env, on_log,+ guard=[(worker_root(), RESERVE)] if installing else [])+ first_seed = base_seed if base_seed is not None else secrets.randbelow(2**31)+ request = dict(prompt=prompt, seeds=[first_seed + i for i in range(n)],+ width=width, height=height, output_dir=str(output_dir), refs=refs,+ variant=config.flux3_variant, quantize=config.mflux_quantize)+ result = _run([str(worker_python()), str(ROOT / "scripts/flux3_worker.py")], env, on_log, request,+ timeout=1800 + 3600 * n,+ # The worker guards its own downloads with RESERVE; here only+ # the output volume matters, so a full disk still stops it.+ guard=[(output_dir, OUTPUT_HEADROOM)])+ if len(result) != n or any(not Path(r["png_path"]).is_file() for r in result):+ raise RuntimeError("FLUX 3 returned no complete image. Check the log and retry.")+ return resultdiff --git a/image_engine.py b/image_engine.pyindex 565de37..33439b0 100644--- a/image_engine.py+++ b/image_engine.py@@ -347,6 +347,9 @@ class ImageEngineConfig:# _load_agent_image_config in mlx_ltx_panel.py).kind: str = "mflux" # "mock" | "mflux" | "bfl" | "hidream"+ # FLUX 3 always runs in its own worker environment.+ flux3_variant: str = "distilled"+# BFL (cloud)bfl_api_key: str = ""bfl_model: str = "flux-dev" # flux-dev | flux-pro | flux-pro-1.1 | flux-schnell@@ -479,7 +482,8 @@ def generate(*, prompt: str, n: int, output_dir: Path,base_seed: int | None = None,refs: list[str] | None = None,config: ImageEngineConfig,- on_log: "callable | None" = None) -> list[dict]:+ on_log: "callable | None" = None,+ install_env: dict | None = None) -> list[dict]:"""Generate `n` candidate images for one shot. Saves under `output_dir`.Args:@@ -518,7 +522,7 @@ def generate(*, prompt: str, n: int, output_dir: Path,# Validate ref paths up-front so we fail fast — Qwen-Edit-2509 supports# 1-3 input images; more than 3 is unsupported by the model.if refs:- if len(refs) > 3:+ if len(refs) > (10 if config.kind == "flux3" else 3):raise ValueError(f"refs: Qwen-Image-Edit-2509 supports 1-3 input images, got {len(refs)}")@@ -526,6 +530,10 @@ def generate(*, prompt: str, n: int, output_dir: Path,if not Path(r).is_file():raise FileNotFoundError(f"ref image not found: {r}")+ if config.kind == "flux3":+ import flux3_engine+ return flux3_engine.generate(prompt, n, width, height, output_dir, base_seed,+ config, refs, on_log, install_env)if config.kind == "mock":return _generate_mock(prompt, n, width, height, output_dir, base_seed, refs=refs)if config.kind == "mflux":@@ -539,6 +547,10 @@ def generate(*, prompt: str, n: int, output_dir: Path,def health_check(config: ImageEngineConfig) -> tuple[bool, str]:"""Light readiness probe for the configured backend."""+ if config.kind == "flux3":+ import flux3_engine+ return True, ("FLUX 3 ready" if flux3_engine.worker_ready()+ else "FLUX 3 installs on first use")if config.kind == "mock":try:from PIL import Image # noqa: F401diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex db4e2fb..be9fe76 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -34113,6 +34113,9 @@ def _preflight_estimate_ram_gb(cfg) -> float:The `9b` variant gets a hard override — its Metal residency dwarfsevery 4B sibling regardless of quantize."""+ if cfg.kind == "flux3":+ import flux3_engine+ return flux3_engine.ram_need(cfg)if cfg.kind == "hidream":# 2026-05-31 review fix: HiDream-O1 BF16 was exempt from the RAM gate# (fell through to the 1.0 GB `!= mflux` branch). Its Metal residency@@ -34373,10 +34376,10 @@ def run_image_job_inner(job: dict) -> None:refs_in = p.get("refs") or []if not isinstance(refs_in, list):raise RuntimeError(f"refs must be a list, got {type(refs_in).__name__}")- if len(refs_in) > 3:- raise RuntimeError(- "refs supports at most 3 images (Qwen-Edit-2509 limit)"- )+ import flux3_engine+ max_refs = 10 if engine_override in flux3_engine.PRESETS else 3+ if len(refs_in) > max_refs:+ raise RuntimeError(f"This engine supports at most {max_refs} reference images.")refs_resolved: list[str] = []for r in refs_in:if not isinstance(r, str) or not r.strip():@@ -34398,6 +34401,10 @@ def run_image_job_inner(job: dict) -> None:except ValueError as e:raise RuntimeError(str(e))+ if cfg.kind == "flux3":+ width, height = agent_image_engine.ASPECT_DIMS.get(aspect, (1280, 720))+ flux3_engine.validate(cfg, width, height, refs_resolved, SYSTEM_RAM_GB)+# User-picked LoRAs from the unified picker (same hidden #lorasJson# form field the video form uses). The job's `loras` param shape is# the cleaned list of {path, strength} that parse_loras_from_form()@@ -34492,6 +34499,7 @@ def run_image_job_inner(job: dict) -> None:refs=refs_resolved or None,config=cfg,on_log=lambda line: push(f"[image] {line}"),+ **({"install_env": _music_install_env()} if cfg.kind == "flux3" else {}),)except Exception as _gen_exc: # noqa: BLE001# Friendly message for the Ideogram 4 license gate: mflux 403s on the@@ -34565,6 +34573,7 @@ def run_image_job_inner(job: dict) -> None:"generated_at": generated_at,"refs_ignored": c.get("refs_ignored", False),"source": "panel.queue.image",+ **({"flux3": c} if cfg.kind == "flux3" else {}),}try:sidecar_path.write_text(json.dumps(sidecar, indent=2), encoding="utf-8")@@ -42013,6 +42022,15 @@ def _build_image_engine_config("""engine_override = (engine_override or "auto").lower()form = form or {}+ import flux3_engine+ if engine_override in flux3_engine.PRESETS:+ recipe = flux3_engine.PRESETS[engine_override]+ pack = flux3_engine.PACKS[f"{recipe['variant']}-q{recipe['quantize']}"]+ return agent_image_engine.ImageEngineConfig(+ kind="flux3", flux3_variant=recipe["variant"],+ mflux_model=pack["repo"], mflux_quantize=recipe["quantize"],+ mflux_steps=recipe["steps"], mflux_guidance=recipe["guidance"],+ mflux_lora_paths=[], mflux_lora_scales=[])if engine_override == "auto":return low_ram_auto_image_config(_load_agent_image_config(), form)# ===== Ideogram 4 (fp8) — typography & layout, text-in-image ===========diff --git a/model_licences.py b/model_licences.pyindex 4eebc96..d696518 100644--- a/model_licences.py+++ b/model_licences.py@@ -48,6 +48,15 @@ REPORT_MISUSE_URL = ("https://github.com/mrbizarro/Phosphene/issues/new"# Static facts per model. `version` is the licence's own date: change it when# the licence text changes and everyone is asked again.LICENCES: dict[str, dict] = {+ "flux3": {+ "model": "FLUX 3 Klein by Black Forest Labs",+ "licence": "FLUX Kommunity License v1.0",+ "licensor": "Black Forest Labs Inc.",+ "version": "flux-kommunity-1.0",+ "url": "https://huggingface.co/black-forest-labs/flux-3-image-klein/blob/main/LICENSE.md",+ "non_commercial": False,+ "covers": "FLUX 3 Image Klein and Klein Base, including quantized weights",+ },"h3": {"model": "MiniMax H3 (Hailuo H3)","licence": "MiniMax H3 Community License Agreement",@@ -199,6 +208,19 @@ COPY: dict = {'modal_title': 'Model licence','accept_label': 'I have read and accept the Bria FIBO licence for ''non-commercial use only.'}}+COPY["flux3"] = {+ "title": "FLUX 3 Klein licence",+ "summary": "The app is MIT. These model weights have a separate licence from Black Forest Labs.",+ "badge": "Commercial outputs below USD 5M revenue",+ "terms": [+ "Commercial output generation is permitted only while your gross annualized revenue, including affiliates, is below USD 5 million. Otherwise obtain commercial terms from Black Forest Labs.",+ "Review outputs for unlawful or infringing content before sharing or displaying them. Disclose AI generation or modification where the law requires it.",+ "Follow the full licence, including its use restrictions. Rights to the model are granted directly to you by Black Forest Labs, not by Phosphene.",+ "When sharing model weights, include the full licence and the Black Forest Labs attribution notice. The community quantizations are modified models, not official Black Forest Labs products.",+ ],+ "accept_label": "I have read and accept the FLUX Kommunity License and will review outputs before sharing them.",+}+STORE_NAME = "model_licences.json"_LOCK = threading.Lock()@@ -298,6 +320,8 @@ def describe_all(state_dir) -> dict:# ---- which licence a piece of work needs --------------------------------------def licence_for_image_cfg(cfg) -> str | None:"""The licence an image-engine config needs, from its mflux family/model."""+ if cfg is not None and getattr(cfg, "kind", "") == "flux3":+ return "flux3"if cfg is None or getattr(cfg, "kind", "") != "mflux":return Nonefamily = str(getattr(cfg, "mflux_family", "") or "").lower()diff --git a/panel/routes_image.py b/panel/routes_image.pyindex 1a73fb1..b44490f 100644--- a/panel/routes_image.py+++ b/panel/routes_image.py@@ -387,6 +387,9 @@ def get_image_engine_status(h, parsed) -> None:"license_url": ("https://huggingface.co/" + repo)if (repo and engine == "ideogram4_inline") else None,})+ import flux3_engine+ out.extend(flux3_engine.status(key, float(P.SYSTEM_RAM_GB or 0))+ for key in flux3_engine.PRESETS)h._json({"engines": out,"host_ram_gb": int(round(float(P.SYSTEM_RAM_GB or 0)))})except Exception as exc: # noqa: BLE001@@ -762,8 +765,10 @@ def post_image_generate(h, path, qs, ctype) -> None:refs_in = payload.get("refs") or []if not isinstance(refs_in, list):h._json({"error": "refs must be a list of paths"}, 400); return- if len(refs_in) > 3:- h._json({"error": "refs supports at most 3 images (Qwen-Edit-2509 limit)"}, 400); return+ import flux3_engine+ max_refs = 10 if str(payload.get("engine_override") or "").lower() in flux3_engine.PRESETS else 3+ if len(refs_in) > max_refs:+ h._json({"error": f"This engine supports at most {max_refs} reference images."}, 400); returnrefs_resolved: list[str] = []for r in refs_in:if not isinstance(r, str) or not r.strip():@@ -804,6 +809,13 @@ def post_image_generate(h, path, qs, ctype) -> None:if _lic:h._json(_lic, 451); return+ if cfg.kind == "flux3":+ try:+ width, height = P.agent_image_engine.ASPECT_DIMS.get(aspect, (1280, 720))+ flux3_engine.validate(cfg, width, height, refs_resolved, P.SYSTEM_RAM_GB)+ except ValueError as e:+ h._json({"error": str(e)}, 400); return+# Output dir: panel_uploads/library/manual/<YYYYMMDD>/<unix_ms>/# — date-bucketed for directory hygiene PLUS a per-request# millisecond subdir so two generations in the same day don't@@ -836,6 +848,8 @@ def post_image_generate(h, path, qs, ctype) -> None:# Stream mflux stdout into the panel log card so users# see step-by-step progress while the gen runs.# tqdm progress bars come through line-buffered.+ if cfg.kind == "flux3":+ P._preflight_image_job(cfg, engine_override=engine_override)candidates = P.agent_image_engine.generate(prompt=prompt, n=n, aspect=aspect,output_dir=out_dir,@@ -843,6 +857,7 @@ def post_image_generate(h, path, qs, ctype) -> None:refs=refs_resolved or None,config=cfg,on_log=lambda line: P.push(f"[image] {line}"),+ **({"install_env": P._music_install_env()} if cfg.kind == "flux3" else {}),)except FileNotFoundError as e:h._json({"error": str(e)}, 404); return@@ -886,6 +901,7 @@ def post_image_generate(h, path, qs, ctype) -> None:"generated_at": generated_at,"refs_ignored": c.get("refs_ignored", False),"source": "panel.image_studio",+ **({"flux3": c} if cfg.kind == "flux3" else {}),}try:sidecar_path.write_text(P.json.dumps(sidecar, indent=2), encoding="utf-8")diff --git a/scripts/flux3_worker.py b/scripts/flux3_worker.pynew file mode 100644index 0000000..5ea0e64--- /dev/null+++ b/scripts/flux3_worker.py@@ -0,0 +1,139 @@+"""mflux 0.23.0 worker. Executed only with flux3-worker/env/bin/python."""+import gc+import json+import os+from pathlib import Path+import resource+import sys+import time++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT))+from flux3_engine import CREDIT, LICENCE_URL, OUTPUT_HEADROOM, PACKS, cache_root, cached_bytes, downloaded_bytes, clean_env, require_space++# Defence at both process boundaries, including direct Pinokio invocation.+_clean = clean_env()+os.environ.clear()+os.environ.update(_clean)+++def fetch(pack):+ from huggingface_hub import hf_hub_download+ missing = pack["bytes"] - downloaded_bytes(pack)+ if missing > 0: # the reserve guards downloads, not a fully cached model+ require_space(cache_root(), missing)+ # Progress and the disk reserve come from the cache itself, polled on a+ # thread: hf-xet transfers never call the tqdm hook, so a hook-only+ # report sat at 0.00 GB and the reserve went unchecked mid-download.+ import threading+ stop = threading.Event()+ def watch():+ while not stop.wait(3):+ try:+ require_space(cache_root())+ except RuntimeError as exc:+ print("FLUX 3: " + str(exc), flush=True)+ os._exit(1)+ print(f"[download] model weights: {downloaded_bytes(pack) / 1e9:.2f} GB "+ f"of {pack['bytes'] / 1e9:.2f} GB", flush=True)+ watcher = threading.Thread(target=watch, daemon=True)+ if cached_bytes(pack) < pack["bytes"]:+ watcher.start()+ path = None+ for i, item in enumerate(pack["files"], 1):+ print(f"FLUX 3 download: file {i}/{len(pack['files'])}, {item['path']}", flush=True)+ path = Path(hf_hub_download(pack["repo"], item["path"], revision=pack["revision"],+ token=False))+ if path.stat().st_size != item["size"]:+ raise RuntimeError("Incomplete FLUX 3 download. Retry to resume it.")+ if item.get("sha256"):+ import hashlib+ print(f"FLUX 3: verifying {item['path']}", flush=True)+ with path.open("rb") as handle:+ digest = hashlib.file_digest(handle, "sha256").hexdigest()+ if digest != item["sha256"]:+ raise RuntimeError("FLUX 3 weights failed verification. Download a clean copy in another cache location.")+ print(f"[download] model weights: {cached_bytes(pack) / 1e9:.2f} GB "+ f"of {pack['bytes'] / 1e9:.2f} GB", flush=True)+ stop.set()+ # All files are in the same pinned snapshot. Retain the BFL licence next+ # to the model and document the conversion's authorship.+ from flux3_engine import snapshot_path+ snapshot = snapshot_path(pack)+ import shutil+ shutil.copyfile(ROOT / "docs/licenses/FLUX-Kommunity-1.0.txt", snapshot / "LICENSE.txt")+ shutil.copyfile(ROOT / "docs/licenses/FLUX3-NOTICE.txt", snapshot / "NOTICE.txt")+ return snapshot+++def cli_args(request, model, seed, output):+ base = "flux3-image-klein" + ("-base" if request["variant"] == "base" else "")+ args = ["mflux-generate-flux3", "--model", str(model), "--base-model", base,+ "--prompt", request["prompt"], "--seed", str(seed),+ "--width", str(request["width"]), "--height", str(request["height"]),+ "--steps", "50" if request["variant"] == "base" else "16",+ "--output", str(output), "--metadata", "--low-ram"]+ if request["variant"] == "base":+ args += ["--guidance", "3.5"]+ if request["refs"]:+ args += ["--image-paths", *request["refs"]]+ return args+++def main():+ # Pinokio removes SSL variables. Use this worker's certifi, not the+ # studio interpreter's certificate path, for all HTTPS downloads.+ import certifi+ os.environ.setdefault("SSL_CERT_FILE", certifi.where())+ os.environ.setdefault("REQUESTS_CA_BUNDLE", certifi.where())+ request = json.loads(sys.stdin.readline())+ pack = PACKS[f"{request['variant']}-q{request['quantize']}"]+ model = fetch(pack)+ import mlx.core as mx+ if request["refs"]:+ from mflux.models.flux3.cli.flux3_edit_generate import main as render+ else:+ from mflux.models.flux3.cli.flux3_generate import main as render+ from PIL import Image+ native_reset = mx.reset_peak_memory+ peaks = []+ def track_reset():+ peaks.append(mx.get_peak_memory())+ native_reset()+ # mflux resets its peak counter after loading. Keep that peak too.+ mx.reset_peak_memory = track_reset+ for seed in request["seeds"]:+ output = Path(request["output_dir"]) / f"flux3_{time.time_ns()}_{seed}.png"+ require_space(output.parent, OUTPUT_HEADROOM, reserve=0)+ mx.clear_cache()+ peaks.clear()+ native_reset()+ started = time.monotonic()+ print(f"FLUX 3: rendering seed {seed} ({'edit' if request['refs'] else 'text to image'})", flush=True)+ sys.argv = cli_args(request, model, seed, output)+ render()+ if not output.is_file():+ raise RuntimeError("The worker stopped before writing a complete image.")+ with Image.open(output) as im:+ im.verify()+ with Image.open(output) as im:+ width, height = im.size+ result = dict(png_path=str(output), seed=seed, engine="flux3", model=pack["repo"],+ width=width, height=height, elapsed_seconds=round(time.monotonic() - started, 3),+ peak_mlx_gb=round(max([mx.get_peak_memory(), *peaks]) / 1e9, 3),+ peak_rss_gb=round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e9, 3),+ peak_rss_scope="worker process high-water mark",+ credit=CREDIT, licence_url=LICENCE_URL, revision=pack["revision"],+ variant=request["variant"], quantize=request["quantize"], refs=request["refs"])+ output.with_suffix(".flux3.json").write_text(json.dumps(result, indent=2) + "\n")+ print("FLUX3_RESULT " + json.dumps(result), flush=True)+ gc.collect()+++if __name__ == "__main__":+ try:+ main()+ except Exception as exc:+ from flux3_engine import _redact+ print("FLUX 3: " + _redact(str(exc)), flush=True)+ sys.exit(1)diff --git a/scripts/pinokio/flux3_env.py b/scripts/pinokio/flux3_env.pynew file mode 100644index 0000000..52e92d2--- /dev/null+++ b/scripts/pinokio/flux3_env.py@@ -0,0 +1,81 @@+"""Lazy, locked FLUX 3 install. Called by the panel and Pinokio, never the studio pip."""+import fcntl+import json+import os+import platform+from pathlib import Path+import shutil+import subprocess+import sys++ROOT = Path(__file__).resolve().parents[2]+sys.path.insert(0, str(ROOT))+from flux3_engine import INSTALL_BUDGET, clean_env, require_space, requirements_digest+++def check_destination(root):+ target = (root / "env").resolve()+ if target in {Path(sys.prefix).resolve(), (ROOT / "ltx-2-mlx/env").resolve()}:+ raise RuntimeError("FLUX 3 cannot use the studio environment. Choose a separate folder.")+ if (root / "env").exists() and not (root / ".phosphene-flux3-worker").is_file():+ raise RuntimeError("This folder already contains another environment. Choose a new FLUX 3 folder.")+++def main():+ if platform.system() != "Darwin" or platform.machine() != "arm64":+ raise RuntimeError("FLUX 3 requires an Apple Silicon Mac.")+ if int(platform.mac_ver()[0].split(".")[0]) < 14:+ raise RuntimeError("FLUX 3 requires macOS 14 or later.")+ root = Path(sys.argv[1]).resolve()+ check_destination(root)+ root.mkdir(parents=True, exist_ok=True)+ py = root / "env/bin/python"+ requirements = Path(__file__).with_name("flux3_requirements.txt")+ expected = dict(line.split("==", 1) for line in requirements.read_text().splitlines()+ if line and not line.startswith("#"))+ check = ("import importlib.metadata as m,json; "+ "print(json.dumps({p:m.version(p) for p in " + repr(list(expected)) + "}))")+ def mark_ready():+ temp = root / f".ready.{os.getpid()}"+ temp.write_text(requirements_digest() + "\n")+ os.replace(temp, root / ".ready")++ def ready():+ if not py.is_file():+ return False+ p = subprocess.run([str(py), "-I", "-c", check], capture_output=True,+ text=True, errors="replace", env=clean_env(), timeout=30)+ try:+ return p.returncode == 0 and json.loads(p.stdout) == expected+ except ValueError:+ return False+ with (root / ".install.lock").open("a") as lock:+ print("FLUX 3: checking its separate image engine...", flush=True)+ fcntl.flock(lock, fcntl.LOCK_EX)+ check_destination(root)+ (root / ".phosphene-flux3-worker").write_text("Phosphene FLUX 3 worker\n")+ if ready():+ mark_ready()+ return+ (root / ".ready").unlink(missing_ok=True)+ require_space(root, INSTALL_BUDGET)+ uv = shutil.which("uv")+ if not uv:+ raise RuntimeError("uv was not found. Start Phosphene through Pinokio and retry.")+ print("FLUX 3: installing its separate image engine. Stop cancels this step.", flush=True)+ if not py.is_file():+ subprocess.run([uv, "venv", "--python", "3.12", str(root / "env")], check=True, env=clean_env())+ subprocess.run([uv, "pip", "install", "--no-cache", "--python", str(py),+ "-r", str(requirements)], check=True, env=clean_env())+ if not ready():+ raise RuntimeError("FLUX 3 packages did not match their pins. Retry the install.")+ mark_ready()+ print("FLUX 3: image engine ready.", flush=True)+++if __name__ == "__main__":+ try:+ main()+ except Exception as exc:+ print(f"FATAL error: {exc}", flush=True)+ sys.exit(1)diff --git a/scripts/pinokio/flux3_requirements.txt b/scripts/pinokio/flux3_requirements.txtnew file mode 100644index 0000000..44a34d6--- /dev/null+++ b/scripts/pinokio/flux3_requirements.txt@@ -0,0 +1,59 @@+# FLUX 3 worker only. Resolved for macOS arm64, Python 3.12 on 2026-10-23.+# Fresh-install and GPU validation are recorded separately in docs/FLUX3.md.+annotated-doc==0.0.5+anyio==4.15.1+certifi==2026.10.23+charset-normalizer==3.5.2+click==8.5.0+contourpy==1.4.0+cycler==0.12.1+filelock==4.2.4+fonttools==4.67.0+fsspec==2026.9.0+h11==0.16.0+hf-transfer==0.1.9+hf-xet==1.7.0+httpcore==1.0.9+httpx==0.28.1+huggingface-hub==1.33.0+idna==3.20+jinja2==3.1.6+kiwisolver==1.5.1+markdown-it-py==4.2.0+markupsafe==3.0.4+matplotlib==3.11.2+mdurl==0.1.2+mflux==0.23.0+mlx==0.32.4+mlx-metal==0.32.4+mpmath==1.3.0+networkx==3.7+numpy==2.5.4+opencv-python==4.14.0.94+packaging==26.3+piexif==1.1.3+pillow==12.3.0+platformdirs==4.13.5+protobuf==7.36.2+pygments==2.21.0+pyparsing==3.3.3+python-dateutil==3.0.0+pyyaml==6.0.3+regex==2026.9.29+requests==2.34.2+rich==15.0.0+safetensors==0.8.0+sentencepiece==0.2.2+setuptools==84.2.1+shellingham==1.5.4+six==1.17.0+sympy==1.14.0+tokenizers==0.23.3+toml==0.10.2+torch==2.13.0+tqdm==4.70.1+transformers==5.19.0+typer==0.27.3+typing-extensions==4.16.0+tzdata==2026.5+urllib3==2.8.0diff --git a/webapp/docs/images.md b/webapp/docs/images.mdindex e1dbc35..0bda9dd 100644--- a/webapp/docs/images.md+++ b/webapp/docs/images.md@@ -43,3 +43,13 @@ Keys on the canvas, with a box selected:[[shortcuts:canvas]]A Layout render needs at least one box.++## FLUX 3 Klein++Choose **FLUX 3 Q8 / Standard** to make an image from text, or add reference images to edit them. Describe the complete scene you want. Standard uses 16 steps. **Base Quality** uses a separate model at 50 steps and takes longer.++Q8 is the recommended quality. Q6 uses less memory; Q4 supports 24 GB Macs with a small image size and one reference. 32 GB or more is recommended. The first run downloads about 9.9 GB for Q8, 7.6 GB for Q6 or 5.3 GB for Q4, plus the image engine. Stop cancels setup or rendering; a later run resumes downloads. After that, an image takes about 50 seconds on an M4 Max with 64 GB.++The model uses the FLUX Kommunity License, separate from the app's MIT licence. Read and accept it on first use. Commercial output generation is permitted for users below USD 5 million gross annualized revenue including affiliates, subject to the full terms. Review images before sharing them and make any legally required AI disclosures.++Your images appear in the gallery. Choose **Animate** to send one to image-to-video. FLUX.1 and Qwen LoRAs cannot be used with this model.diff --git a/webapp/index.html b/webapp/index.htmlindex eab82fb..908d8c3 100644--- a/webapp/index.html+++ b/webapp/index.html@@ -2322,7 +2322,7 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea>here), but the hint now says text-only is a real optiontoo, in plain words. --><h2>Make or change a picture- <span class="h2-hint">Drop a photo to edit it, or leave the slots empty and describe one in words below · Ideogram 4 makes pictures from text alone</span>+ <span class="h2-hint">Drop a photo to edit it, or leave the slots empty and describe one in words below · FLUX 3 Klein and Ideogram 4 make pictures from text alone</span></h2><div class="studio-ref-grid" id="imgStudioRefs"><div class="studio-ref-slot" data-slot="0">@@ -2599,6 +2599,12 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea><option value="qwen_edit_lightning_inline" selected>Reference Edit — Fast (image-to-image, Lightning 4-step, ~1:20, default, multi-ref)</option><option value="qwen_edit_inline">Reference Edit — Standard (image-to-image, 8-step Q6, ~2:05, no LoRA)</option><option value="qwen_edit_high_inline">Reference Edit — Quality (image-to-image, 40-step Q8 + CFG, ~3:50, final renders)</option>+ <option value="flux3_distilled_q8">FLUX 3 Q8 / Standard</option>+ <option value="flux3_distilled_q6">FLUX 3 Q6 / Standard</option>+ <option value="flux3_distilled_q4">FLUX 3 Q4 / Standard</option>+ <option value="flux3_base_q8">FLUX 3 Q8 / Base Quality</option>+ <option value="flux3_base_q6">FLUX 3 Q6 / Base Quality</option>+ <option value="flux3_base_q4">FLUX 3 Q4 / Base Quality</option><option value="ideogram4_inline">Ideogram 4 — typography & layout (text-in-image; optional reference bridge)</option><!-- HiDream-O1 hidden 2026-05-28 (issue #15): the engine expects astandalone lab-repo clone at ~/HIDREAM-O1-MLX-LAB-active/.venv@@ -2618,11 +2624,13 @@ The same wizard walks out of frame. Audio: footsteps on leaves."></textarea></div></div>+ <p id="flux3Notice" class="hint" hidden>FLUX 3 Klein by Black Forest Labs. Free. Standard: 16 steps. Base Quality: 50 steps, separate download. Q8 recommended; Q6 uses less memory. 32 GB Mac recommended; 24 GB with small Q4 images and one reference. <button type="button" class="ghost-btn" onclick="openLicence('flux3', {readOnly:true})">FLUX Kommunity licence</button></p>+<div><div class="mini-fields"><div class="mf-cell"><span class="mf-label">Aspect</span>- <select id="imgStudioAspect" onchange="imgStudioUpdateEstimate();if(typeof ideoApplyAspect==='function')ideoApplyAspect()" style="padding:7px 9px;font-size:13px;">+ <select id="imgStudioAspect" onchange="imgStudioUpdateValidity();imgStudioUpdateEstimate();if(typeof ideoApplyAspect==='function')ideoApplyAspect()" style="padding:7px 9px;font-size:13px;"><option value="16:9" selected>16:9 — 1280×720</option><option value="4:3">4:3 — 1024×768</option><option value="1:1">1:1 — 1024×1024</option>diff --git a/webapp/js/loras.js b/webapp/js/loras.jsindex 5779a38..b21f5c9 100644--- a/webapp/js/loras.js+++ b/webapp/js/loras.js@@ -48,6 +48,7 @@ function _currentLoraModeFilter() {}// Image Studio: read the engine override + map to compat tag.const eng = (document.getElementById('imgStudioEngine')?.value || 'auto').toLowerCase();+ if (eng.startsWith('flux3_')) return 'image:flux3';if (eng.startsWith('qwen_edit')) return 'image:qwen';if (eng.startsWith('ideogram')) return 'image:ideogram';if (eng.startsWith('flux2_edit') || eng.startsWith('flux2')) return 'image:flux2';@@ -82,6 +83,7 @@ function _loraFilterLabel(tag) {case 'video': return 'LTX-Video LoRAs (active video mode)';case 'video:h3': return 'Hailuo H3 LoRAs (MiniMax H3 base — separate library)';case 'image': return 'image LoRAs (any mflux family — auto engine)';+ case 'image:flux3': return 'FLUX 3: LoRAs are not available in this image engine yet';case 'image:qwen': return 'Qwen-Image / Qwen-Image-Edit LoRAs';case 'image:ideogram': return 'Ideogram 4 LoRAs (community formats — none validated yet)';case 'image:flux2': return 'FLUX.2 LoRAs';@@ -301,7 +303,7 @@ function _serializeLoras() {// `scale_v` rides along only on a strength replayed from an older recipe// (Load Params / Finish, _restoreLoraPicker): it tells the server which// meaning of "strength" that number was written in (Codex H3-03).- const slim = _activeLoras.filter(_inLane)+ const slim = _activeLoras.filter(l => _tag !== 'image:flux3' && _inLane(l)).map(l => (typeof l.scale_v === 'number')? { path: l.path, strength: l.strength, scale_v: l.scale_v }: { path: l.path, strength: l.strength });@@ -586,6 +588,7 @@ async function refreshLoras() {}function _loraGenerationCompatible(row, modeTag) {+ if (modeTag === 'image:flux3') return false;return !(modeTag === 'video' && row && row.ltx_compatible === false);}diff --git a/webapp/js/queue.js b/webapp/js/queue.jsindex c5b0474..1786cbd 100644--- a/webapp/js/queue.js+++ b/webapp/js/queue.js@@ -4804,6 +4804,7 @@ function _displayPromptFor(prompt) {// (params.engine = "mflux/ideogram" etc.). Falls back to the raw token.function _imgEngineLabel(token) {const map = {+ 'flux3': 'FLUX 3 Klein by Black Forest Labs','mflux/ideogram': 'Ideogram 4', 'mflux/hidream': 'HiDream','mflux/qwen_edit': 'Qwen-Edit', 'mflux/flux2': 'FLUX.2', 'mflux': 'mflux'};diff --git a/webapp/js/stage.js b/webapp/js/stage.jsindex 719e772..a0a8add 100644--- a/webapp/js/stage.js+++ b/webapp/js/stage.js@@ -25,6 +25,9 @@ function imgStudioUpdateValidity() {const eng = document.getElementById('imgStudioEngine');const status = document.getElementById('imgStudioStatus');if (!btn || !eng) return;+ const flux3 = eng.value.startsWith('flux3_');+ const flux3Notice = document.getElementById('flux3Notice');+ if (flux3Notice) flux3Notice.hidden = !flux3;const refsCount = IMG_STUDIO.refs.filter(r => r && r.path).length;const needsRefs = imgStudioRequiresRefs(eng.value);let invalidReason = '';@@ -51,6 +54,12 @@ function imgStudioUpdateValidity() {// engine that actually does this.invalidReason = 'This engine composes against a photo — drop one into a slot above, or switch Engine (below) to "Ideogram 4" to make a picture from words alone.';}+ if (!invalidReason && flux3 && _IMG_HOST_RAM_GB < 32) {+ const aspect = (document.getElementById('imgStudioAspect') || {}).value || '';+ if (!aspect.endsWith('s') || refsCount > 1) {+ invalidReason = 'On a 24 GB Mac, choose Q4, a small image size and at most one reference.';+ }+ }// Non-blocking notice (does NOT disable Generate): Ideogram is text-only,// so a loaded reference is silently dropped unless the reference bridge is// on. Surface that trap with a way out (turn on the bridge, or switch to a@@ -422,6 +431,12 @@ function imgStudioRenderEnginePill() {}return;}+ if (info.lazy_install && !info.worker_installed) {+ pill.dataset.state = 'missing';+ pill.textContent = 'sets up on first use';+ pill.title = 'Generate installs the image engine, then downloads the selected model. Stop cancels either step.';+ return;+ }if (info.cached) {pill.dataset.state = 'ready';pill.innerHTML = '<svg class="ph" aria-hidden="true" style="margin-right:4px;vertical-align:-2px"><use href="#ph-check-bold"/></svg>ready';