{
  "name": "Meta Ads Workflow",
  "nodes": [
    {
      "parameters": {},
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -120,
        305
      ],
      "id": "5d79fca2-f19f-4c7a-a8b9-9cc9835e7819",
      "name": "When clicking ‘Test workflow’"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "e9538bee-ac72-4c84-a6ac-88123ecd9681",
              "name": "meta_ad_library_url",
              "value": "https://www.facebook.com/ads/library/?active_status=active&ad_type=all&country=DE&is_targeted_country=false&media_type=all&search_type=page&view_all_page_id=568734186606016",
              "type": "string"
            },
            {
              "id": "a9e1a2d7-b986-470c-b0a0-8bbf29b8b5fb",
              "name": "prompt",
              "value": "# VIDEO ANALYSIS AGENT INSTRUCTIONS  You are a specialized AI agent that analyzes video advertisements and extracts structured data with expert-level insights. Your purpose is to break down video ads into their key components and provide a comprehensive analysis from both creative and business perspectives.  ## YOUR ROLE AND EXPERTISE  You are an expert in Meta advertising with deep knowledge of: - Creative strategy and execution - Hook effectiveness and attention-capturing techniques - Storytelling structure and narrative flow - Ad format identification and best practices - Consumer psychology and engagement patterns - Business objectives and conversion strategy  ## DATA EXTRACTION REQUIREMENTS  For each video analyzed, extract and organize the following structured data:  ### 1. HOOK ANALYSIS - Identify and describe the hook (first few seconds) in detail - Explain how the hook attempts to capture viewer attention - Assess the hook's effectiveness and alignment with the overall message - Note any pattern interrupts, curiosity gaps, or emotional triggers used  ### 2. FULL TRANSCRIPT - Provide a complete, verbatim transcript of all spoken content/voice over - Include timestamps for major transitions or key points - Note tone shifts, emphasis, and delivery style - Keep the original language for the transcript  ### 3. AD FORMAT IDENTIFICATION Select the primary format from these categories: - Before and After - Facts and Stats - Features and Benefits - Holiday - Seasonal - Media and Press - Promotion and Discount - Reasons Why - Testimonial - Review - Us vs Them  If multiple formats are used, identify the dominant format and note secondary approaches.  ### 4. CONCEPT SUMMARY - Provide a concise description of the entire ad concept in 300 characters or less - Highlight the core message and unique selling proposition - Identify the primary emotional appeal and call to action  ### 5. NARRATIVE BREAKDOWN Divide the ad into three distinct sections and analyze each:  **Beginning:** - Describe the opening sequence and establishment of context - Identify how the brand introduces the problem or opportunity - Note visual style, pacing, and initial framing  **Middle:** - Describe how the narrative develops - Identify key information presentation, product demonstrations - Note how tension, solution, or value proposition is built  **End:** - Describe the resolution and closing sequence - Identify the specific call to action and urgency mechanisms - Note how the brand reinforces its message and identity  ## OUTPUT FORMAT  Present your analysis in a clean, structured format using the following template:   ## HOOK ANALYSIS [Detailed description of the hook and its effectiveness]  ## FULL TRANSCRIPT [Complete verbatim transcript of voice over]  ## AD FORMAT Primary Format: [Selected format] Secondary Elements: [If applicable]  ## CONCEPT SUMMARY [Concise 300-character max description of the overall concept]  ## NARRATIVE BREAKDOWN  ### Beginning [Detailed analysis of opening sequence]  ### Middle [Detailed analysis of the main content]  ### End [Detailed analysis of closing sequence and call to action]   ## ANALYSIS APPROACH  1. Watch the entire video multiple times to ensure comprehensive understanding 2. Focus first on objective observations before making interpretive assessments 3. Consider both creative execution and business strategy in your analysis 4. Provide specific timestamps when referencing particular moments 5. Be precise and detailed in your descriptions while maintaining clarity 6. Avoid subjective value judgments unless specifically relevant to effectiveness 7. Identify patterns and techniques that could be replicated or improved  ## FINAL CONSIDERATIONS  - Always maintain a professional, analytical tone - Provide actionable insights that could improve future creative approaches - Consider how the ad might perform with different audience segments - When uncertain about specific elements, note multiple possible interpretations - Focus on the \"why\" behind creative choices, not just the \"what\"  Your analysis should serve as both a documentation of the existing creative and a strategic resource for improving future advertising efforts.",
              "type": "string"
            },
            {
              "id": "9fa3b6a0-9155-4edf-9783-73cfe44b6e4e",
              "name": "max_ads_to_scrape",
              "value": 150,
              "type": "number"
            },
            {
              "id": "fd4c4083-45bc-4b86-a238-6ca38bc0d7b5",
              "name": "max_ads_to_analyze",
              "value": 5,
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        100,
        300
      ],
      "id": "42cc6dca-e291-4d3d-b16b-d567d622856a",
      "name": "Settings"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        1860,
        305
      ],
      "id": "6b8d13fc-b303-4113-ad74-900c3f49d9cf",
      "name": "Loop Over Items"
    },
    {
      "parameters": {
        "modelName": "models/gemini-2.0-flash",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1,
      "position": [
        3840,
        400
      ],
      "id": "3def3c87-d5e4-4dfe-a275-a91a3233fd51",
      "name": "Google Gemini Chat Model",
      "credentials": {
        "googlePalmApi": {
          "id": "niR5fG7q7IqqUGaB",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Comprehensive cleaning of text for JSON compatibility\nreturn items.map(item => {\n  // Access the original data\n  const data = Array.isArray(item.json) ? item.json[0] : item.json;\n  \n  if (data && data.prompt) {\n    // Create a copy of all the original fields\n    const newData = { ...data };\n    \n    // Get the prompt text and clean it\n    let cleanPrompt = data.prompt;\n    \n    // Remove all newlines\n    cleanPrompt = cleanPrompt.replace(/(\\r\\n|\\n|\\r)/gm, \" \");\n    \n    // Remove markdown formatting characters\n    cleanPrompt = cleanPrompt.replace(/[#*_`[\\]()]/g, \"\");\n    \n    // Replace multiple spaces with a single space\n    cleanPrompt = cleanPrompt.replace(/\\s+/g, \" \");\n    \n    // Remove any special characters that might cause JSON issues\n    cleanPrompt = cleanPrompt.replace(/[\\u0000-\\u001F\\u007F-\\u009F]/g, \"\");\n    \n    // Remove quotes that might interfere with JSON\n    cleanPrompt = cleanPrompt.replace(/[\"']/g, \"\");\n    \n    // Remove backslashes\n    cleanPrompt = cleanPrompt.replace(/\\\\/g, \"\");\n    \n    // Update only the prompt field with the cleaned version\n    newData.prompt = cleanPrompt.trim();\n    \n    // Replace the original data with the updated version\n    item.json = Array.isArray(item.json) ? [newData] : newData;\n  }\n  \n  return item;\n});"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        320,
        305
      ],
      "id": "ca1c65fa-d915-4ccf-bf86-1b2d3cf70dd0",
      "name": "Clean Prompt"
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "1yo1eU7LHQ7WEj0xEvprz0k9Vydu3-Vl4M6EGbiAlN3o",
          "mode": "list",
          "cachedResultName": "Meta Video Output",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1yo1eU7LHQ7WEj0xEvprz0k9Vydu3-Vl4M6EGbiAlN3o/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "value": "gid=0",
          "mode": "list",
          "cachedResultName": "Tabellenblatt1",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1yo1eU7LHQ7WEj0xEvprz0k9Vydu3-Vl4M6EGbiAlN3o/edit#gid=0"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "hook": "={{ $json.output.hook }}",
            "transcript": "={{ $json.output.transcript }}",
            "format": "={{ $json.output.format }}",
            "concept": "={{ $json.output.concept }}",
            "start_of_ad": "={{ $json.output.start_of_ad }}",
            "mid_of_ad": "={{ $json.output.mid_of_ad }}",
            "end_of_ad": "={{ $json.output.end_of_ad }}",
            "ad_id": "={{ $('Download File').item.json.ad_archive_id }}",
            "video_url": "={{ $('Download File').item.json.video_hd_url }}",
            "eu_reach": "={{ $('Download File').item.json.eu_total_reach }}",
            "landing_page": "={{ $('Download File').item.json.link_url }}",
            "page_name": "={{ $('Download File').item.json.page_name }}",
            "ad_library_link": "={{ \"https://www.facebook.com/ads/library/?id=\" + $('Download File').item.json.ad_archive_id }}",
            "link_to_video": "={{ $('Save to Google Drive').item.json.webViewLink }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "ad_id",
              "displayName": "ad_id",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "video_url",
              "displayName": "video_url",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "hook",
              "displayName": "hook",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "transcript",
              "displayName": "transcript",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "format",
              "displayName": "format",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "concept",
              "displayName": "concept",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "start_of_ad",
              "displayName": "start_of_ad",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "mid_of_ad",
              "displayName": "mid_of_ad",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "end_of_ad",
              "displayName": "end_of_ad",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "eu_reach",
              "displayName": "eu_reach",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "landing_page",
              "displayName": "landing_page",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "ad_library_link",
              "displayName": "ad_library_link",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "page_name",
              "displayName": "page_name",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "link_to_video",
              "displayName": "link_to_video",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {
          "useAppend": true
        }
      },
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        4220,
        300
      ],
      "id": "85f92a59-da95-413a-8e73-76520d633068",
      "name": "Store Data",
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "0hKHko3t0o7pjfwX",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.candidates[0].content.parts[0].text }}",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You act as a helpful assistant who is particularly good at condensing provided text and extracting its essence.\nYou will be given an advertising analysis and should convert it into a structured format.\n\n- Hook (max 120 characters)\n- Transcript (unabridged)\n- Advertising format (max 50 characters, word combination only)\n- Overall concept (max 250 characters)\n- Beginning of the advertisement (max 120 characters)\n- Middle of the advertisement (max 120 characters)\n- End of the advertisement (max 120 characters)"
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        3840,
        180
      ],
      "id": "c80e4030-cf1c-4406-8f08-ed5f3f875321",
      "name": "Structured Output Parsing Agent",
      "retryOnFail": true
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        3400,
        180
      ],
      "id": "03f8be68-174f-4a49-9ad7-885e70d7f16b",
      "name": "Wait for Upload Processing",
      "webhookId": "a0e5485e-3f3c-47c6-ab19-9b9dc6158ab5"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googlePalmApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n   \"contents\": [\n      {\n         \"parts\": [\n            {\n               \"text\": \"{{ $('Clean Prompt').item.json.prompt }}\"\n            },\n            {\n               \"file_data\": {\n                  \"mime_type\": \"{{ $json.file.mimeType }}\",\n                  \"file_uri\": \"{{ $json.file.uri }}\"\n               }\n            }\n         ]\n      }\n   ]\n}\n",
        "options": {
          "response": {}
        }
      },
      "id": "beffa5f6-28b4-4e89-88d9-f28950b9e148",
      "name": "Analyze Video with Gemini",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        3620,
        180
      ],
      "typeVersion": 4.2,
      "credentials": {
        "googlePalmApi": {
          "id": "niR5fG7q7IqqUGaB",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "url": "={{ $json.video_hd_url }}",
        "options": {
          "response": {
            "response": {
              "responseFormat": "file"
            }
          }
        }
      },
      "id": "4bd811ab-d43c-4272-b1b2-124c9586aa08",
      "name": "Download File",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        2080,
        180
      ],
      "typeVersion": 4.2
    },
    {
      "parameters": {
        "jsCode": "// Get the binary data from previous node\nconst binaryData = $input.all()[0].binary.data;\n\n// Create a new binary object with the correct MIME type\nconst newBinaryData = {\n  ...binaryData,\n  mimeType: 'video/mp4'  // Explicitly set the correct MIME type\n};\n\n// Return the modified data\nreturn {\n  json: $input.all()[0].json,\n  binary: {\n    data: newBinaryData\n  }\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2300,
        180
      ],
      "id": "dddfbe6b-b6d0-4bf6-833d-8d69aec18b0a",
      "name": "Change Filetype to Video"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.apify.com/v2/acts/curious_coder~facebook-ads-library-scraper/run-sync-get-dataset-items",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n    \"count\": {{ $json.max_ads_to_scrape }},\n    \"scrapeAdDetails\": true,\n    \"scrapePageAds.activeStatus\": \"all\",\n    \"urls\": [\n        {\n            \"url\": \"{{ $json.meta_ad_library_url }}\",\n            \"method\": \"GET\"\n        }\n    ]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        540,
        305
      ],
      "id": "40f8e0ec-6a35-49ce-ae49-86261afe169f",
      "name": "Scrape Meta Ad Library with Apify",
      "credentials": {
        "httpQueryAuth": {
          "id": "QGON3Fzukcyy4AtQ",
          "name": "Query Auth account"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "c40036d9-8c6c-4cd8-b9f7-eac1d41adfba",
              "name": "ad_archive_id",
              "value": "={{ $json.ad_archive_id }}",
              "type": "string"
            },
            {
              "id": "3add9e6b-8656-4bab-bd81-bd3a0d689a9a",
              "name": "video_hd_url",
              "value": "={{ $json.snapshot?.cards?.[0]?.video_hd_url || $json.snapshot?.videos?.[0]?.video_hd_url || '' }}",
              "type": "string"
            },
            {
              "id": "00966733-bb39-4649-8f3e-4887d7ddcc00",
              "name": "video_preview_image_url",
              "value": "={{ $json.snapshot?.cards?.[0]?.video_preview_image_url || $json.snapshot?.videos?.[0]?.video_preview_image_url || '' }}",
              "type": "string"
            },
            {
              "id": "bba54ff9-f043-4042-bc0c-8288707107c9",
              "name": "link_url",
              "value": "={{ $json.snapshot?.link_url || $json.snapshot?.cards?.[0]?.link_url || '' }}",
              "type": "string"
            },
            {
              "id": "cdef955d-f846-4ad5-a2c0-fee1676d0fa8",
              "name": "eu_total_reach",
              "value": "={{ $json.aaa_info.eu_total_reach }}",
              "type": "number"
            },
            {
              "id": "64655f86-be39-4b57-8efc-f7ccdc231ae7",
              "name": "page_name",
              "value": "={{ $json.page_name }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1640,
        305
      ],
      "id": "438f96f1-120f-4b7e-bdd9-714b14e718f4",
      "name": "Pass relevant Fields"
    },
    {
      "parameters": {
        "jsonSchemaExample": "{\n \"hook\": \"Our Starter Set Duo is going viral right now. Holy is the healthy alternative to energy drinks. And we're starting the new year 2024 after all.\",\n \"transcript\": \"Unser Starter-Set Duo geht gerade viral. Holy ist die gesunde Alternative zu Energy Drinks. Und wir starten ja schließlich ins neue Jahr 2024. Deshalb kannst du jetzt mit unserem Starter-Set Duo alle unsere Bestseller probieren. Holy Energy und Holy Eistee plus gratis Shaker. Und das ganze jetzt mit krassen 30% Rabatt. Und das Beste daran: Kein Zucker, kein Taurin und kein anderer Bullshit. Aber mit natürlich fruchtigem Geschmack. Einfach mixen, shaken und genießen. Und ich verspreche euch, es schmeckt extrem geil. Und mit dem Code Holy sparst du dir 5€ auf deine Bestellung. Diesen Deal gibt's allerdings nur bis zum 29. Februar.\",\n \"format\": \"Action and Discount + Features and Benefits\",\n \"concept\": \"The Holy Starter Set Duo is presented as a healthy, sugar-free and taurine-free alternative to conventional energy drinks. With fruity flavor, easy preparation, and a limited-time discount offer, the target audience is encouraged to make a purchase.\",\n \"start_of_ad\": \"Our Starter Set Duo is going viral right now. Holy is the healthy alternative to energy drinks as we start the new year 2024.\",\n \"mid_of_ad\": \"Try all bestsellers: Holy Energy, Holy Iced Tea plus free shaker with 30% discount. No sugar, no taurine - just natural flavor.\",\n \"end_of_ad\": \"Simply mix, shake, and enjoy. With code Holy you save €5 on your order. Offer valid only until February 29th.\"\n}"
      },
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.2,
      "position": [
        4000,
        400
      ],
      "id": "fd28944e-09ae-41f7-b1eb-01ae3c2a8f9e",
      "name": "Structured Output Parser"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "db05b050-dd51-4bb8-9e70-2c5067b51082",
              "name": "=duration_in_days",
              "value": "={{ ($json.end_date - $json.start_date) / (60 * 60 * 24) }}",
              "type": "number"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        760,
        305
      ],
      "id": "589adcc5-883d-43e0-87d0-42dc1da9455f",
      "name": "Calculate Runtime in Days"
    },
    {
      "parameters": {
        "type": "code",
        "code": "try {\n  // Safely extract and convert values with better NaN handling\n  const getValueFromItem = (item) => {\n    if (!item || !item.json) return 0;\n    \n    let value;\n    if (item.json.aaa_info && \n        item.json.aaa_info.eu_total_reach !== undefined && \n        item.json.aaa_info.eu_total_reach !== null) {\n      value = item.json.aaa_info.eu_total_reach;\n    } else if (item.json.duration_in_days !== undefined && \n               item.json.duration_in_days !== null) {\n      value = item.json.duration_in_days;\n    } else {\n      return 0;\n    }\n    \n    // More robust number conversion\n    const numValue = Number(value);\n    return isNaN(numValue) ? 0 : numValue;\n  };\n  \n  const aValue = getValueFromItem(a);\n  const bValue = getValueFromItem(b);\n  \n  // Sort in descending order (higher values first)\n  return bValue - aValue; // This properly returns the comparison result\n} catch (error) {\n  console.log('Sorting error:', error.message);\n  return 0;\n}"
      },
      "type": "n8n-nodes-base.sort",
      "typeVersion": 1,
      "position": [
        980,
        305
      ],
      "id": "dc3b1185-56b5-43c3-aefe-d72c26b9feb3",
      "name": "Sort by Reach or Days Running"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "4829fbdd-4afb-451a-888b-286ebd4a88e5",
              "leftValue": "={{ $json.snapshot.videos[0].video_hd_url }}",
              "rightValue": "http",
              "operator": {
                "type": "string",
                "operation": "startsWith"
              }
            },
            {
              "id": "a34d849c-8462-44b4-b6db-10a33cd320e7",
              "leftValue": "={{ $json.snapshot.cards[0].video_hd_url }}",
              "rightValue": "http",
              "operator": {
                "type": "string",
                "operation": "startsWith"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        1200,
        305
      ],
      "id": "d7c037cb-6d88-4da2-91b5-08bab34cda6d",
      "name": "Filter only Video Ads"
    },
    {
      "parameters": {
        "maxItems": "={{ $('Settings').item.json.max_ads_to_analyze }}"
      },
      "type": "n8n-nodes-base.limit",
      "typeVersion": 1,
      "position": [
        1420,
        305
      ],
      "id": "4b18a600-016d-49fb-a80f-5e965eb5152b",
      "name": "Limit Videos to Analyze"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://generativelanguage.googleapis.com/upload/v1beta/files",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googlePalmApi",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "X-Goog-Upload-Protocol",
              "value": "resumable"
            },
            {
              "name": "X-Goog-Upload-Command",
              "value": "start"
            },
            {
              "name": "X-Goog-Upload-Header-Content-Length",
              "value": "={{ $json.size }}"
            },
            {
              "name": "X-Goog-Upload-Header-Content-Type",
              "value": "={{ $json.mimeType }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n\"file\": {\n\"display_name\": \"{{ $json.name }}\"\n}\n}",
        "options": {
          "response": {
            "response": {
              "fullResponse": true
            }
          }
        }
      },
      "id": "fbfb6da5-8e51-4f27-aece-16a2ea70e513",
      "name": "Gemini - Generate Upload URL",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        2740,
        180
      ],
      "typeVersion": 4.2,
      "credentials": {
        "googlePalmApi": {
          "id": "niR5fG7q7IqqUGaB",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Gemini - Generate Upload URL').item.json.headers['x-goog-upload-url'] }}",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googlePalmApi",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Length",
              "value": "={{ $('Save to Google Drive').item.json.size }}"
            },
            {
              "name": "X-Goog-Upload-Offset",
              "value": "0"
            },
            {
              "name": "X-Goog-Upload-Command",
              "value": "upload, finalize"
            }
          ]
        },
        "sendBody": true,
        "contentType": "binaryData",
        "inputDataFieldName": "data",
        "options": {
          "response": {}
        }
      },
      "id": "61404200-e991-4f07-8a17-c69208f7ce15",
      "name": "Gemini - Upload File",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        3180,
        180
      ],
      "typeVersion": 4.2,
      "credentials": {
        "googlePalmApi": {
          "id": "niR5fG7q7IqqUGaB",
          "name": "Google Gemini(PaLM) Api account"
        }
      }
    },
    {
      "parameters": {
        "content": "You'll have to select a folder in your own google drive for this node to work\n\n[How to Connect Google Drive](https://www.youtube.com/watch?v=3Ai1EPznlAc)"
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2420,
        -20
      ],
      "typeVersion": 1,
      "id": "8ca54eba-9b20-4368-986d-b9644a703073",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "name": "={{ $('Loop Over Items').item.json.ad_archive_id + \"_\" + $('Loop Over Items').item.json.page_name}}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "value": "1i4UrePldbyytT1VispedGRcV5xMAWcJr",
          "mode": "list",
          "cachedResultName": "Meta Ads",
          "cachedResultUrl": "https://drive.google.com/drive/folders/1i4UrePldbyytT1VispedGRcV5xMAWcJr"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2520,
        180
      ],
      "id": "d33c10b8-9d80-407d-98e3-c4cd7bd2909c",
      "name": "Save to Google Drive",
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "WTbMEIGqP9GH59QG",
          "name": "Google Drive account"
        }
      }
    },
    {
      "parameters": {
        "operation": "download",
        "fileId": {
          "__rl": true,
          "value": "={{ $('Save to Google Drive').item.json.id }}",
          "mode": "id"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2960,
        180
      ],
      "id": "8d8b4434-c43d-47a8-bfc6-ce2da17dc8cf",
      "name": "Download from Google Drive",
      "credentials": {
        "googleDriveOAuth2Api": {
          "id": "WTbMEIGqP9GH59QG",
          "name": "Google Drive account"
        }
      }
    }
  ],
  "pinData": {},
  "connections": {
    "When clicking ‘Test workflow’": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Clean Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [],
        [
          {
            "node": "Download File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Structured Output Parsing Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Clean Prompt": {
      "main": [
        [
          {
            "node": "Scrape Meta Ad Library with Apify",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store Data": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parsing Agent": {
      "main": [
        [
          {
            "node": "Store Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait for Upload Processing": {
      "main": [
        [
          {
            "node": "Analyze Video with Gemini",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Video with Gemini": {
      "main": [
        [
          {
            "node": "Structured Output Parsing Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download File": {
      "main": [
        [
          {
            "node": "Change Filetype to Video",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Change Filetype to Video": {
      "main": [
        [
          {
            "node": "Save to Google Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scrape Meta Ad Library with Apify": {
      "main": [
        [
          {
            "node": "Calculate Runtime in Days",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pass relevant Fields": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Structured Output Parsing Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Calculate Runtime in Days": {
      "main": [
        [
          {
            "node": "Sort by Reach or Days Running",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sort by Reach or Days Running": {
      "main": [
        [
          {
            "node": "Filter only Video Ads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter only Video Ads": {
      "main": [
        [
          {
            "node": "Limit Videos to Analyze",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit Videos to Analyze": {
      "main": [
        [
          {
            "node": "Pass relevant Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini - Generate Upload URL": {
      "main": [
        [
          {
            "node": "Download from Google Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini - Upload File": {
      "main": [
        [
          {
            "node": "Wait for Upload Processing",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save to Google Drive": {
      "main": [
        [
          {
            "node": "Gemini - Generate Upload URL",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download from Google Drive": {
      "main": [
        [
          {
            "node": "Gemini - Upload File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "f0b48d7f-2112-4ab6-b130-3737566e3f8a",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "ed0bee221502cbe8fc8412c2ea623723691c5f5888a5a0d55e51f3d4c69169f3"
  },
  "id": "hhmEktb6CIxM5ryQ",
  "tags": []
}