{
  "name": "crAIzy chAIns · SOULREADERPLAY (RERUN)",
  "connections": {
    "Seed input": {
      "main": [
        [
          {
            "node": "Basic LLM Chain",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Basic LLM Chain": {
      "main": [
        [
          {
            "node": "Nouns to items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Nouns to items": {
      "main": [
        [
          {
            "node": "Wikimedia Commons",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download Image": {
      "main": [
        [
          {
            "node": "Batch 1-by-1",
            "type": "main",
            "index": 0
          },
          {
            "node": "💾 Foto speichern",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Batch 1-by-1": {
      "main": [
        [
          {
            "node": "Aggregate Results (Code",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Compute Brightness",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Results (Code": {
      "main": [
        [
          {
            "node": "Basic LLM Chain1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write Next Text": {
      "main": [
        [
          {
            "node": "Save Post Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Script Writer Final": {
      "main": [
        [
          {
            "node": "Save Script",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Script": {
      "main": [
        [
          {
            "node": "🧩 Ergebnis zusammenführen",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Post Text": {
      "main": [
        [
          {
            "node": "Script Writer Final",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Compute Brightness": {
      "main": [
        [
          {
            "node": "Batch 1-by-1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GenKI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Basic LLM Chain",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "GenKI Chat Model1": {
      "ai_languageModel": [
        [
          {
            "node": "Basic LLM Chain1",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "GenKI Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "Write Next Text",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "GenKI Chat Model3": {
      "ai_languageModel": [
        [
          {
            "node": "Script Writer Final",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Commons → Pexels-Format": {
      "main": [
        [
          {
            "node": "Download Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wikimedia Commons": {
      "main": [
        [
          {
            "node": "Commons → Pexels-Format",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "🔧 Matrix lesen": {
      "main": [
        [
          {
            "node": "Write Next Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Basic LLM Chain1": {
      "main": [
        [
          {
            "node": "🔧 Matrix lesen",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "🧩 Ergebnis zusammenführen": {
      "main": [
        [
          {
            "node": "Save Script -> Build HTML",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Script -> Build HTML": {
      "main": [
        [
          {
            "node": "Build HTML -> Convert to File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build HTML -> Convert to File": {
      "main": [
        [
          {
            "node": "💾 Seite speichern",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "💾 Seite speichern": {
      "main": [
        [
          {
            "node": "📋 meta.json bauen",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "📋 meta.json bauen": {
      "main": [
        [
          {
            "node": "💾 meta speichern",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "💾 meta speichern": {
      "main": [
        [
          {
            "node": "🎙️ Sprechtext Skript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "🎙️ Sprechtext Skript": {
      "main": [
        [
          {
            "node": "🔊 TTS Skript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "🔊 TTS Skript": {
      "main": [
        [
          {
            "node": "🧩 Audio Skript zusammensetzen",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "🧩 Audio Skript zusammensetzen": {
      "main": [
        [
          {
            "node": "💾 Audio Skript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "▶️ Start": {
      "main": [
        [
          {
            "node": "⚙️ Rerun-Konfiguration",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "⚙️ Rerun-Konfiguration": {
      "main": [
        [
          {
            "node": "Seed input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": [],
  "active": false,
  "nodes": [
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "49cf6609-ad34-4750-a9aa-835ff5ed76b2",
              "name": "seed_script",
              "value": "={{ $json.chatInput || $json.seed_text }}",
              "type": "string"
            },
            {
              "id": "b53d8ec2-6279-4972-8529-cca715a38e00",
              "name": "loop_index",
              "value": "={{ Number($json.loop_index) || 0 }}",
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -16,
        -16
      ],
      "id": "b5e030cd-1f56-482e-84eb-e288b0a7104a",
      "name": "Seed input",
      "notes": "🔁 RERUN: Seed-Text aus der Konfiguration (statt Chat-Eingabe).",
      "notesInFlow": true
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Extrahiere aus dem folgenden Text GENAU 5 deutsche Substantive (einzelne Wörter).\nKeine Eigennamen, keine Verben, keine Adjektive.\n\nAntworte NUR als gültiges JSON in genau diesem Format:\n{\"nouns\":[\"Wort1\",\"Wort2\",\"Wort3\",\"Wort4\",\"Wort5\"]}\n\nText:\n{{$json.seed_script}}",
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.9,
      "position": [
        192,
        -16
      ],
      "id": "c25409db-c96d-437f-a5bb-c25cf9f779c7",
      "name": "Basic LLM Chain"
    },
    {
      "parameters": {
        "jsCode": "let raw = ($json.text || \"\").trim();\n\n// entfernt ```json ... ``` oder auch ``json ... ``\nraw = raw\n  .replace(/^```json\\s*/i, \"\")\n  .replace(/^```/i, \"\")\n  .replace(/^``json\\s*/i, \"\")\n  .replace(/^``/i, \"\")\n  .replace(/```$/i, \"\")\n  .replace(/``$/i, \"\")\n  .trim();\n\nconst parsed = JSON.parse(raw);\nconst nouns = parsed.nouns || [];\n\nif (!Array.isArray(nouns) || nouns.length === 0) {\n  throw new Error(\"Keine nouns gefunden. LLM Output war: \" + raw);\n}\n\nreturn nouns.map((noun, i) => ({\n  json: {\n    noun,\n    noun_index: i,\n    seed_script: $json.seed_script,\n    loop_index: $json.loop_index\n  }\n}));"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        544,
        -16
      ],
      "id": "85c73097-e12e-4bec-b0c7-583e3dfb0f9e",
      "name": "Nouns to items"
    },
    {
      "parameters": {
        "url": "={{$json.photos[0].src.large}}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file",
              "outputPropertyName": "image"
            }
          }
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "User-Agent",
              "value": "craizy-chains-rerun/1.0 (https://craizy.studio; hello@craizy.studio)"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        960,
        -16
      ],
      "id": "cd041a2a-7b13-4051-9b79-fcba1a16320e",
      "name": "Download Image",
      "notes": "🔁 RERUN: Wikimedia verlangt einen User-Agent.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1184,
        -16
      ],
      "id": "8d8c71a5-354a-4bb5-a6d8-983e1a4cfefb",
      "name": "Batch 1-by-1"
    },
    {
      "parameters": {
        "jsCode": "const images = items.map(it => ({\n  noun: it.json.noun,\n  noun_index: it.json.noun_index,\n  url: it.json.photos?.[0]?.src?.large,\n  brightness: it.json.brightness,\n  mood: it.json.mood,\n  philosophy: it.json.philosophy,\n  tags: it.json.tags || []\n}));\n\nconst avgBrightness =\n  images.reduce((sum, x) => sum + (x.brightness ?? 5), 0) / images.length;\n\nconst moodCounts = images.reduce((acc, x) => {\n  acc[x.mood] = (acc[x.mood] || 0) + 1;\n  return acc;\n}, {});\n\nreturn [{\n  json: {\n    seed_script: items[0].json.seed_script,\n    loop_index: items[0].json.loop_index,\n    images,\n    avgBrightness,\n    moodCounts\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1472,
        -320
      ],
      "id": "d7dcff6d-46ee-478b-b5ae-39ce8c2718d9",
      "name": "Aggregate Results (Code"
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Schreibe ALLES auf DEUTSCH.\nDu bekommst 5 Bilder (Stimmung, Helligkeit, Tags, Philosophie pro Bild).\nErstelle eine emotionale Matrix, die die 5 Bilder als zusammenhängende Idee interpretiert.\n\nGib NUR gültiges JSON zurück:\n\n{\n  \"headline\": \"Kurzer poetischer Titel (Deutsch)\",\n  \"thesis\": \"1-2 Sätze auf Deutsch: Was verbindet diese 5 Bilder?\",\n  \"matrix\": [\n    {\n      \"image_index\": 0,\n      \"dominant_emotion\": \"1 deutsches Wort\",\n      \"brightness\": 0-10,\n      \"philosophical_note\": \"1 Satz auf Deutsch\"\n    }\n  ],\n  \"overall_tone\": \"positive|neutral|dark\",\n  \"writing_prompt\": \"1 deutscher Satz: Wie soll der nächste Text geschrieben werden (Genre + Stil)?\"\n}\n\nBILD-DATEN:\n{{ JSON.stringify({ images: $json.images, avgBrightness: $json.avgBrightness, moodCounts: $json.moodCounts }) }}",
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.9,
      "position": [
        1680,
        -320
      ],
      "id": "6b2a5505-2015-4fc6-9514-8ed2ff29b2d3",
      "name": "Basic LLM Chain1",
      "notes": "🔧 Repariert: Bild-Daten aus „Aggregate Results“ werden jetzt angehängt (vorher sah das Modell keine Bilder).",
      "notesInFlow": true
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Schreibe einen kurzen Beitrag auf DEUTSCH (120–180 Wörter).\nNutze die emotionale Matrix als Regieanweisung.\nDer Text soll eigenständig funktionieren, auch wenn er banal wirkt.\n\nStilvorgabe (aus der Matrix):\n{{$json.writing_prompt}}\n\nNutze diese Bild-Infos als Inspiration:\n{{ JSON.stringify($json.images) }}\n\nGib NUR den Text zurück (kein JSON, keine Überschriften).",
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.9,
      "position": [
        2032,
        -320
      ],
      "id": "1cecec7f-1e90-4b4a-9676-3e3434f8ea22",
      "name": "Write Next Text",
      "notes": "🔧 Repariert: Ausdrucks-Markierung (=) fehlte – {{…}} ging sonst wörtlich ans Modell.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Schreibe aus dem folgenden Beitrag ein gesprochenes Skript auf DEUTSCH.\nDauer ca. 45–70 Sekunden.\nKurzes Intro + klarer Schluss.\nKeine Zeitmarken, keine Musik, keine Regieanweisungen.\n\nBEITRAG:\n{{$json.post_text}}",
        "batching": {}
      },
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.9,
      "position": [
        2544,
        -320
      ],
      "id": "d552db88-7d68-4603-91c9-9d0f2c57a098",
      "name": "Script Writer Final"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "bcc777b0-29f8-4279-8da9-4f66bd0735fc",
              "name": "script_text",
              "value": "={{$json.text}}",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2944,
        -320
      ],
      "id": "4e1bdb5f-cb5d-4f0d-af65-7e5f9ae42a0a",
      "name": "Save Script"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "b1bc1804-e22b-4d43-9725-1ed70f98cf0a",
              "name": "post_text",
              "value": "={{$json.text}}",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2304,
        -320
      ],
      "id": "4f064d5a-df63-43b6-b0a5-f9ccb53a53c4",
      "name": "Save Post Text"
    },
    {
      "parameters": {
        "jsCode": "// Erwartet Binary: image (von Download Image)\n// 🔁 RERUN: n8n 2.x legt Binärdaten auf der Platte ab ($binary.image.data ist leer) → Puffer über den Helper\nif (!$binary?.image) {\n  throw new Error(\"Kein Binary.image gefunden. Prüfe Download Image Node.\");\n}\n\nconst buf = await this.helpers.getBinaryDataBuffer(0, 'image');\n\n// Schneller Helligkeits-Proxy: Durchschnitt über Byte-Samples\nlet sum = 0;\nconst step = Math.max(1, Math.floor(buf.length / 20000)); // ~20k Samples\nlet count = 0;\n\nfor (let i = 0; i < buf.length; i += step) {\n  sum += buf[i];\n  count++;\n}\n\nconst avg = sum / count;           // 0..255\nconst brightness = Math.round((avg / 255) * 10); // 0..10\n\nlet mood = \"neutral\";\nif (brightness >= 7) mood = \"positive\";\nif (brightness <= 3) mood = \"dark\";\n\nconst philosophy =\n  mood === \"positive\"\n    ? \"Das Licht wirkt wie eine Einladung, die Welt für einen Moment leichter zu nehmen.\"\n    : mood === \"dark\"\n      ? \"Im Dunkel liegt keine Antwort – aber oft die ehrlichste Frage.\"\n      : \"Neutralität ist der Zwischenraum, in dem Bedeutung erst entsteht.\";\n\nreturn [{\n  json: {\n    ...$json,\n    brightness,\n    mood,\n    philosophy,\n    tags: [$json.noun || \"bild\", mood]\n  },\n  binary: $binary\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1616,
        272
      ],
      "id": "4f5961d1-95fd-4a5f-be9e-f854d6b754a8",
      "name": "Compute Brightness",
      "notes": "🔧 Repariert: war deaktiviert – ohne ihn fehlten Helligkeit, Stimmung und Philosophie. Helligkeits-Formel des Teams unverändert.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "jsCode": "if (!$binary) throw new Error(\"Kein $binary vorhanden.\");\nconst keys = Object.keys($binary);\nif (keys.length === 0) throw new Error(\"Kein Binary gefunden.\");\n\nconst key = keys[0];\nconst bin = $binary[key];\nif (!bin?.data) throw new Error(⁠ Binary '${key}' hat keine data. Keys: ${keys.join(\", \")} ⁠);\n\nconst buf = Buffer.from(bin.data, 'base64');\n\nlet sum = 0;\nconst step = Math.max(1, Math.floor(buf.length / 20000));\nlet count = 0;\n\nfor (let i = 0; i < buf.length; i += step) { sum += buf[i]; count++; }\n\nconst avg = sum / count;           // 0..255\nconst brightness = Math.round((avg / 255) * 10);\n\nlet mood = \"neutral\";\nif (brightness >= 7) mood = \"positive\";\nif (brightness <= 3) mood = \"dark\";\n\nreturn [{\n  json: { ...$json, binary_key_used: key, brightness, mood },\n  binary: $binary\n}];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1456,
        400
      ],
      "id": "06568c1f-db1e-4971-a87a-cac5e5b7d41c",
      "name": "Compute Brightness1"
    },
    {
      "parameters": {
        "content": "## 🔁 RERUN-FASSUNG (lokal)\nLogik & Prompts wie in der Abgabe. Ersetzt: Gemini → GenKI-Gateway, Pexels → Wikimedia Commons (gleiches Antwortformat), Chat-Eingabe → Seed-Text in der Konfiguration (Loop: Skript wird nächster Seed), + Seite (Team-Code „Build HTML“), meta.json, Vorlesen → rerun/_roh/.\n🔧 Repariert: Helligkeits-Node war deaktiviert; Matrix bekam keine Bilddaten; Matrix-JSON wurde nicht gelesen; „Write Next Text“ ohne Ausdrucks-Markierung.\n\n## 🔗 crAIzy chAIns – Archiv\n\n# SOULREADERPLAY\n\n**Team:** SOULREADER\n**Crazy-Level:** completely crAIzy, more than you'd expect\n\n> Aus einem Text werden 5 Nomen, aus Nomen Bilder, aus Bildern Helligkeit & Stimmung – und daraus ein neuer Text. Endlos.\n\nEntstanden im Seminar *crAIzy chAIns* (UdK Berlin, WiSe 2025/26). Gebaut als **agentische Rube-Goldberg-Maschine**: nicht effizient, sondern absichtlich verschlungen. Modelle & Prompts sind Stand 2025/26 – **kein Produktiv-Template, sondern ein Spielzeug**.\n\n### Setup-Checkliste\n- **Pexels** – Header „Authorization“ = eigener Pexels-API-Key (pexels\n- **Google Gemini Chat Model** – Credential „Google Gemini (PaLM) API“ anlegen (Key: aistudio\n\nAlle Stellen sind im Canvas mit **⚙️ SETUP** markiert. Es sind keine Zugangsdaten enthalten.\n\ncraizy.studio",
        "height": 900,
        "width": 680,
        "color": 6
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -1080,
        -360
      ],
      "id": "16a9a3e5-5816-4e07-8ab1-94611f5db3eb",
      "name": "README crAIzy chAIns"
    },
    {
      "id": "25b90267-a100-405f-9423-4ddd0536ea83",
      "name": "GenKI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        192,
        176
      ],
      "notes": "🔁 RERUN: GenKI-Gateway statt Google Gemini (ursprünglich Ollama gemma3:27b).",
      "notesInFlow": true,
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('⚙️ Rerun-Konfiguration').first().json.model_small }}"
        },
        "options": {
          "maxTokens": 4000,
          "timeout": 300000,
          "maxRetries": 3
        }
      }
    },
    {
      "id": "1236a348-b65e-42d6-9736-4dacaf703216",
      "name": "GenKI Chat Model1",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1616,
        -112
      ],
      "notes": "🔁 RERUN: GenKI-Gateway statt Google Gemini (ursprünglich Ollama gemma3:27b).",
      "notesInFlow": true,
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('⚙️ Rerun-Konfiguration').first().json.model_main }}"
        },
        "options": {
          "maxTokens": 4000,
          "timeout": 300000,
          "maxRetries": 3
        }
      }
    },
    {
      "id": "0342afb0-9e8c-4bd1-9e30-0cb14e8bc8c0",
      "name": "GenKI Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        1968,
        -112
      ],
      "notes": "🔁 RERUN: GenKI-Gateway statt Google Gemini (ursprünglich Ollama gemma3:27b).",
      "notesInFlow": true,
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('⚙️ Rerun-Konfiguration').first().json.model_main }}"
        },
        "options": {
          "maxTokens": 4000,
          "timeout": 300000,
          "maxRetries": 3
        }
      }
    },
    {
      "id": "cd58f25b-4067-4951-abc0-1e7ce76d10f3",
      "name": "GenKI Chat Model3",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        2480,
        -112
      ],
      "notes": "🔁 RERUN: GenKI-Gateway statt Google Gemini (ursprünglich Ollama gemma3:27b).",
      "notesInFlow": true,
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('⚙️ Rerun-Konfiguration').first().json.model_main }}"
        },
        "options": {
          "maxTokens": 4000,
          "timeout": 300000,
          "maxRetries": 3
        }
      }
    },
    {
      "parameters": {
        "url": "https://commons.wikimedia.org/w/api.php",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "action",
              "value": "query"
            },
            {
              "name": "format",
              "value": "json"
            },
            {
              "name": "generator",
              "value": "search"
            },
            {
              "name": "gsrnamespace",
              "value": "6"
            },
            {
              "name": "gsrlimit",
              "value": "5"
            },
            {
              "name": "prop",
              "value": "imageinfo"
            },
            {
              "name": "iiprop",
              "value": "url|mime|extmetadata"
            },
            {
              "name": "iiurlwidth",
              "value": "960"
            },
            {
              "name": "iiextmetadatafilter",
              "value": "LicenseShortName|Artist"
            },
            {
              "name": "gsrsearch",
              "value": "={{ $json.noun }} filetype:bitmap"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "User-Agent",
              "value": "craizy-chains-rerun/1.0 (https://craizy.studio; hello@craizy.studio)"
            }
          ]
        },
        "options": {
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 2500
            }
          }
        }
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        752,
        -16
      ],
      "id": "479cafc1-0b62-4bf2-94e8-c9926530dda5",
      "name": "Wikimedia Commons",
      "notes": "🔁 RERUN: Pexels → Wikimedia Commons (freie Lizenzen, kein Key nötig). Suche mit dem Nomen, wie im Original.",
      "notesInFlow": true,
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "id": "950ce14b-c55f-42df-a5f8-59fbe7422740",
      "name": "Commons → Pexels-Format",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        852,
        184
      ],
      "parameters": {
        "jsCode": "// 🔁 RERUN: Wikimedia-Commons-Antwort → gleiche Form wie die Pexels-Antwort ({ photos: [ { src: { large } } ] }),\n// damit die Team-Nodes dahinter unverändert bleiben. Wie im Original (per_page=1): erster Treffer, nur Fotos (JPEG).\nconst strip = (s) => String(s || '').replace(/<[^>]+>/g, '').replace(/\\s+/g, ' ').trim();\nconst nouns = $('Nouns to items').all();\nconst out = [];\nfor (let n = 0; n < $input.all().length; n++) {\n  let j = $input.all()[n].json;\n  // Commons meldet „Search is currently too busy“ mit HTTP 200 → hier nachfassen\n  for (let t = 0; j.error && t < 6; t++) {\n    await new Promise((r) => setTimeout(r, 5000 * (t + 1)));\n    const q = Object.assign({}, {\"action\": \"query\", \"format\": \"json\", \"generator\": \"search\", \"gsrnamespace\": \"6\", \"gsrlimit\": \"5\", \"prop\": \"imageinfo\", \"iiprop\": \"url|mime|extmetadata\", \"iiurlwidth\": \"960\", \"iiextmetadatafilter\": \"LicenseShortName|Artist\"}, { gsrsearch: nouns[n].json.noun + ' filetype:bitmap' });\n    j = await this.helpers.httpRequest({ url: 'https://commons.wikimedia.org/w/api.php', qs: q, json: true, headers: { 'User-Agent': 'craizy-chains-rerun/1.0 (https://craizy.studio; hello@craizy.studio)' } });\n  }\n  if (j.error) throw new Error('Commons: ' + j.error.info);\n  const pages = Object.values(j.query?.pages || {}).sort((a, b) => a.index - b.index);\n  const p = pages.find((x) => /jpeg/.test(x.imageinfo?.[0]?.mime || '')) || pages[0];\n  if (!p) throw new Error('Commons: kein Bild gefunden für ' + nouns[n].json.noun);\n  const i = p.imageinfo[0], m = i.extmetadata || {};\n  out.push({ json: { page: 1, per_page: 1, total_results: pages.length, photos: [ {\n    id: p.pageid, url: i.descriptionurl, alt: p.title.replace(/^File:/, '').replace(/\\.[a-z]+$/i, ''),\n    photographer: strip(m.Artist?.value), license: strip(m.LicenseShortName?.value),\n    src: { large: i.thumburl || i.url } } ] } });\n}\nreturn out;"
      }
    },
    {
      "id": "106ea6fd-a65e-4ce5-8ae9-a344f8994a84",
      "name": "💾 Foto speichern",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        960,
        364
      ],
      "parameters": {
        "operation": "write",
        "fileName": "={{ $('⚙️ Rerun-Konfiguration').first().json.out_dir }}/soulreaderplay_{{ $('⚙️ Rerun-Konfiguration').first().json.run_id }}_loop{{ $('⚙️ Rerun-Konfiguration').first().json.loop_index }}_foto{{ $itemIndex + 1 }}.jpg",
        "dataPropertyName": "image",
        "options": {}
      }
    },
    {
      "id": "ed0f4b23-9549-4cf5-9557-0f8b5b7fa0c2",
      "name": "🔧 Matrix lesen",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1860,
        -120
      ],
      "parameters": {
        "jsCode": "// JSON aus der Modellantwort; tolerant, falls das Modell Anführungszeichen im Text nicht maskiert\nconst parse = (s) => { s = String(s || '').replace(/```(json)?/g, '');\n  try { return JSON.parse(s.match(/\\{[\\s\\S]*\\}/)[0]); } catch (e) {}\n  const o = {}; const keys = [...s.matchAll(/\"(\\w+)\"\\s*:\\s*/g)];\n  keys.forEach((k, i) => { const end = i + 1 < keys.length ? keys[i + 1].index : s.lastIndexOf('}');\n    let v = s.slice(k.index + k[0].length, end).trim().replace(/,$/, '').trim();\n    if (v.startsWith('\"') && v.endsWith('\"')) v = v.slice(1, -1).replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"');\n    o[k[1]] = v; });\n  return keys.length ? o : null; };\n// 🔧 Repariert: Die Matrix kam als Text zurück; „Write Next Text“ erwartet writing_prompt und images als Felder.\nconst m = parse($json.text) || {};\nreturn [{ json: Object.assign({}, $('Aggregate Results (Code').first().json, m) }];"
      }
    },
    {
      "id": "a1e1c7c2-282c-476e-a983-039f62a23dc9",
      "name": "🧩 Ergebnis zusammenführen",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3164,
        -320
      ],
      "parameters": {
        "jsCode": "return [{ json: Object.assign({}, $('🔧 Matrix lesen').first().json, $('Seed input').first().json,\n  { post_text: $('Save Post Text').first().json.post_text, script_text: $json.script_text }) }];"
      }
    },
    {
      "id": "7f861cda-03de-4324-a5ed-6cb8055f66e4",
      "name": "Save Script -> Build HTML",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3384,
        -320
      ],
      "parameters": {
        "jsCode": "const headline = $json.headline || `Loop ${$json.loop_index ?? \"\"}`;\nconst thesis = $json.thesis || \"\";\nconst images = $json.images || [];\nconst matrix = $json.matrix || [];\nconst writingPrompt = $json.writing_prompt || \"\";\n\nconst postText = $json.post_text || \"\";\nconst scriptText = $json.script_text || \"\";\n\nconst matrixPretty = JSON.stringify(matrix, null, 2);\n\nconst html = `<!doctype html>\n<html lang=\"de\">\n<head>\n<meta charset=\"utf-8\">\n<title>${headline}</title>\n<style>\nbody{font-family:system-ui;max-width:980px;margin:40px auto;line-height:1.45}\n.grid{display:grid;grid-template-columns:repeat(5,1fr);gap:10px;margin:16px 0}\nimg{width:100%;border-radius:14px;aspect-ratio:1/1;object-fit:cover}\n.card{padding:14px;border:1px solid #ddd;border-radius:14px;margin:14px 0}\npre{background:#111;color:#eee;padding:12px;border-radius:14px;white-space:pre-wrap}\n.small{color:#666}\n</style>\n</head>\n<body>\n\n<h1>${headline}</h1>\n<p class=\"small\">Loop #${$json.loop_index ?? \"\"}</p>\n\n<div class=\"card\">\n<h2>These</h2>\n<p>${thesis}</p>\n</div>\n\n<div class=\"card\">\n<h2>Bilder</h2>\n<div class=\"grid\">\n${images.map((i) => `<img src=\"${i.url || \"\"}\" alt=\"${i.noun || \"\"}\">`).join(\"\")}\n</div>\n</div>\n\n<div class=\"card\">\n<h2>Schreibanweisung</h2>\n<p>${writingPrompt}</p>\n</div>\n\n<div class=\"card\">\n<h2>Beitrag</h2>\n<pre>${postText}</pre>\n</div>\n\n<div class=\"card\">\n<h2>Skript</h2>\n<pre>${scriptText}</pre>\n</div>\n\n<div class=\"card\">\n<h2>Emotionale Matrix</h2>\n<pre>${matrixPretty}</pre>\n</div>\n\n</body>\n</html>`;\n\nreturn [{ json: { ...$json, html } }];"
      },
      "notes": "Code des Teams aus der Website-Fassung (unverändert).",
      "notesInFlow": true
    },
    {
      "id": "178494a1-7ef6-4e8b-9fc9-765f5d6c5078",
      "name": "Build HTML -> Convert to File",
      "type": "n8n-nodes-base.convertToFile",
      "typeVersion": 1.1,
      "position": [
        3604,
        -320
      ],
      "parameters": {
        "operation": "toText",
        "sourceProperty": "html",
        "options": {
          "fileName": "post.html"
        }
      }
    },
    {
      "id": "8192c41d-5d09-49b3-aac3-74539d7dfd64",
      "name": "💾 Seite speichern",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        3824,
        -320
      ],
      "parameters": {
        "operation": "write",
        "fileName": "={{ $('⚙️ Rerun-Konfiguration').first().json.out_dir }}/soulreaderplay_{{ $('⚙️ Rerun-Konfiguration').first().json.run_id }}_loop{{ $('⚙️ Rerun-Konfiguration').first().json.loop_index }}_seite.html",
        "dataPropertyName": "data",
        "options": {}
      }
    },
    {
      "id": "989ee740-c23f-48c8-baa2-e3ae0eb425f8",
      "name": "📋 meta.json bauen",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4044,
        -320
      ],
      "parameters": {
        "jsCode": "const c = $('⚙️ Rerun-Konfiguration').first().json;\nconst m = $('🧩 Ergebnis zusammenführen').first().json;\nconst nouns = $('Nouns to items').all().map((x) => x.json.noun);\nconst fotos = $('Commons → Pexels-Format').all().map((x, i) => { const p = x.json.photos[0];\n  return { nomen: nouns[i], titel: p.alt, autor: p.photographer, lizenz: p.license, quelle: p.url, bild: p.src.large }; });\nconst agg = $('Aggregate Results (Code').first().json;\nconst meta = { run_id: c.run_id, loop_index: Number(c.loop_index), seed: m.seed_script, nomen: nouns, fotos,\n  helligkeit: agg.images.map((x) => ({ brightness: x.brightness, mood: x.mood, philosophy: x.philosophy })),\n  avgBrightness: agg.avgBrightness, moodCounts: agg.moodCounts,\n  matrix: { headline: m.headline, thesis: m.thesis, matrix: m.matrix, overall_tone: m.overall_tone, writing_prompt: m.writing_prompt },\n  post_text: m.post_text, script_text: m.script_text,\n  modelle: { nomen: c.model_small, text: c.model_main, tts: 'chatterbox (Jade.wav)' } };\nreturn [{ json: {}, binary: { data: await this.helpers.prepareBinaryData(Buffer.from(JSON.stringify(meta, null, 2)), 'meta.json', 'application/json') } }];"
      }
    },
    {
      "id": "2556b53f-6e7f-446b-b902-460659331ac5",
      "name": "💾 meta speichern",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        4264,
        -320
      ],
      "parameters": {
        "operation": "write",
        "fileName": "={{ $('⚙️ Rerun-Konfiguration').first().json.out_dir }}/soulreaderplay_{{ $('⚙️ Rerun-Konfiguration').first().json.run_id }}_loop{{ $('⚙️ Rerun-Konfiguration').first().json.loop_index }}_meta.json",
        "dataPropertyName": "data",
        "options": {}
      }
    },
    {
      "id": "87bf535d-958b-4d8e-8f8f-c1e1535b4b6e",
      "name": "🎙️ Sprechtext Skript",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4484,
        -320
      ],
      "parameters": {
        "jsCode": "// JSON aus der Modellantwort; tolerant, falls das Modell Anführungszeichen im Text nicht maskiert\nconst parse = (s) => { s = String(s || '').replace(/```(json)?/g, '');\n  try { return JSON.parse(s.match(/\\{[\\s\\S]*\\}/)[0]); } catch (e) {}\n  const o = {}; const keys = [...s.matchAll(/\"(\\w+)\"\\s*:\\s*/g)];\n  keys.forEach((k, i) => { const end = i + 1 < keys.length ? keys[i + 1].index : s.lastIndexOf('}');\n    let v = s.slice(k.index + k[0].length, end).trim().replace(/,$/, '').trim();\n    if (v.startsWith('\"') && v.endsWith('\"')) v = v.slice(1, -1).replace(/\\\\n/g, '\\n').replace(/\\\\\"/g, '\"');\n    o[k[1]] = v; });\n  return keys.length ? o : null; };\nconst stimmen = {\"brit\": {\"voice\": \"Henry.wav\", \"lang\": \"en\"}, \"schott\": {\"voice\": \"Connor.wav\", \"lang\": \"en\"}, \"bayr\": {\"voice\": \"Axel.wav\", \"lang\": \"de\"}, \"sächs\": {\"voice\": \"Eli.wav\", \"lang\": \"de\"}, \"chines\": {\"voice\": \"Leonardo.wav\", \"lang\": \"zh\"}};\nconst standard = {\"voice\": \"Eli.wav\", \"lang\": \"de\"};\nreturn $input.all().map((it, i) => { const input = $('Save Script').first().json.script_text; const v = {\"voice\": \"Jade.wav\", \"lang\": \"de\"};\n  if (!input || input.length < 20) throw new Error('Sprechtext leer');\n  // Chinesisch: Der TTS-Server teilt nur an lateinischen Satzzeichen → ganzer Text wird ein Riesen-Chunk (Brei).\n  // Deshalb satzweise synthetisieren und danach wieder zusammensetzen.\n  const segs = v.lang === 'zh' ? input.split(/(?<=[。！？!?])/).map(s => s.trim()).filter(Boolean) : [input];\n  return segs.map((s, k) => ({ json: { input: s, voice: v.voice, language: v.lang, idx: i, seg: k, full_text: input } })); }).flat();"
      }
    },
    {
      "id": "49b4e010-d5e9-4dd3-ac06-316352dddd95",
      "name": "🔊 TTS Skript",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        4704,
        -320
      ],
      "parameters": {
        "method": "POST",
        "url": "https://tts.udk.digital/v1/audio/speech",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "options": {
          "timeout": 600000,
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ model: 'chatterbox', input: $json.input, voice: $json.voice, response_format: 'mp3', language: $json.language }) }}"
      },
      "notes": "🔁 RERUN-Zusatz: Das gesprochene Skript wird vorgelesen (UdK-Chatterbox).",
      "notesInFlow": true
    },
    {
      "id": "b1a4e586-877d-4f36-8250-548667b081da",
      "name": "🧩 Audio Skript zusammensetzen",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        4814,
        -140
      ],
      "parameters": {
        "jsCode": "// Teil-Audios (nur bei Chinesisch mehrere) je Sprechtext wieder zu einer Datei verbinden\nconst src = $('🎙️ Sprechtext Skript').all();\nconst groups = new Map();\nfor (let i = 0; i < $input.all().length; i++) { const k = src[i].json.idx;\n  if (!groups.has(k)) groups.set(k, { json: { voice: src[i].json.voice, language: src[i].json.language, input: src[i].json.full_text }, bufs: [] });\n  let b = await this.helpers.getBinaryDataBuffer(i, 'data');\n  // ID3-Kopf der Folgeteile entfernen (sonst stolpern Player/Whisper an der Naht)\n  if (groups.get(k).bufs.length && b.slice(0, 3).toString() === 'ID3') b = b.slice(10 + ((b[6] << 21) | (b[7] << 14) | (b[8] << 7) | b[9]));\n  groups.get(k).bufs.push(b); }\nconst out = [];\nfor (const g of groups.values()) out.push({ json: g.json, binary: { data: await this.helpers.prepareBinaryData(Buffer.concat(g.bufs), 'audio.mp3', 'audio/mpeg') } });\nreturn out;"
      }
    },
    {
      "id": "0431c5e8-7020-420a-9fc9-3caea531e352",
      "name": "💾 Audio Skript",
      "type": "n8n-nodes-base.readWriteFile",
      "typeVersion": 1,
      "position": [
        4924,
        -320
      ],
      "parameters": {
        "operation": "write",
        "fileName": "={{ $('⚙️ Rerun-Konfiguration').first().json.out_dir }}/soulreaderplay_{{ $('⚙️ Rerun-Konfiguration').first().json.run_id }}_loop{{ $('⚙️ Rerun-Konfiguration').first().json.loop_index }}_skript.mp3",
        "dataPropertyName": "data",
        "options": {}
      }
    },
    {
      "id": "ff657d68-e276-45c4-9da0-029a4d4d841c",
      "name": "▶️ Start",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -240,
        -64
      ],
      "parameters": {}
    },
    {
      "id": "a2d4554e-9291-4599-8abd-3c07a1be25c8",
      "name": "⚙️ Rerun-Konfiguration",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -240,
        156
      ],
      "notes": "Hier Modelle, Seed und Ausgabeordner ändern.",
      "notesInFlow": true,
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "062c5645-ccb7-40c2-a449-681699156363",
              "name": "model_main",
              "value": "cc/claude-sonnet-5",
              "type": "string"
            },
            {
              "id": "b18685d5-eebf-456c-a3a9-0e731ce17657",
              "name": "model_small",
              "value": "cc/claude-haiku-5-5",
              "type": "string"
            },
            {
              "id": "ccd94223-601e-4d47-a2e0-dca41ae48b62",
              "name": "model_vision",
              "value": "cc/claude-sonnet-5",
              "type": "string"
            },
            {
              "id": "18d3784d-29cb-4c35-a198-e34214eb1e06",
              "name": "seed",
              "value": 1881,
              "type": "number"
            },
            {
              "id": "22a1661f-edf4-4ce0-9576-8efa4a062928",
              "name": "out_dir",
              "value": "/PFAD/ZU/craizy-chains/exponate/03_soulreaderplay/rerun/_roh",
              "type": "string"
            },
            {
              "id": "0e77c3ea-bc35-4560-9e7a-54d5f4c1fdf9",
              "name": "run_id",
              "value": "={{ $now.toFormat('yyyy-MM-dd_HHmm') }}",
              "type": "string"
            },
            {
              "id": "c6673bcf-688e-456c-a910-baaa10a89e97",
              "name": "seed_text",
              "value": "Sein Blick ist vom Vorübergehn der Stäbe\nso müd geworden, daß er nichts mehr hält.\nIhm ist, als ob es tausend Stäbe gäbe\nund hinter tausend Stäben keine Welt.\n\nDer weiche Gang geschmeidig starker Schritte,\nder sich im allerkleinsten Kreise dreht,\nist wie ein Tanz von Kraft um eine Mitte,\nin der betäubt ein großer Wille steht.\n\nNur manchmal schiebt der Vorhang der Pupille\nsich lautlos auf –. Dann geht ein Bild hinein,\ngeht durch der Glieder angespannte Stille –\nund hört im Herzen auf zu sein.",
              "type": "string"
            },
            {
              "id": "c369df70-5aa3-48de-bd8a-6e012b1aa336",
              "name": "loop_index",
              "value": "0",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    }
  ]
}