搜尋
首頁web前端js教程AWS JavaScript WordPress = 使用人工智慧的有趣內容自動化策略

幾個月前,我開始為一個專注於科技領域的客戶合作一個關於人工智慧生成內容的專案。我的職責主要是使用 WordPress 設定 SSG 作為 Headless CMS 用於 Nuxt 前端。

客戶過去每週寫幾次關於影響該行業的不同趨勢或情況的文章,為了增加網站的流量和文章的輸出,他決定使用人工智慧為他產生文章。

一段時間後,在正確的提示下,客戶得到的資訊與人類撰寫的文章幾乎完全匹配,很難發現它們是機器製作的。

在我開始研究不同的功能後,我會不斷被問到一件特定的事情。

哎,可以更新一下這篇文章的特色圖片嗎?

經過兩週的每日更新貼文後,我突然靈光一現。

AWS   JavaScript   WordPress = Fun Content Automation Strategies Using Artificial Intelligence

為什麼我不使用人工智慧自動為這些文章產生特色圖像?

我們已經自動化撰寫帖子,為什麼不自動化精選圖片?

在空閒時間,我在電腦上嘗試生成法學碩士,因此我或多或少對如何解決這個支線任務有了一個紮實的想法。我向客戶發送了一條訊息,詳細說明了問題是什麼、我想要做什麼以及優勢是什麼,無需令人信服,我就獲得了使用此功能的綠燈,並立即同意了我的第一步。

1. 設計解決方案的外觀。

鑑於我接觸過在本地運行模型,我立即知道自行託管這些模型是不可行的。放棄這個之後,我開始嘗試根據文字提示產生圖像的 API。

特色圖片由兩部分組成:主要組成的圖形和吸引人的標語。

組成的圖形將是與文章相關的一些元素,以良好的方式排列,然後應用一些顏色和紋理,並應用一些混合模式來實現品牌之後的一些奇特效果。

標語是簡短的 8-12 個單字的句子,下面有一個簡單的陰影。

根據我的測試,我意識到追求影像產生的人工智慧路線是不切實際的。影像品質沒有達到預期,而且過程太耗時,無法證明其使用的合理性。考慮到這將作為 AWS Lambda 函數運行,其中執行時間直接影響成本。

放棄了這一點,我選擇了 B 計畫:使用 JavaScript 的 Canvas API 將圖像和設計資源混合在一起。

深入觀察,我們主要有 5 種風格的簡單帖子,以及大約 4 種類型的紋理,其中 3 種使用相同的文字對齊方式、樣式和位置。做了一些數學計算後,我想:

嗯,如果我拍攝這 3 個影像,抓取 8 個紋理並使用混合模式,我就可以解決 24 種變化

鑑於這 3 種類型的貼文具有相同的文字樣式,它實際上是一個模板。

解決了這個問題後,我轉向了標語產生器。我想根據文章的內容和標題來建立一個口號。鑑於公司已經支付了費用,我決定使用 ChatGPT 的 API,經過一些實驗和提示調整後,我的口號產生器有了一個非常好的 MVP。

弄清楚任務中最困難的 2 個部分後,我花了一些時間在 Figma 中整理出我服務的最終架構的圖表。

AWS   JavaScript   WordPress = Fun Content Automation Strategies Using Artificial Intelligence

2.編寫我的 lambda

計劃建立一個 Lambda 函數,能夠分析貼文內容、產生標語並組裝特色圖片 - 所有這些都與 WordPress 無縫整合。

我將提供一些程式碼,但足以向ke傳達整體想法。

分析內容

Lambda 函數首先從傳入事件負載中提取必要的參數:

const { title: request_title, content, backend, app_password} = JSON.parse(event.body);

  • 標題和內容:這些提供了文章的上下文。
  • 後端: 用於圖片上傳的 WordPress 後端 URL。
  • app_password: 我將使用 WordPress Rest API 以我的使用者身分上傳的驗證令牌。

產生標語

