紀錄學習-使用Hexo架設部落格 (4) 使用OpenAI輔助總結與網址

用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與OpenAI API總結文章

以下是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 openai
import os
import 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');

// 模拟的数据对象
// const data = {
// title: 'Example Post',
// full_source: path.join(__dirname, '../source/_posts/貓貓測試.md'),
// content: fs.readFileSync(path.join(__dirname, '../source/_posts/貓貓測試.md'), 'utf8')
// };

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, ''); // 移除 HTML 标签
const scriptPath = path.join(hexo.base_dir, 'source/_scripts/summarize_post.py');
const summary = execSync(`python3 ${scriptPath} "${content}"`).toString().trim();
data.summary = summary;

// 读取文章的 Front Matter
const filePath = data.full_source;
const fileContent = fs.readFileSync(filePath, 'utf8');
const postParts = fileContent.split('---');

if (postParts.length > 2) {
// 更新 Front Matter
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> 後面開始 -->
<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 --save

然後修改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 os
import openai
openai.api_key = 'API KEY'

# Generate SEO-friendly URL name using OpenAI
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}':"
# Call OpenAI API to get a response
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # You can use "gpt-4" if available
messages=[
{"role": "system", "content": "You are an assistant that generates SEO-friendly URL slugs."},
{"role": "user", "content": prompt}
]
)

# Extract the generated slug from the response
slug = response['choices'][0]['message']['content'].strip()

# Ensure the slug is URL-friendly by replacing spaces with hyphens and converting to lowercase
slug = slug.replace(" ", "-").lower()

return slug

def convert_to_markdown(title, date, tags, categories, index_img_path, blocks, post_dir,url_name):
# Add metadata
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美。


紀錄學習-使用Hexo架設部落格 (4) 使用OpenAI輔助總結與網址
https://codinglu.tw/2024/07/seo-friendly-url-name-for-blog-post-title-紀錄學習-使用hexo架設部落格-4-使用openai輔助總結與網址-hexo-python-ai/
作者
阿盧
發布於
2024年7月25日
許可協議
📌 本文瀏覽量: 0