Episode 19 (#12)
David Gyori11728752967f
diff --git a/README.md b/README.mdindex 28bc074..de9f966 100644--- a/README.md+++ b/README.md@@ -26,6 +26,7 @@ In this repo, you can find the n8n templates we created for the episodes of [AI- [Episode 16: Create AI poem videos with n8n for TikTok](episode_16)- [Episode 17: Create Shopify product videos with Seedance, ElevenLabs, Latentsync, Flux Kontext and n8n](episode_17)- [Episode 18: Scary story TikTok videos workflow](episode_18)+- [Episode 19: Run FLUX.1 Kontext [dev] with modal.com](episode_19)## serversdiff --git a/episode_19/README.md b/episode_19/README.mdnew file mode 100644index 0000000..d767fcb--- /dev/null+++ b/episode_19/README.md@@ -0,0 +1,43 @@+# Episode 19: Run FLUX.1 Kontext [dev] with modal.com++In this video, we show you how to use Modal’s serverless GPU infrastructure with n8n to do image generation with Flux Kontext Dev for free.++<table>+ <tr>+ <td>+ <a href="https://www.skool.com/ai-agents-az/about">📚 Join our Skool community for support, premium content and more!</a>+ <p>Be part of a growing community and help us create more content like this</p>+ </td>+ <td>+ <img width="548" height="596" alt="Screenshot 2025-07-29 at 3 23 33 PM" src="https://github.com/user-attachments/assets/d687b58d-92d0-44c0-93f8-7be23d3cb80c" />+ </td>+ </tr>+</table>++## Free n8n JSON workflow++- [n8n workflow to run FLUX.1 Kontext [dev] on modal.com](flux_kontext_dev_modal.json)++## Modal application++- [python modal application to run FLUX.1 Kontext [dev]](flux_kontext_dev_modal.py)++## Instructions++1. Install python3 and venv+2. Create a new virtual environment with `python3 -m venv .venv`+3. Activate the virtual environment with `source .venv/bin/activate`+4. Install modal with `pip install modal`+5. Download the [python application](flux_kontext_dev_modal.py) and put it in the same directory+6. Run `modal deploy flux_kontext_dev_modal.py` to deploy the application+7. Copy the URL of the deployed application+8. Add the URL to your n8n workflow in the `Configure me` node and run the workflow++## Additional resources++- [Join n8n](https://n8n.partnerlinks.io/fenoo5ekqs1g)+- [Modal.com](https://modal.com)++## Watch the video++[](https://www.youtube.com/watch?v=ndMi2Mo7znA)diff --git a/episode_19/flux_kontext_dev_modal.json b/episode_19/flux_kontext_dev_modal.jsonnew file mode 100644index 0000000..924fce2--- /dev/null+++ b/episode_19/flux_kontext_dev_modal.json@@ -0,0 +1,287 @@+{+ "name": "Demo: flux kontext",+ "nodes": [+ {+ "parameters": {+ "formTitle": "Image editing using self-hosted Flux Kontext dev on modal.com",+ "formFields": {+ "values": [+ {+ "fieldLabel": "Image to edit",+ "fieldType": "file",+ "acceptFileTypes": ".jpg, .png, .jpeg",+ "requiredField": true+ },+ {+ "fieldLabel": "Prompt",+ "fieldType": "textarea",+ "placeholder": "what should we change on the image?",+ "requiredField": true+ }+ ]+ },+ "options": {}+ },+ "type": "n8n-nodes-base.formTrigger",+ "typeVersion": 2.2,+ "position": [+ -1140,+ 180+ ],+ "id": "e4a4d9d8-c467-40fc-8614-7289ab7571cf",+ "name": "On form submission",+ "webhookId": "8c88ede6-1b40-4136-b0f0-869b0f3b183a"+ },+ {+ "parameters": {+ "jsCode": "return $('On form submission').first()"+ },+ "type": "n8n-nodes-base.code",+ "typeVersion": 2,+ "position": [+ -420,+ 180+ ],+ "id": "2dcf8472-347a-40ff-abc6-f796b248c702",+ "name": "Relay the uploaded image"+ },+ {+ "parameters": {+ "assignments": {+ "assignments": [+ {+ "id": "b276d1d9-cb45-4f11-b415-a1b45ec1e1cf",+ "name": "modal_server_url",+ "value": "https://gyoridavid--flux-kontext-fastapi-fastapi-app.modal.run",+ "type": "string"+ }+ ]+ },+ "options": {}+ },+ "type": "n8n-nodes-base.set",+ "typeVersion": 3.4,+ "position": [+ -880,+ 180+ ],+ "id": "95ba07dc-bd58-492a-8b56-45e8aa37ba16",+ "name": "Configure me"+ },+ {+ "parameters": {+ "assignments": {+ "assignments": [+ {+ "id": "7bbb518a-c4f1-49a5-9e72-3e9d939b131b",+ "name": "SERVER_URL",+ "value": "={{ ((u) => { let s = u.trim(); if (!/^https?:\\/\\//i.test(s)) s = 'https://' + s; const parts = s.split('/'); return parts[0] + '//' + parts[2]; })($json.modal_server_url) }}",+ "type": "string"+ }+ ]+ },+ "options": {}+ },+ "type": "n8n-nodes-base.set",+ "typeVersion": 3.4,+ "position": [+ -640,+ 180+ ],+ "id": "297dff50-3f0a-4949-a124-89d7c3e5b3ea",+ "name": "Setup default"+ },+ {+ "parameters": {+ "method": "POST",+ "url": "={{ $('Setup default').first().json.SERVER_URL }}/edit_image",+ "authentication": "genericCredentialType",+ "genericAuthType": "httpBearerAuth",+ "sendBody": true,+ "contentType": "multipart-form-data",+ "bodyParameters": {+ "parameters": [+ {+ "name": "prompt",+ "value": "={{ $('On form submission').first().json.Prompt }}"+ },+ {+ "parameterType": "formBinaryData",+ "name": "image",+ "inputDataFieldName": "Image_to_edit"+ }+ ]+ },+ "options": {+ "redirect": {+ "redirect": {}+ }+ }+ },+ "type": "n8n-nodes-base.httpRequest",+ "typeVersion": 4.2,+ "position": [+ -160,+ 180+ ],+ "id": "f59acce7-35f9-45ed-93f9-fcd92be5f496",+ "name": "Edit the image using Flux Kontext [dev]",+ "credentials": {+ "httpBearerAuth": {+ "id": "DQ3YaYoVhWYXlWfi",+ "name": "Modal.com flux kontext app"+ }+ }+ },+ {+ "parameters": {+ "operation": "binaryToPropery",+ "options": {}+ },+ "type": "n8n-nodes-base.extractFromFile",+ "typeVersion": 1,+ "position": [+ 0,+ 0+ ],+ "id": "984cb62e-1e61-4cab-aacf-c65c49d8fb24",+ "name": "Turn image to base64"+ },+ {+ "parameters": {+ "assignments": {+ "assignments": [+ {+ "id": "1ca08e29-c4d6-4693-9829-5155d7433dd8",+ "name": "mime",+ "value": "={{ $('Edit the image using Flux Kontext [dev]').last().json['Image to edit'][0].mimetype }}",+ "type": "string"+ },+ {+ "id": "bd6e6fe8-8dc4-494e-8c19-ee16c60a3a31",+ "name": "base64_data",+ "value": "={{ $json.data }}",+ "type": "string"+ }+ ]+ },+ "options": {}+ },+ "type": "n8n-nodes-base.set",+ "typeVersion": 3.4,+ "position": [+ 180,+ 180+ ],+ "id": "6c7aeb79-c0e9-4ca5-ac41-3f62dad3436a",+ "name": "Map image data"+ },+ {+ "parameters": {+ "options": {+ "formDescription": "=<h1>This is the edited image</h1>\n\n<img src=\"data:{{ $json.mime }};base64,{{ $json.base64_data }}\" style=\"max-width: 100%; height: auto;\" />\n",+ "buttonLabel": "Close the form"+ }+ },+ "type": "n8n-nodes-base.form",+ "typeVersion": 1,+ "position": [+ 420,+ 180+ ],+ "id": "c4c6c6e2-90e4-4fdc-925b-1dd46068e72c",+ "name": "Present image",+ "webhookId": "fd475be9-f768-4444-a32f-a582f81bddca"+ }+ ],+ "pinData": {},+ "connections": {+ "On form submission": {+ "main": [+ [+ {+ "node": "Configure me",+ "type": "main",+ "index": 0+ }+ ]+ ]+ },+ "Relay the uploaded image": {+ "main": [+ [+ {+ "node": "Edit the image using Flux Kontext [dev]",+ "type": "main",+ "index": 0+ }+ ]+ ]+ },+ "Configure me": {+ "main": [+ [+ {+ "node": "Setup default",+ "type": "main",+ "index": 0+ }+ ]+ ]+ },+ "Setup default": {+ "main": [+ [+ {+ "node": "Relay the uploaded image",+ "type": "main",+ "index": 0+ }+ ]+ ]+ },+ "Edit the image using Flux Kontext [dev]": {+ "main": [+ [+ {+ "node": "Turn image to base64",+ "type": "main",+ "index": 0+ }+ ]+ ]+ },+ "Turn image to base64": {+ "main": [+ [+ {+ "node": "Map image data",+ "type": "main",+ "index": 0+ }+ ]+ ]+ },+ "Map image data": {+ "main": [+ [+ {+ "node": "Present image",+ "type": "main",+ "index": 0+ }+ ]+ ]+ }+ },+ "active": false,+ "settings": {+ "executionOrder": "v1"+ },+ "versionId": "9ee36fd7-f6fa-441c-92d1-20c847a596c0",+ "meta": {+ "instanceId": "636db6b6ab21a21c6458e2137f340e33dc3e49f5a1c560c8d1e2372c227cf40e"+ },+ "id": "cyC4LG7SY2GsBjo7",+ "tags": []+}\ No newline at end of filediff --git a/episode_19/flux_kontext_dev_modal.py b/episode_19/flux_kontext_dev_modal.pynew file mode 100644index 0000000..0e559b7--- /dev/null+++ b/episode_19/flux_kontext_dev_modal.py@@ -0,0 +1,262 @@+from io import BytesIO+from pathlib import Path+from typing import Optional++import modal++# Define the container image with all necessary dependencies+diffusers_commit_sha = "00f95b9755718aabb65456e791b8408526ae6e76"++image = (+ modal.Image.from_registry(+ "nvidia/cuda:12.8.1-devel-ubuntu22.04",+ add_python="3.12",+ )+ .entrypoint([]) # remove verbose logging by base image on entry+ .apt_install("git")+ .pip_install("uv")+ .run_commands(+ f"uv pip install --system --compile-bytecode --index-strategy unsafe-best-match accelerate~=1.8.1 git+https://github.com/huggingface/diffusers.git@{diffusers_commit_sha} huggingface-hub[hf-transfer]~=0.33.1 Pillow~=11.2.1 safetensors~=0.5.3 transformers~=4.53.0 sentencepiece~=0.2.0 torch==2.7.1 optimum-quanto==0.2.7 fastapi[standard]==0.115.4 python-multipart==0.0.12 --extra-index-url https://download.pytorch.org/whl/cu128"+ )+)++MODEL_NAME = "black-forest-labs/FLUX.1-Kontext-dev"+MODEL_REVISION = "f9fdd1a95e0dfd7653cb0966cda2486745122695"++CACHE_DIR = Path("/cache")+cache_volume = modal.Volume.from_name("hf-hub-cache", create_if_missing=True)+volumes = {CACHE_DIR: cache_volume}++secrets = [modal.Secret.from_name("flux-app-secrets", required_keys=["HF_TOKEN"])]++image = image.env(+ {+ "HF_HUB_ENABLE_HF_TRANSFER": "1", # Allows faster model downloads+ "HF_HOME": str(CACHE_DIR), # Points the Hugging Face cache to a Volume+ }+)++app = modal.App("flux-kontext-fastapi")++with image.imports():+ import torch+ import os+ from diffusers import FluxKontextPipeline+ from diffusers.utils import load_image+ from PIL import Image+ from fastapi import FastAPI, File, UploadFile, Form, HTTPException+ from fastapi.responses import Response++ image=image,+ cpu="0.5",+ memory="2GiB",+ gpu="L40s",+ volumes=volumes,+ secrets=secrets,+ scaledown_window=120,+ timeout=10 * 60, # 10 minutes+)+class FluxKontextModel:+ @modal.enter()+ def enter(self):+ print(f"Downloading {MODEL_NAME} if necessary...")++ dtype = torch.bfloat16+ self.device = "cuda"++ self.pipe = FluxKontextPipeline.from_pretrained(+ MODEL_NAME,+ revision=MODEL_REVISION,+ torch_dtype=dtype,+ cache_dir=CACHE_DIR,+ token=os.environ.get("HF_TOKEN"),+ ).to(self.device)++ @modal.method()+ def inference(+ self,+ image_bytes: bytes,+ prompt: str,+ width: int = 1024,+ height: int = 1024,+ guidance_scale: float = 3.5,+ num_inference_steps: int = 20,+ seed: Optional[int] = None,+ ) -> bytes:+ # Use provided seed or generate a random one+ if seed is not None:+ generator = torch.Generator(device=self.device).manual_seed(seed)+ else:+ generator = torch.Generator(device=self.device)++ init_image = load_image(Image.open(BytesIO(image_bytes)))++ image = self.pipe(+ width=width,+ height=height,+ image=init_image,+ prompt=prompt,+ guidance_scale=guidance_scale,+ num_inference_steps=num_inference_steps,+ output_type="pil",+ generator=generator,+ ).images[0]++ byte_stream = BytesIO()+ image.save(byte_stream, format="PNG")+ image_bytes = byte_stream.getvalue()++ return image_bytes++# Create a separate FastAPI app to handle the web interface[email protected](image=image, volumes=volumes, secrets=secrets, cpu="0.5", memory="2GiB")[email protected]_app()+def fastapi_app():+ from fastapi import Depends, FastAPI, File, UploadFile, Form, HTTPException, status+ from fastapi.responses import Response+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials+ from PIL import Image+ from io import BytesIO++ web_app = FastAPI(+ title="Flux Kontext Image Editor",+ description="Edit images using Flux Kontext Dev model",+ version="1.0.0",+ )++ @web_app.post("/edit_image")+ async def edit_image(+ image: UploadFile = File(..., description="Input image file"),+ prompt: str = Form(..., description="Text prompt describing the desired edit"),+ token: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer(auto_error=False)),+ guidance_scale: float = Form(+ 3.5, description="Guidance scale (higher = more prompt adherence)"+ ),+ num_inference_steps: int = Form(20, description="Number of inference steps"),+ seed: int = Form(None, description="Random seed for reproducible results"),+ ):+ """+ Edit an image using Flux Kontext Dev model.++ - **image**: Upload an image file (PNG, JPG, JPEG)+ - **prompt**: Text description of how you want to edit the image+ - **guidance_scale**: Controls how closely the model follows the prompt (default: 3.5)+ - **num_inference_steps**: Number of denoising steps (default: 20)+ - **seed**: Optional seed for reproducible results+ """++ if os.environ.get("BEARER_TOKEN", False):+ if not token or token.credentials != os.environ["BEARER_TOKEN"]:+ raise HTTPException(+ status_code=status.HTTP_401_UNAUTHORIZED,+ detail="Incorrect bearer token",+ headers={"WWW-Authenticate": "Bearer"},+ )+++ try:+ if image.content_type not in ["image/png", "image/jpeg", "image/jpg"]:+ raise HTTPException(+ status_code=400,+ detail="Invalid file type. Please upload a PNG or JPEG image.",+ )++ image_bytes = await image.read()++ # Validate image size+ if len(image_bytes) > 10 * 1024 * 1024: # 10MB limit+ raise HTTPException(+ status_code=400,+ detail="Image file too large. Please upload an image smaller than 10MB.",+ )++ pil_image = Image.open(BytesIO(image_bytes))+ width, height = pil_image.size++ aspect_ratio_float = width / height+ # https://docs.bfl.ai/kontext/kontext_text_to_image#flux-1-kontext-text-to-image-parameters+ min_ratio = 3 / 7+ max_ratio = 7 / 3++ if aspect_ratio_float < min_ratio or aspect_ratio_float > max_ratio:+ raise HTTPException(+ status_code=400,+ detail=f"Invalid aspect ratio. Image aspect ratio ({width}:{height}) must be between 3:7 and 7:3. Current ratio: {aspect_ratio_float:.2f}",+ )++ model = FluxKontextModel()+ result_bytes = model.inference.remote(+ width=width,+ height=height,+ image_bytes=image_bytes,+ prompt=prompt,+ guidance_scale=guidance_scale,+ num_inference_steps=num_inference_steps,+ seed=seed,+ )++ return Response(+ content=result_bytes,+ media_type="image/png",+ headers={"Content-Disposition": "inline; filename=edited_image.png"},+ )++ except Exception as e:+ raise HTTPException(+ status_code=500, detail=f"Error processing image: {str(e)}"+ )++ return web_app+++# ## CLI Interface+# You can test the model locally using the CLI interface.+# Run with: modal run flux_fastapi.py --prompt "your prompt here" --image-path "path/to/image.jpg" --output-path "path/to/output.jpg"[email protected]_entrypoint()+def main(+ image_path: str = "demo_images/dog.png",+ output_path: str = "/tmp/edited_image.png",+ prompt: str = "A cute dog wizard inspired by Gandalf from Lord of the Rings, featuring detailed fantasy elements in Studio Ghibli style",+ guidance_scale: float = 3.5,+ num_inference_steps: int = 20,+ seed: Optional[int] = None,+):+ """+ Test the Flux Kontext model locally via CLI.+ """+ print(f"🎨 Reading input image from {image_path}")++ try:+ input_image_bytes = Path(image_path).read_bytes()+ except FileNotFoundError:+ print(f"❌ Error: Image file not found at {image_path}")+ return++ pil_image = Image.open(BytesIO(input_image_bytes))+ width, height = pil_image.size++ aspect_ratio_float = width / height+ # https://docs.bfl.ai/kontext/kontext_text_to_image#flux-1-kontext-text-to-image-parameters+ min_ratio = 3 / 7+ max_ratio = 7 / 3++ if aspect_ratio_float < min_ratio or aspect_ratio_float > max_ratio:+ print(f"❌ Error: Invalid aspect ratio. Image aspect ratio ({width}:{height}) must be between 3:7 and 7:3. Current ratio: {aspect_ratio_float:.2f}")+ return++ print(f"🎨 Editing image with prompt: {prompt}")++ model = FluxKontextModel()+ output_image_bytes = model.inference.remote(+ image_bytes=input_image_bytes,+ prompt=prompt,+ guidance_scale=guidance_scale,+ num_inference_steps=num_inference_steps,+ seed=seed,+ )++ print(f"🎨 Saving output image to {output_path}")+ output_path.write_bytes(output_image_bytes)++ print("✅ Image editing completed successfully!")