該函數的第一個主要任務是使用analyzeContent函數產生標語,該函數使用OpenAI的API根據文章的標題和內容製作值得點擊的標語。

我們的函數獲取帖子標題和內容,但返回標語、帖子情緒以了解帖子是正面、負面還是中性意見,以及來自標準普爾指數公司的可選公司符號。

const { 口號、情緒、公司 } =等待analyzeContent({ title: request_title, content });

這一步很關鍵,因為口號直接影響圖片的美感。

創建特色圖像

接下來,generateImage函數開始運作:

let buffer;

buffer = await generateImage({
    title: tagline,
    company_logo: company_logo,
    sentiment: sentiment,
});

此函數處理:

  • 設計構圖。
  • 分層紋理、顏色和品牌元素。
  • 套用效果並建立標題。

以下是其工作原理的分步分析:

generateImage 函數首先設定一個空白畫布,定義其尺寸,並準備好處理所有設計元素。

let buffer;

buffer = await generateImage({
    title: tagline,
    company_logo: company_logo,
    sentiment: sentiment,
});

從那裡,從預先定義的資源集合中載入隨機背景圖片。這些圖像經過精心設計,以適應以技術為導向的品牌,同時允許貼文之間有足夠的多樣性。背景圖像是根據其情緒隨機選擇的。

為了確保每個背景圖像看起來都很棒,我根據寬高比動態計算其尺寸。這樣可以避免扭曲,同時保持視覺平衡完好。

新增標語

標語很短,但根據一些規則,這個有影響力的句子被分成可管理的部分,並動態設計樣式以確保它始終可讀,無論長度或畫布大小如何(基於行的字數、字長等) .

const COLOURS = {
        BLUE: "#33b8e1",
        BLACK: "#000000",
    }

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    const images_path = path.join(__dirname, 'images/');
    const files_length = fs.readdirSync(images_path).length;
    const images_folder = process.env.ENVIRONMENT === "local"
        ? "./images/" : "/var/task/images/";


    registerFont("/var/task/fonts/open-sans.bold.ttf", { family: "OpenSansBold" });
    registerFont("/var/task/fonts/open-sans.regular.ttf", { family: "OpenSans" });


    console.log("1. Created canvas");

    const canvas = createCanvas(1118, 806);

    let image = await loadImage(`${images_folder}/${Math.floor(Math.random() * (files_length - 1 + 1)) + 1}.jpg`);


    let textBlockHeight = 0;

    console.log("2. Image loaded");

    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;
    const aspectRatio = image.width / image.height;


    console.log("3. Defined ASPECT RATIO",)

    let drawWidth, drawHeight;
    if (image.width > image.height) {
        // Landscape orientation: fit by width
        drawWidth = canvasWidth;
        drawHeight = canvasWidth / aspectRatio;
    } else {
        // Portrait orientation: fit by height
        drawHeight = canvasHeight;
        drawWidth = canvasHeight * aspectRatio;
    }

    // Center the image
    const x = (canvasWidth - drawWidth) / 2;
    const y = (canvasHeight - drawHeight) / 2;
    const ctx = canvas.getContext("2d");
    console.log("4. Centered Image")
    ctx.drawImage(image, x, y, drawWidth, drawHeight);

最後,畫布被轉換為 PNG 緩衝區。

console.log("4.1 Text splitting");
if (splitText.length === 1) {

    const isItWiderThanHalf = ctx.measureText(splitText[0]).width > ((canvasWidth / 2) + 160);
    const wordCount = splitText[0].split(" ").length;

    if (isItWiderThanHalf && wordCount > 4) {

        const refactored_line = splitText[0].split(" ").reduce((acc, curr, i) => {
            if (i % 3 === 0) {
                acc.push([curr]);
            } else {
                acc[acc.length - 1].push(curr);
            }
            return acc;
        }, []).map((item) => item.join(" "));

        refactored_line[1] = "[s]" + refactored_line[1] + "[s]";

        splitText = refactored_line

    }
}

