{
  "name": "Local AI Video Generator in n8n That Turns a Topic Into a Shot List",
  "nodes": [
    {
      "name": "Video Idea Form",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "path": "video-prep-shot-list",
        "formTitle": "Video Prep Generator",
        "formDescription": "One topic in, script + shot list + thumbnail brief out.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Topic",
              "requiredField": true
            },
            {
              "fieldLabel": "Audience",
              "requiredField": true
            },
            {
              "fieldLabel": "Video length",
              "fieldType": "dropdown",
              "fieldOptions": {
                "values": [
                  {
                    "option": "30"
                  },
                  {
                    "option": "60"
                  },
                  {
                    "option": "180"
                  }
                ]
              },
              "requiredField": true
            },
            {
              "fieldLabel": "Telegram chat ID",
              "requiredField": true
            }
          ]
        },
        "options": {}
      },
      "id": "5222dbf0-8131-43db-9da0-0e08564c66d8"
    },
    {
      "name": "Clean Input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "parameters": {
        "jsCode": "const f = $input.first().json;\nconst pick = (...keys) => { for (const k of keys) if (f[k] !== undefined && String(f[k]).trim() !== '') return String(f[k]).trim(); return ''; };\nconst topic = pick('Topic').replace(/\\s+/g, ' ');\nconst audience = pick('Audience') || 'general viewers';\nconst lengthSeconds = parseInt(pick('Video length'), 10) || 60;\nconst chatId = pick('Telegram chat ID');\nconst beatCount = lengthSeconds <= 30 ? 3 : lengthSeconds <= 60 ? 5 : 8;\nconst query = topic.toLowerCase().replace(/[^a-z0-9 ]/g, ' ').replace(/\\s+/g, ' ').trim();\nreturn [{ json: { topic, audience, lengthSeconds, beatCount, chatId, query } }];"
      },
      "id": "6b46acfc-8f98-417a-833e-bb2a9043c103"
    },
    {
      "name": "Search SearXNG",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ],
      "parameters": {
        "url": "http://searxng:8080/search",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ $json.query }}"
            },
            {
              "name": "format",
              "value": "json"
            }
          ]
        },
        "options": {}
      },
      "id": "ae89cc5b-e944-47c8-9900-ac84840044cc"
    },
    {
      "name": "Trim References",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        0
      ],
      "parameters": {
        "jsCode": "const input = $('Clean Input').first().json;\nconst results = ($input.first().json.results || []).slice(0, 5);\nconst clip = (s, n) => String(s || '').replace(/\\s+/g, ' ').trim().slice(0, n);\nconst references = results.length\n  ? results.map((r, i) => `${i + 1}. ${clip(r.title, 90)}: ${clip(r.content, 180)} (${clip(r.url, 80)})`).join('\\n')\n  : 'No web references found. Write from general knowledge.';\nreturn [{ json: { ...input, references, referenceCount: results.length } }];"
      },
      "id": "d5d8fc61-1962-4ed7-9bec-447d97caf75c"
    },
    {
      "name": "Write Script",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.4,
      "position": [
        880,
        0
      ],
      "parameters": {
        "promptType": "define",
        "text": "=Write a YouTube video script.\nTopic: {{ $json.topic }}\nAudience: {{ $json.audience }}\nTarget length: {{ $json.lengthSeconds }} seconds ({{ $json.beatCount }} beats)\n\nRecent web references:\n{{ $json.references }}\n\nUse EXACTLY this format, one item per line, one or two short spoken sentences each, no extra commentary:\nHOOK: <opening line>\nBEAT 1: <spoken narration>\n...\nBEAT {{ $json.beatCount }}: <spoken narration>\nCTA: <call to action>",
        "hasOutputParser": false
      },
      "id": "d88e7714-62c0-4939-971f-8bd2c499b680"
    },
    {
      "name": "Ollama Script Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOllama",
      "typeVersion": 1,
      "position": [
        900,
        220
      ],
      "parameters": {
        "model": "gemma4:12b-it-qat",
        "options": {
          "temperature": 0.7
        }
      },
      "id": "d509579c-5b6a-4fa8-bc86-5131d3fe528d"
    },
    {
      "name": "Shot List",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1240,
        0
      ],
      "parameters": {
        "jsCode": "const base = $('Trim References').first().json;\nconst script = String($input.first().json.text || '').replace(/\\*\\*/g, '').trim();\nconst clean = s => s.replace(/^[\\s:\\-\u2013\u2014]+/, '').trim();\nlet hook = '', cta = '';\nconst beats = [];\nfor (const raw of script.split('\\n')) {\n  const line = raw.trim().replace(/^[#>\\s*-]+/, '');\n  let m;\n  if ((m = line.match(/^hook\\s*[:\\-\u2013]\\s*(.*)/i))) hook = clean(m[1]);\n  else if ((m = line.match(/^(?:call to action|cta)\\s*[:\\-\u2013]\\s*(.*)/i))) cta = clean(m[1]);\n  else if ((m = line.match(/^(?:beat\\s*)?(\\d+)\\s*[:.)\\-\u2013]\\s*(.*)/i))) beats.push(clean(m[2]));\n}\nlet texts = [];\nif (hook) texts.push({ label: 'Hook', text: hook });\nbeats.forEach((b, i) => texts.push({ label: `Beat ${i + 1}`, text: b }));\nif (cta) texts.push({ label: 'CTA', text: cta });\nif (texts.length < 2) {\n  // fallback: model ignored the format, split into sentences\n  const sentences = script.split(/(?<=[.!?])\\s+/).filter(s => s.trim()).slice(0, 10);\n  texts = sentences.map((s, i) => ({ label: `Shot ${i + 1}`, text: s.trim() }));\n}\nif (!texts.length) throw new Error('Script was empty, nothing to build a shot list from');\nconst total = base.lengthSeconds;\nconst weights = texts.map(t => Math.max(1, t.text.split(/\\s+/).length));\nconst wsum = weights.reduce((a, b) => a + b, 0);\nconst raw = weights.map(w => w / wsum * total);\nconst durs = raw.map(r => Math.max(1, Math.floor(r)));\nlet diff = total - durs.reduce((a, b) => a + b, 0);\nconst order = raw.map((r, i) => [r - Math.floor(r), i]).sort((a, b) => b[0] - a[0]).map(x => x[1]);\nfor (let k = 0; diff !== 0 && k < 1000; k++) {\n  const i = order[k % order.length];\n  if (diff > 0) { durs[i]++; diff--; } else if (durs[i] > 1) { durs[i]--; diff++; }\n}\nconst ts = s => `${String(Math.floor(s / 3600)).padStart(2, '0')}:${String(Math.floor(s % 3600 / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}.000`;\nlet t = 0;\nconst shots = texts.map((x, i) => {\n  const start = t; t += durs[i];\n  return { shot: i + 1, label: x.label, text: x.text, seconds: durs[i], start: ts(start), end: ts(t),\n    ffmpeg: `-ss ${ts(start)} -to ${ts(t)}` };\n});\nconst pad = (s, n) => String(s).padEnd(n);\nconst table = [\n  `${pad('#', 3)}| ${pad('Shot', 7)}| ${pad('Start', 13)}| ${pad('End', 13)}| ${pad('Sec', 4)}| Narration`,\n  `${'-'.repeat(3)}|${'-'.repeat(8)}|${'-'.repeat(14)}|${'-'.repeat(14)}|${'-'.repeat(5)}|${'-'.repeat(20)}`,\n  ...shots.map(s => `${pad(s.shot, 3)}| ${pad(s.label, 7)}| ${pad(s.start, 13)}| ${pad(s.end, 13)}| ${pad(s.seconds, 4)}| ${s.text}`),\n].join('\\n');\nreturn [{ json: { ...base, script, shots, shotTable: table, shotCount: shots.length, totalSeconds: t } }];"
      },
      "id": "0d24d1a8-25db-4ab3-90a5-d6c7954b3216"
    },
    {
      "name": "Thumbnail Brief",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.4,
      "position": [
        1460,
        0
      ],
      "parameters": {
        "promptType": "define",
        "text": "=Write a short thumbnail brief (under 90 words) for this video: main image, 3-5 word text overlay, colors, and facial expression or focal point.\nAudience: {{ $json.audience }}\n\nScript:\n{{ $json.script }}",
        "hasOutputParser": false
      },
      "id": "8aa03ff1-9a6d-450f-be04-edf542f73f96"
    },
    {
      "name": "Ollama Thumbnail Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOllama",
      "typeVersion": 1,
      "position": [
        1480,
        220
      ],
      "parameters": {
        "model": "gemma4:12b-it-qat",
        "options": {
          "temperature": 0.7
        }
      },
      "id": "3f0c460c-da77-4ed0-bbfe-519bc5648bdd"
    },
    {
      "name": "Create Google Doc",
      "type": "n8n-nodes-base.googleDocs",
      "typeVersion": 2,
      "position": [
        1820,
        0
      ],
      "parameters": {
        "resource": "document",
        "operation": "create",
        "title": "={{ 'Video Prep - ' + $('Shot List').first().json.topic }}",
        "folderId": "default"
      },
      "id": "32c56493-8da7-4f6e-816d-dcd7396186a1"
    },
    {
      "name": "Write Doc Content",
      "type": "n8n-nodes-base.googleDocs",
      "typeVersion": 2,
      "position": [
        2040,
        0
      ],
      "parameters": {
        "resource": "document",
        "operation": "update",
        "documentURL": "={{ $json.id }}",
        "actionsUi": {
          "actionFields": [
            {
              "action": "insert",
              "text": "={{ 'VIDEO PREP: ' + $('Shot List').first().json.topic + '\\nAudience: ' + $('Shot List').first().json.audience + '\\nTarget length: ' + $('Shot List').first().json.lengthSeconds + 's\\n\\n=== SCRIPT ===\\n' + $('Shot List').first().json.script + '\\n\\n=== SHOT LIST (planning markers, use with ffmpeg -ss/-to) ===\\n' + $('Shot List').first().json.shotTable + '\\n\\n=== THUMBNAIL BRIEF ===\\n' + $('Thumbnail Brief').first().json.text }}"
            }
          ]
        }
      },
      "id": "906bbc0b-24ec-4ec0-8b8a-db04a4207dee"
    },
    {
      "name": "Send Telegram Summary",
      "type": "n8n-nodes-base.telegram",
      "typeVersion": 1.2,
      "position": [
        2260,
        0
      ],
      "parameters": {
        "chatId": "={{ $('Clean Input').first().json.chatId }}",
        "text": "={{ 'Video prep ready: ' + $('Shot List').first().json.topic.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') + '\\nShots: ' + $('Shot List').first().json.shotCount + '\\nTotal runtime: ' + $('Shot List').first().json.totalSeconds + 's\\nDoc: https://docs.google.com/document/d/' + $('Create Google Doc').first().json.id + '/edit' }}",
        "additionalFields": {
          "appendAttribution": false,
          "parse_mode": "HTML"
        }
      },
      "id": "de66ce1e-f92b-4a00-90fc-262db7cc3d9e"
    }
  ],
  "connections": {
    "Video Idea Form": {
      "main": [
        [
          {
            "node": "Clean Input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean Input": {
      "main": [
        [
          {
            "node": "Search SearXNG",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search SearXNG": {
      "main": [
        [
          {
            "node": "Trim References",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trim References": {
      "main": [
        [
          {
            "node": "Write Script",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ollama Script Model": {
      "ai_languageModel": [
        [
          {
            "node": "Write Script",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Write Script": {
      "main": [
        [
          {
            "node": "Shot List",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Shot List": {
      "main": [
        [
          {
            "node": "Thumbnail Brief",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ollama Thumbnail Model": {
      "ai_languageModel": [
        [
          {
            "node": "Thumbnail Brief",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Thumbnail Brief": {
      "main": [
        [
          {
            "node": "Create Google Doc",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Google Doc": {
      "main": [
        [
          {
            "node": "Write Doc Content",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write Doc Content": {
      "main": [
        [
          {
            "node": "Send Telegram Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}