用Hexo架設部落格後,玩家想提升SEO,利用OpenAI API寫總結與調整網址。 Python負責總結文章,JS加入摘要到文章中。再用OpenAI調整網址,增加美觀性。最後,用API生成SEO友好URL,提高文章曝光率。玩得不亦樂乎,50次只要0.02美元,物超所值!
使用Hexo架設部落格後,本來只是想簡單紀錄教學與日常。但總會想到一些問題來折騰自己。
趁颱風天,測試使用OpenAI 的API,做了兩件事情:一為用OpenAI撰寫整篇文章的總結,一為調整文章網址
都為了增加網站的SEO,也為了自己的好玩拉,有沒有做沒什麼差。
用OpenAI撰寫整篇文章的總結 想法是「寫完文章後」→「Python與OpenAI API總結文章」→「generate的時候用JS加入到文章的excerpt中」
以下是Python程式碼, 路徑為./source/_scripts/summarize_post.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 import openaiimport osimport sys openai.api_key = 'API KEY' def summarize_post(post_content): response = openai.ChatCompletion.create ( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": "你是一個能夠摘要部落格文章的有幫助助手。"}, {"role": "user", "content": f"請將以下文章摘要成70個字,用有趣、大眾能懂的口吻,用繁體中文總結:\n\n{post_content}"} ] ) return response['choices' ][0 ]['message' ]['content' ].strip()if __name__ == "__main__": post_content = sys.argv[1 ] summary = summarize_post(post_content) print(summary )
generate的時候用JS加入到文章的excerpt中
JS程式碼,路徑放在./scripts/generate_summary.js
透過execSync
執行前面的Python檔案取得data.summary
也是在做讀檔寫檔(還好有GPT)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 const { execSync } = require ('child_process' );const fs = require ('fs' );const yaml = require ('js-yaml' );const path = require ('path' ); hexo.extend .filter .register ('before_post_render' , function (data ) { console .log (`Processing post: ${data.title} ` ); if (data.summary ) { console .log (`Summary already exists for post: ${data.title} ` ); return data; } try { const content = data.content .replace (/<[^>]*>/g , '' ); const scriptPath = path.join (hexo.base_dir , 'source/_scripts/summarize_post.py' ); const summary = execSync (`python3 ${scriptPath} "${content} "` ).toString ().trim (); data.summary = summary; const filePath = data.full_source ; const fileContent = fs.readFileSync (filePath, 'utf8' ); const postParts = fileContent.split ('---' ); if (postParts.length > 2 ) { let frontMatter = yaml.load (postParts[1 ]); if (!frontMatter) { frontMatter = {}; } frontMatter.summary = summary; const newFrontMatter = yaml.dump (frontMatter); const newFileContent = `---\n${newFrontMatter} ---\n${postParts.slice(2 ).join('---' )} ` ; fs.writeFileSync (filePath, newFileContent, 'utf8' ); console .log (`Summary generated and saved for post: ${data.title} ` ); } else { console .error (`Error: Invalid Front Matter format in post: ${data.title} ` ); } } catch (error) { console .error (`Error generating summary for post: ${data.title} ` , error); } return data; });
在主題中的post要加入這個函式,路徑為./themes/fluid/layout/post.ejs
,如果還沒產生總結,就開一個區塊來放。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 <article class ="post-content mx-auto" > <h1 id ="seo-header" > <%= page.subtitle || page.title %> </h1 > <% if (page.summary) { %> <div class ="post-summary" > <p > <%= page.summary %> </p > </div > <% } %>
用OpenAI調整網址幫助SEO與美觀 這邊是了一陣子發現網址(permalink)的設定,在_config.yml
中預設為
1 permalink: :year/ :month/ :day/ :title
可參考文件:https://hexo.io/zh-tw/docs/permalinks
但因為title都是中文,也不能直接寫permalink: 字串
這點我給差評
解法是下載hexo-abbrlink
這個外掛
1 npm install hexo-abbrlink
然後修改permalink為
1 permalink: :year/ :month/ :abbrlink
再做meta-data的修改即可,修改方式如下
因為這是後來與Notion同步時寫的,所以寫在Python當中,路徑為./main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 import osimport openai openai.api_key = 'API KEY' def generate_seo_url_name (title, tags ): prompt = f"Generate a SEO-friendly URL name for a blog post with the title '{title} ' and tags '{tags} ':" response = openai.ChatCompletion.create( model="gpt-3.5-turbo" , messages=[ {"role" : "system" , "content" : "You are an assistant that generates SEO-friendly URL slugs." }, {"role" : "user" , "content" : prompt} ] ) slug = response['choices' ][0 ]['message' ]['content' ].strip() slug = slug.replace(" " , "-" ).lower() return slugdef convert_to_markdown (title, date, tags, categories, index_img_path, blocks, post_dir,url_name ): markdown = f"---\ntitle: {title} \ndate: {date} \ntags: [{tags} ]\ncategories: {categories} \nindex_img: {index_img_path} \nbanner_img: {index_img_path} \nabbrlink: {url_name} \n---\n\n" def main (): url_name = generate_seo_url_name(title, tags) markdown_content = convert_to_markdown(title, date, tags, categories, index_img_path, blocks, post_dir, url_name)
以上為兩個AI輔助的功能,目前使用3.5-turbo,因為很便宜,測試時狂摳猛摳,大概50次只要0.02美。