let tagline = splitText.filter(item => item !== '' && item !== '[br]' && item !== '[s]' && item !== '[/s]' && item !== '[s]');
let headlineSentences = [];
let lineCounter = {
    total: 0,
    reduced_line_counter: 0,
    reduced_lines_indexes: []
}

console.log("4.2 Tagline Preparation", tagline);

for (let i = 0; i  item !== '' && item !== '[s]' && item !== '[/s]');

        const lineWidth = ctx.measureText(finalLine[0]).width
        const halfOfWidth = canvasWidth / 2;

        if (lineWidth > halfOfWidth && finalLine[0]) {

            let splitted_text = finalLine[0].split(" ").reduce((acc, curr, i) => {

                const modulus = finalLine[0].split(" ").length >= 5 ? 3 : 2;
                if (i % modulus === 0) {
                    acc.push([curr]);
                } else {
                    acc[acc.length - 1].push(curr);
                }
                return acc;
            }, []);

            let splitted_text_arr = []

            splitted_text.forEach((item, _) => {
                let lineText = item.join(" ");

                item = lineText

                splitted_text_arr.push(item)
            })

            headlineSentences[i] = splitted_text_arr[0] + '/s/'

            if (splitted_text_arr[1]) {
                headlineSentences.splice(i + 1, 0, splitted_text_arr[1] + '/s/')
            }
        } else {
            headlineSentences.push("/s/" + finalLine[0] + "/s/")
        }


    } else {
        headlineSentences.push(line)
    }
}

console.log("5. Drawing text on canvas", headlineSentences);

const headlineSentencesLength = headlineSentences.length;
let textHeightAccumulator = 0;

for (let i = 0; i  item !== '/s/');
    const nextLine = headlineSentences[i + 1];
    if (nextLine && /^\s*$/.test(nextLine)) {
        headlineSentences.splice(i + 1, 1);
    }

    let line = headlineSentences[i];

    if (!line) continue;
    let lineText = line.trim();

    let textY;

    ctx.font = " 72px OpenSans";

    const cleanedUpLine = lineText.includes('/s/') ? lineText.replace(/\s+/g, ' ') : lineText;
    const lineWidth = ctx.measureText(cleanedUpLine).width
    const halfOfWidth = canvasWidth / 2;

    lineCounter.total += 1

    const isLineTooLong = lineWidth > (halfOfWidth + 50);

    if (isLineTooLong) {

        if (lineText.includes(':')) {
            const split_line_arr = lineText.split(":")
            if (split_line_arr.length > 1) {
                lineText = split_line_arr[0] + ":";
                if (split_line_arr[1]) {
                    headlineSentences.splice(i + 1, 0, split_line_arr[1])
                }
            }
        }

        ctx.font = "52px OpenSans";

        lineCounter.reduced_line_counter += 1

        if (i === 0 && headlineSentencesLength === 2) {
            is2LinesAndPreviewsWasReduced = true
        }


        lineCounter.reduced_lines_indexes.push(i)

    } else {

        if (i === 0 && headlineSentencesLength === 2) {
            is2LinesAndPreviewsWasReduced = false
        }


    }

    if (lineText.includes("/s/")) {

        lineText = lineText.replace(/\/s\//g, "");

        if (headlineSentencesLength > (i + 1) && i  (canvasWidth / 2.35)) {

                ctx.font = "84px OpenSansBold";

                assignedSize = 80

            } else {

                ctx.font = "84px OpenSansBold";

                assignedSize = 84

            }
        } else {


            if (i === headlineSentencesLength - 1 && lineWidth  (canvasWidth / 2) + 120) {

            if (assignedSize === 84) {
                ctx.font = "72px OpenSansBold";
            } else if (assignedSize === 80) {
                ctx.font = "64px OpenSansBold";

                textHeightAccumulator += 8
            } else {
                ctx.font = "52px OpenSansBold";
            }
        }



    } else {

        const textWidth = ctx.measureText(lineText).width


        if (textWidth > (canvasWidth / 2)) {
            ctx.font = "44px OpenSans";
            textHeightAccumulator += 12
        } else if (i === headlineSentencesLength - 1) {
            textHeightAccumulator += 12
        }

    }

    ctx.fillStyle = "white";
    ctx.textAlign = "center";

    const textHeight = ctx.measureText(lineText).emHeightAscent;

    textHeightAccumulator += textHeight;

    if (headlineSentencesLength == 3) {
        textY = (canvasHeight / 3)
    } else if (headlineSentencesLength == 4) {
        textY = (canvasHeight / 3.5)
    } else {
        textY = 300
    }

    textY += textHeightAccumulator;

    const words = lineText.split(' ');
    console.log("words", words, lineText, headlineSentences)
    const capitalizedWords = words.map(word => {
        if (word.length > 0) return word[0].toUpperCase() + word.slice(1)
        return word
    });
    const capitalizedLineText = capitalizedWords.join(' ');

    ctx.fillText(capitalizedLineText, canvasWidth / 2, textY);

}

