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

AWS JavaScript WordPress = 使用人工智慧的有趣內容自動化策略

Jan 05, 2025 pm 08:40 PM

幾個月前,我開始為一個專注於科技領域的客戶合作一個關於人工智慧生成內容的專案。我的職責主要是使用 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 < tagline.length; i++) {
    let line = tagline[i];

    if (line.includes("[s]") || line.includes("[/s]")) {

        const finalLine = line.split(/(\[s\]|\[\/s\])/).filter(item => 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 < headlineSentencesLength; i++) {
    headlineSentences = headlineSentences.filter(item => 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 < headlineSentencesLength - 1 && nextLine) {

            if (nextLine.slice(0, 2).includes("?") && nextLine.length < 3) {
                lineText += '?';
                headlineSentences.pop();
            }

            if (nextLine.slice(0, 2).includes(":")) {
                lineText += ':';
                headlineSentences[i + 1] = headlineSentences[i + 1].slice(2);
            }

        }

        let lineWidth = ctx.measureText(lineText).width


        let assignedSize;


        if (lineText.split(" ").length <= 2) {

            if (lineWidth > (canvasWidth / 2.35)) {

                ctx.font = "84px OpenSansBold";

                assignedSize = 80

            } else {

                ctx.font = "84px OpenSansBold";

                assignedSize = 84

            }
        } else {


            if (i === headlineSentencesLength - 1 && lineWidth < (canvasWidth / 2.5) && lineText.split(" ").length === 3) {

                ctx.font = "84px OpenSansBold";
                assignedSize = 84

            } else {

                lineCounter.reduced_line_counter += 1;

                ctx.font = "52px OpenSansBold";
                assignedSize = 52

            }

            lineCounter.reduced_lines_indexes.push(i)

        }

        lineWidth = ctx.measureText(lineText).width



        if (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

熱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

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

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1668
14
CakePHP 教程
1427
52
Laravel 教程
1329
25
PHP教程
1273
29
C# 教程
1256
24
JavaScript引擎:比較實施 JavaScript引擎:比較實施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

Python vs. JavaScript:學習曲線和易用性 Python vs. JavaScript:學習曲線和易用性 Apr 16, 2025 am 12:12 AM

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C到JavaScript:所有工作方式 從C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在行動中:現實世界中的示例和項目 JavaScript在行動中:現實世界中的示例和項目 Apr 19, 2025 am 12:13 AM

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

了解JavaScript引擎:實施詳細信息 了解JavaScript引擎:實施詳細信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python vs. JavaScript:社區,圖書館和資源 Python vs. JavaScript:社區,圖書館和資源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python vs. JavaScript:開發環境和工具 Python vs. JavaScript:開發環境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

See all articles