最後! ! !將圖片上傳到 WordPress

成功產生映像緩衝區後,呼叫 uploadImageToWordpress 函數。

此函數透過對 WordPress 圖像進行編碼,處理使用其 REST API 將圖像傳送到 WordPress 的繁重工作。

函數首先透過清理空格和特殊字元來準備用作檔案名稱的標語:

const buffer = canvas.toBuffer("image/png");
return buffer;

然後將圖像緩衝區轉換為 Blob 對象,以使其與 WordPress API 相容:

const file = new Blob([buffer], { type: "image/png" });

準備 API 請求 使用編碼的圖像和標語,該函數建立一個 FormData 對象,並添加可選的元數據,例如用於可訪問性的 alt_text 和用於上下文的標題。

const createSlug = (string) => {
    return string.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '');
};

const image_name = createSlug(tagline);

為了進行身份驗證,使用者名稱和應用程式密碼以 Base64 進行編碼並包含在請求標頭中:

formData.append("file", file, image_name + ".png");
formData.append("alt_text", `${tagline} image`);
formData.append("caption", "Uploaded via API");

發送圖片使用準備好的資料和標頭向 WordPress 媒體端點發出 POST 請求,並在等待回應後驗證成功或錯誤。

const credentials = `${username}:${app_password}`;
const base64Encoded = Buffer.from(credentials).toString("base64");

如果成功,我會在 lambda 中返回相同的媒體回應。

這就是我的 lambda 最終的樣子。

const response = await fetch(`${wordpress_url}wp-json/wp/v2/media`, {
    method: "POST",
    headers: {
        Authorization: "Basic " + base64Encoded,
        contentType: "multipart/form-data",
    },
    body: formData,
});

if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Error uploading image: ${response.statusText}, Details: ${errorText}`);
}

這是我的腳本產生的範例圖像。它沒有在生產中使用,只是使用本範例的通用資源建立。

AWS   JavaScript   WordPress = Fun Content Automation Strategies Using Artificial Intelligence

後果

一段時間過去了,每個人都很高興我們不再有劣質或空洞的無圖像文章,圖像與設計師製作的圖像非常匹配,設計師很高興他只專注於為整個公司的其他營銷活動進行設計。

但隨後出現了一個新問題:有時客戶不喜歡生成的圖像,他會要求我啟動腳本為特定帖子生成新圖像。

這給我帶來了下一個支線任務:Wordpress 插件,使用人工智慧為特定帖子手動生成特色圖像

以上是AWS JavaScript WordPress = 使用人工智慧的有趣內容自動化策略的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

JavaScript框架:為現代網絡開發提供動力JavaScript框架:為現代網絡開發提供動力May 02, 2025 am 12:04 AM

JavaScript框架的強大之處在於簡化開發、提升用戶體驗和應用性能。選擇框架時應考慮:1.項目規模和復雜度,2.團隊經驗,3.生態系統和社區支持。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。