AI生成文章会被检测出来吗 降重方法与人工写作对比技巧
- Linkreate AI插件 文章
- 2025-08-30 19:42:16
- 17阅读
AI生成文章的检测原理
AI生成文章之所以能被检测出来,主要基于其特定的文本特征和模式。当前主流的AI检测工具通过分析文本的 perplexity(困惑度)和 burstiness(突发性)等指标来判断内容是否由AI生成。
AI生成的文本通常具有以下特征:
- 句法结构过于规整,缺乏人类写作中的不规则变化
- 词汇使用模式相对固定,偏好常用词而非特定领域的专业术语
- 段落长度和句子结构过于均匀,缺乏人类写作中的自然变化
- 缺乏深度的个人见解和独特的表达方式
- 上下文连贯性过强,缺乏人类写作中常见的思维跳跃
主流AI检测工具分析
当前市场上有多款AI检测工具,它们各有特点和检测准确率:
检测工具 | 检测原理 | 准确率 | 适用场景 |
---|---|---|---|
Turnitin | 基于文本特征分析和机器学习模型 | 约98% | 学术论文检测 |
Originality.ai | 结合GPT-3.5和GPT-4的检测算法 | 约94% | 网络内容检测 |
GPTZero | 分析文本的perplexity和burstiness | 约85% | 教育领域检测 |
Content at Scale | 多维度分析文本特征 | 约90% | SEO内容检测 |
AI生成文章与人工写作的对比
AI生成文章与人工写作在多个维度上存在明显差异,了解这些差异有助于我们更好地理解AI检测的原理和降重的方法。
创作过程对比
人工写作通常是一个非线性的过程,包括构思、草稿、修改、润色等多个阶段,每个阶段都可能反复进行。而AI生成文章则是一个线性的、一次性的过程,基于输入的提示词直接生成完整内容。
内容特征对比
人工写作的内容通常具有以下特征:
- 个人风格明显,用词习惯独特
- 逻辑结构灵活,可能存在跳跃性思维
- 情感表达丰富,能体现作者的个人经历和观点
- 错误和不一致性较多,但更贴近真实人类表达
AI生成文章的内容特征:
- 语言规范,语法错误少
- 逻辑结构严谨,段落过渡平滑
- 表达方式趋于平均化,缺乏个人特色
- 内容深度有限,难以展现真正的创新思维
降低AI检测率的有效方法
针对AI生成文章的检测特征,我们可以采取多种方法来降低AI检测率,使内容更接近人工写作的风格。
内容结构调整
改变AI生成文章的段落结构和句子长度是降低检测率的有效方法。以下是一个简单的Python代码示例,用于随机调整段落结构:
import random
import re
def restructure_content(text):
将文本分割成句子
sentences = re.split(r'(?<=[。!?])s', text)
随机调整句子顺序
random.shuffle(sentences)
随机合并或拆分句子
restructured_sentences = []
i = 0
while i 0.7 and i < len(sentences) - 1:
合并两个句子
restructured_sentences.append(sentences[i] + sentences[i+1])
i += 2
else:
restructured_sentences.append(sentences[i])
i += 1
重新组合成文本
restructured_text = ''.join(restructured_sentences)
return restructured_text
词汇替换与表达多样化
AI生成文章往往使用相似的词汇和表达方式,通过词汇替换和表达多样化可以有效降低检测率。以下是一个使用同义词替换的Python函数示例:
import random
synonyms_dict = {
"重要": ["关键", "核心", "主要", "基本", "根本"],
"增加": ["提高", "提升", "增强", "加强", "扩大"],
"减少": ["降低", "减小", "缩减", "收缩", "压缩"],
"问题": ["难题", "困难", "挑战", "障碍", "麻烦"],
"方法": ["方式", "途径", "手段", "措施", "策略"]
}
def replace_synonyms(text):
words = text.split()
for i in range(len(words)):
if words[i] in synonyms_dict and random.random() > 0.5:
words[i] = random.choice(synonyms_dict[words[i]])
return ' '.join(words)
增加个人风格与见解
在AI生成文章中增加个人风格和见解是降低检测率的关键。可以通过以下方式实现:
- 添加个人经历或案例
- 引入独特的观点或见解
- 使用特定的表达习惯或口头禅
- 增加情感色彩和主观评价
人工修改与润色
对AI生成文章进行人工修改和润色是最直接有效的降重方法。以下是修改的重点方向:
- 调整句子结构,避免过于规整的表达
- 增加过渡词和连接词,使文章更自然流畅
- 添加个人观点和评论
- 适当增加一些不完美之处,如口语化表达或轻微的语法错误
实际应用案例
使用DeepSeek生成文章并降重
DeepSeek是一款强大的AI写作工具,但直接生成的内容容易被检测。以下是一个使用DeepSeek生成文章并进行降重的实际案例:
- 首先,使用DeepSeek生成基础文章内容:
curl -X POST "https://api.deepseek.com/v1/chat/completions" -H "Content-Type: application/json" -H "Authorization: Bearer YOUR_API_KEY" -d '{ "model": "deepseek-chat", "messages": [ {"role": "system", "content": "你是一个专业的文章写作助手"}, {"role": "user", "content": "请写一篇关于人工智能发展趋势的文章,字数约1000字"} ] }'
- 对生成的内容进行降重处理:
import re import random def reduce_ai_detection(text): 随机调整段落结构 paragraphs = text.split('nn') random.shuffle(paragraphs) text = 'nn'.join(paragraphs) 增加个人观点 personal_comments = [ "在我看来,", "从我的经验来看,", "我个人认为,", "根据我的观察,", "不得不说," ] sentences = re.split(r'(? 0.8: sentences[i] = random.choice(personal_comments) + sentences[i] text = ''.join(sentences) 增加一些口语化表达 colloquial_expressions = [ "说实话,", "老实说,", "说白了,", "讲道理,", "实际上," ] if random.random() > 0.5: text = random.choice(colloquial_expressions) + text return text 假设ai_text是DeepSeek生成的内容 ai_text = "AI生成的文章内容..." humanized_text = reduce_ai_detection(ai_text) print(humanized_text)
使用WordPress插件进行AI内容优化
WordPress平台上有多种AI写作和优化插件,可以帮助用户生成和优化内容。以下是一个使用WordPress AI插件优化内容的示例:
json_encode(array(
'content' => $content,
'level' => $optimization_level
)),
'headers' => array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . get_option('ai_optimization_api_key')
)
));
if (is_wp_error($response)) {
wp_send_json_error('优化请求失败');
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
wp_send_json_success($data['optimized_content']);
}
add_action('wp_ajax_ai_optimize_content', 'handle_ai_optimization_request');
AI生成文章与人工写作的迁移策略
对于需要从纯AI生成文章迁移到更接近人工写作风格的内容,可以采用以下策略:
渐进式优化法
渐进式优化法是指通过多次迭代,逐步将AI生成的内容优化为更接近人工写作的风格。具体步骤如下:
- 使用AI生成初稿
- 进行基础的结构调整和词汇替换
- 添加个人观点和见解
- 进行深度润色和风格调整
- 最终审校和修改
混合创作法
混合创作法是指结合AI生成和人工写作的优势,采用以下方式进行内容创作:
- 使用AI生成文章框架和大纲
- 人工撰写关键段落和个人观点
- 使用AI辅助生成补充内容和案例
- 人工整合和统一风格
- 使用AI进行语法检查和基础润色
- 最终人工审校和个性化调整
AI辅助人工写作法
AI辅助人工写作法是以人工写作为主导,AI为辅助的创作方式:
// AI辅助写作工具示例
class AIAssistedWritingTool {
constructor(apiKey) {
this.apiKey = apiKey;
this.apiUrl = 'https://api.openai.com/v1/chat/completions';
}
// 生成写作建议
async generateWritingSuggestions(topic, context) {
const prompt = `请为以下主题和上下文提供写作建议:
主题:${topic}
上下文:${context}
请提供3-5个写作角度和关键点。`;
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'system', content: '你是一个专业的写作助手' },
{ role: 'user', content: prompt }
]
})
});
const data = await response.json();
return data.choices[0].message.content;
}
// 优化句子表达
async optimizeSentence(sentence) {
const prompt = `请优化以下句子的表达,使其更自然流畅,保持原意不变:
句子:${sentence}`;
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'system', content: '你是一个专业的写作助手' },
{ role: 'user', content: prompt }
]
})
});
const data = await response.json();
return data.choices[0].message.content;
}
// 检查AI检测率
async checkAIDetectionRate(text) {
const prompt = `请分析以下文本的AI检测率,并提供改进建议:
文本:${text}`;
const response = await fetch(this.apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'system', content: '你是一个专业的AI内容检测助手' },
{ role: 'user', content: prompt }
]
})
});
const data = await response.json();
return data.choices[0].message.content;
}
}
// 使用示例
const writingTool = new AIAssistedWritingTool('your-api-key');
AI生成文章的检测与优化工具对比
市面上有多种AI生成文章的检测与优化工具,它们各有特点和适用场景。以下是对几款主流工具的对比:
工具名称 | 功能特点 | 检测准确率 | 优化效果 | 适用场景 |
---|---|---|---|---|
Turnitin | 专业的学术检测,支持多种AI模型检测 | 98% | 不提供优化功能 | 学术论文、教育领域 |
Originality.ai | 综合检测与优化,支持批量处理 | 94% | 提供基础优化建议 | 网络内容、SEO文章 |
GPTZero | 专注于教育领域的AI检测 | 85% | 不提供优化功能 | 教育领域、学生作业 |
Content at Scale | 检测与优化一体化,支持多种AI模型 | 90% | 提供深度优化功能 | 内容营销、SEO优化 |
Wordtune | 专注于内容优化和重写 | 不提供检测功能 | 提供高级优化功能 | 内容创作、文章优化 |
AI生成文章的降重技术实现
对于需要批量处理AI生成文章的场景,可以开发专门的降重工具。以下是一个基于Python的AI文章降重工具的实现示例:
import re
import random
import json
import requests
from collections import defaultdict
class AIDedetector:
def __init__(self, config_file='config.json'):
with open(config_file, 'r', encoding='utf-8') as f:
self.config = json.load(f)
self.synonyms_dict = self._load_synonyms()
self.transition_words = self._load_transition_words()
self.personal_expressions = self._load_personal_expressions()
def _load_synonyms(self):
"""加载同义词词典"""
synonyms_dict = defaultdict(list)
从文件加载同义词词典
try:
with open(self.config['synonyms_file'], 'r', encoding='utf-8') as f:
synonyms_data = json.load(f)
for word, synonyms in synonyms_data.items():
synonyms_dict[word] = synonyms
except FileNotFoundError:
print("同义词词典文件未找到,使用默认词典")
默认同义词词典
synonyms_dict.update({
"重要": ["关键", "核心", "主要", "基本", "根本"],
"增加": ["提高", "提升", "增强", "加强", "扩大"],
"减少": ["降低", "减小", "缩减", "收缩", "压缩"],
"问题": ["难题", "困难", "挑战", "障碍", "麻烦"],
"方法": ["方式", "途径", "手段", "措施", "策略"]
})
return synonyms_dict
def _load_transition_words(self):
"""加载过渡词"""
return [
"然而", "不过", "但是", "因此", "所以", "总的来说",
"首先", "其次", "最后", "另外", "此外", "不仅如此",
"事实上", "实际上", "基本上", "大体上", "总的来说"
]
def _load_personal_expressions(self):
"""加载个人表达"""
return [
"在我看来,", "从我的经验来看,", "我个人认为,",
"根据我的观察,", "不得不说,", "老实说,",
"说实话,", "说白了,", "讲道理,", "实际上,"
]
def replace_synonyms(self, text, replace_ratio=0.3):
"""替换同义词"""
words = text.split()
replaced_count = 0
max_replace = int(len(words) replace_ratio)
for i in range(len(words)):
if replaced_count >= max_replace:
break
if words[i] in self.synonyms_dict and random.random() > 0.5:
words[i] = random.choice(self.synonyms_dict[words[i]])
replaced_count += 1
return ' '.join(words)
def add_transition_words(self, text, add_ratio=0.2):
"""添加过渡词"""
sentences = re.split(r'(?= max_add:
break
if random.random() > 0.5:
transition_word = random.choice(self.transition_words)
sentences[i] = transition_word + "," + sentences[i]
added_count += 1
return ''.join(sentences)
def add_personal_expressions(self, text, add_ratio=0.15):
"""添加个人表达"""
sentences = re.split(r'(?= max_add:
break
if random.random() > 0.7:
personal_expr = random.choice(self.personal_expressions)
sentences[i] = personal_expr + sentences[i]
added_count += 1
return ''.join(sentences)
def adjust_sentence_structure(self, text):
"""调整句子结构"""
随机拆分长句
sentences = re.split(r'(? 100 and random.random() > 0.5:
尝试在逗号处拆分句子
parts = re.split(r',|;', sentence)
if len(parts) > 1:
adjusted_sentences.extend(parts)
else:
adjusted_sentences.append(sentence)
else:
adjusted_sentences.append(sentence)
随机合并短句
final_sentences = []
i = 0
while i < len(adjusted_sentences):
if i < len(adjusted_sentences) - 1 and len(adjusted_sentences[i]) 0.5:
合并两个短句
final_sentences.append(adjusted_sentences[i] + "," + adjusted_sentences[i+1])
i += 2
else:
final_sentences.append(adjusted_sentences[i])
i += 1
确保句子以正确的标点符号结尾
for i in range(len(final_sentences)):
if not final_sentences[i].endswith('。') and not final_sentences[i].endswith('!') and not final_sentences[i].endswith('?'):
final_sentences[i] += '。'
return ''.join(final_sentences)
def optimize_text(self, text):
"""综合优化文本"""
应用各种优化技术
text = self.replace_synonyms(text)
text = self.add_transition_words(text)
text = self.add_personal_expressions(text)
text = self.adjust_sentence_structure(text)
return text
def check_ai_detection(self, text):
"""检查AI检测率"""
api_url = self.config['detection_api_url']
api_key = self.config['detection_api_key']
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
data = {
'text': text
}
try:
response = requests.post(api_url, headers=headers, json=data)
result = response.json()
return result
except Exception as e:
print(f"AI检测请求失败: {e}")
return None
使用示例
if __name__ == "__main__":
dedetector = AIDedetector()
原始AI生成文本
ai_text = "人工智能是一门研究如何使计算机模拟人类智能的学科。它包括机器学习、自然语言处理、计算机视觉等多个领域。随着技术的发展,人工智能在各个行业都得到了广泛应用。"
print("原始文本:")
print(ai_text)
print("n")
优化文本
optimized_text = dedetector.optimize_text(ai_text)
print("优化后的文本:")
print(optimized_text)
print("n")
检查AI检测率
detection_result = dedetector.check_ai_detection(ai_text)
if detection_result:
print("原始文本AI检测结果:")
print(json.dumps(detection_result, ensure_ascii=False, indent=2))
print("n")
optimized_detection_result = dedetector.check_ai_detection(optimized_text)
if optimized_detection_result:
print("优化后文本AI检测结果:")
print(json.dumps(optimized_detection_result, ensure_ascii=False, indent=2))
WordPress中集成AI生成与优化功能
对于WordPress用户,可以通过插件或自定义代码集成AI生成与优化功能。以下是一个完整的WordPress插件实现示例,用于AI内容生成和优化:
prefix . 'aicgo_settings';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
setting_name varchar(50) NOT NULL,
setting_value text NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
// 添加默认设置
$default_settings = array(
array('setting_name' => 'api_provider', 'setting_value' => 'openai'),
array('setting_name' => 'api_key', 'setting_value' => ''),
array('setting_name' => 'model', 'setting_value' => 'gpt-3.5-turbo'),
array('setting_name' => 'max_tokens', 'setting_value' => '2000'),
array('setting_name' => 'temperature', 'setting_value' => '0.7'),
array('setting_name' => 'optimization_level', 'setting_value' => 'medium')
);
foreach ($default_settings as $setting) {
$wpdb->insert(
$table_name,
array(
'setting_name' => $setting['setting_name'],
'setting_value' => $setting['setting_value']
)
);
}
}
// 添加管理菜单
add_action('admin_menu', 'aicgo_admin_menu');
function aicgo_admin_menu() {
add_menu_page(
'AI Content Generator & Optimizer',
'AI Content',
'manage_options',
'aicgo-settings',
'aicgo_settings_page',
'dashicons-edit-page',
30
);
add_submenu_page(
'aicgo-settings',
'Settings',
'Settings',
'manage_options',
'aicgo-settings',
'aicgo_settings_page'
);
add_submenu_page(
'aicgo-settings',
'Content Generator',
'Generator',
'edit_posts',
'aicgo-generator',
'aicgo_generator_page'
);
add_submenu_page(
'aicgo-settings',
'Content Optimizer',
'Optimizer',
'edit_posts',
'aicgo-optimizer',
'aicgo_optimizer_page'
);
}
// 设置页面
function aicgo_settings_page() {
if (!current_user_can('manage_options')) {
return;
}
// 保存设置
if (isset($_POST['save_settings'])) {
global $wpdb;
$table_name = $wpdb->prefix . 'aicgo_settings';
$settings = array(
'api_provider' => sanitize_text_field($_POST['api_provider']),
'api_key' => sanitize_text_field($_POST['api_key']),
'model' => sanitize_text_field($_POST['model']),
'max_tokens' => intval($_POST['max_tokens']),
'temperature' => floatval($_POST['temperature']),
'optimization_level' => sanitize_text_field($_POST['optimization_level'])
);
foreach ($settings as $name => $value) {
$wpdb->update(
$table_name,
array('setting_value' => $value),
array('setting_name' => $name)
);
}
echo '设置已保存!
';
}
// 获取当前设置
global $wpdb;
$table_name = $wpdb->prefix . 'aicgo_settings';
$settings = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");
$current_settings = array();
foreach ($settings as $setting) {
$current_settings[$setting->setting_name] = $setting->setting_value;
}
// 显示设置页面
?>
AI Content Generator & Optimizer Settings
API Provider
<option value="openai" >OpenAI
<option value="deepseek" >DeepSeek
<option value="gemini" >Gemini
API Key
<input type="text" name="api_key" value="" class="regular-text">
Model
<input type="text" name="model" value="" class="regular-text">
Max Tokens
<input type="number" name="max_tokens" value="" class="small-text">
Temperature
<input type="number" name="temperature" value="" step="0.1" min="0" max="1" class="small-text">
Optimization Level
<option value="low" >Low
<option value="medium" >Medium
<option value="high" >High
prefix . 'aicgo_settings';
$settings = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");
$current_settings = array();
foreach ($settings as $setting) {
$current_settings[$setting->setting_name] = $setting->setting_value;
}
// 显示生成器页面
?>
AI Content Generator
Generate Content
Topic
Content Type
Blog Post
Article
Product Description
Social Media Post
Word Count
Tone
Formal
Casual
Professional
Friendly
Keywords
jQuery(document).ready(function($) {
$('aicgo-generator-form').on('submit', function(e) {
e.preventDefault();
$('generate_content').prop('disabled', true).val('Generating...');
$('generated_content').(' Generating content...');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'aicgo_generate_content',
topic: $('topic').val(),
content_type: $('content_type').val(),
word_count: $('word_count').val(),
tone: $('tone').val(),
keywords: $('keywords').val()
},
success: function(response) {
if (response.success) {
$('generated_content').('Content generated successfully!
');
} else {
$('generated_content').('Error: ' + response.data + '
');
}
$('generate_content').prop('disabled', false).val('Generate Content');
},
error: function() {
$('generated_content').('An error occurred. Please try again.
');
$('generate_content').prop('disabled', false).val('Generate Content');
}
});
});
$(document).on('click', 'create_post', function(e) {
e.preventDefault();
var content = $('generated_content textarea').val();
var topic = $('topic').val();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'aicgo_create_post',
title: topic,
content: content
},
success: function(response) {
if (response.success) {
$('generated_content').append('');
} else {
$('generated_content').append('Error: ' + response.data + '
');
}
},
error: function() {
$('generated_content').append('An error occurred. Please try again.
');
}
});
});
});
prefix . 'aicgo_settings';
$settings = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");
$current_settings = array();
foreach ($settings as $setting) {
$current_settings[$setting->setting_name] = $setting->setting_value;
}
// 获取最近的帖子
$recent_posts = get_posts(array(
'numberposts' => 10,
'post_status' => 'publish'
));
// 显示优化器页面
?>
AI Content Optimizer
Optimize Content
Select Post
-- Select a post --
<option value="ID; ?>">post_title; ?>
Optimization Level
Low
Medium
High
Optimization Goals
jQuery(document).ready(function($) {
$('aicgo-optimizer-form').on('submit', function(e) {
e.preventDefault();
if (!$('post_id').val()) {
$('optimization_result').('Please select a post to optimize.
');
return;
}
$('optimize_content').prop('disabled', true).val('Optimizing...');
$('optimization_result').(' Optimizing content...');
var goals = [];
$('input[name="goals[]"]:checked').each(function() {
goals.push($(this).val());
});
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'aicgo_optimize_content',
post_id: $('post_id').val(),
optimization_level: $('optimization_level').val(),
goals: goals
},
success: function(response) {
if (response.success) {
$('optimization_result').('Content optimized successfully!
Original Content
Optimized Content
');
// 显示AI检测结果
if (response.data.ai_detection) {
$('ai_detection_result').('AI Detection Results
Version AI Detection Score Original ' + response.data.ai_detection.original + '% Optimized ' + response.data.ai_detection.optimized + '%
');
}
} else {
$('optimization_result').('Error: ' + response.data + '
');
}
$('optimize_content').prop('disabled', false).val('Optimize Content');
},
error: function() {
$('optimization_result').('An error occurred. Please try again.
');
$('optimize_content').prop('disabled', false).val('Optimize Content');
}
});
});
$(document).on('click', 'update_post', function(e) {
e.preventDefault();
var post_id = $('post_id').val();
var optimized_content = $('optimized_content').val();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'aicgo_update_post',
post_id: post_id,
content: optimized_content
},
success: function(response) {
if (response.success) {
$('optimization_result').append('');
} else {
$('optimization_result').append('Error: ' + response.data + '
');
}
},
error: function() {
$('optimization_result').append('An error occurred. Please try again.
');
}
});
});
});
prefix . 'aicgo_settings';
$settings = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");
$api_settings = array();
foreach ($settings as $setting) {
$api_settings[$setting->setting_name] = $setting->setting_value;
}
// 构建提示词
$prompt = "请生成一篇关于{$topic}的{$content_type},字数约{$word_count}字,语气{$tone}。";
if (!empty($keywords)) {
$prompt .= "请包含以下关键词:{$keywords}。";
}
$prompt .= "请确保内容原创、有价值,并降低AI检测率。";
// 调用AI API生成内容
$content = aicgo_call_ai_api($prompt, $api_settings);
if ($content) {
wp_send_json_success(array('content' => $content));
} else {
wp_send_json_error('Failed to generate content');
}
}
add_action('wp_ajax_aicgo_create_post', 'aicgo_create_post_handler');
function aicgo_create_post_handler() {
if (!current_user_can('edit_posts')) {
wp_send_json_error('Permission denied');
}
$title = sanitize_text_field($_POST['title']);
$content = wp_kses_post($_POST['content']);
$post_data = array(
'post_title' => $title,
'post_content' => $content,
'post_status' => 'draft',
'post_author' => get_current_user_id(),
'post_type' => 'post'
);
$post_id = wp_insert_post($post_data);
if ($post_id) {
$edit_link = get_edit_post_link($post_id);
$view_link = get_permalink($post_id);
wp_send_json_success(array(
'edit_link' => $edit_link,
'view_link' => $view_link
));
} else {
wp_send_json_error('Failed to create post');
}
}
add_action('wp_ajax_aicgo_optimize_content', 'aicgo_optimize_content_handler');
function aicgo_optimize_content_handler() {
if (!current_user_can('edit_posts')) {
wp_send_json_error('Permission denied');
}
$post_id = intval($_POST['post_id']);
$optimization_level = sanitize_text_field($_POST['optimization_level']);
$goals = isset($_POST['goals']) ? array_map('sanitize_text_field', $_POST['goals']) : array();
$post = get_post($post_id);
if (!$post) {
wp_send_json_error('Post not found');
}
$original_content = $post->post_content;
// 获取API设置
global $wpdb;
$table_name = $wpdb->prefix . 'aicgo_settings';
$settings = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");
$api_settings = array();
foreach ($settings as $setting) {
$api_settings[$setting->setting_name] = $setting->setting_value;
}
// 构建优化提示词
$prompt = "请优化以下内容,优化级别:{$optimization_level}。nn";
$prompt .= "优化目标:n";
foreach ($goals as $goal) {
$prompt .= "- {$goal}n";
}
$prompt .= "n原始内容:n{$original_content}nn";
$prompt .= "请保持原意不变,但使内容更自然、更人性化,降低AI检测率。";
// 调用AI API优化内容
$optimized_content = aicgo_call_ai_api($prompt, $api_settings);
if ($optimized_content) {
// 检查AI检测率
$ai_detection = array();
if (in_array('reduce_ai_detection', $goals)) {
$ai_detection['original'] = aicgo_check_ai_detection($original_content, $api_settings);
$ai_detection['optimized'] = aicgo_check_ai_detection($optimized_content, $api_settings);
}
wp_send_json_success(array(
'original_content' => $original_content,
'optimized_content' => $optimized_content,
'ai_detection' => $ai_detection
));
} else {
wp_send_json_error('Failed to optimize content');
}
}
add_action('wp_ajax_aicgo_update_post', 'aicgo_update_post_handler');
function aicgo_update_post_handler() {
if (!current_user_can('edit_posts')) {
wp_send_json_error('Permission denied');
}
$post_id = intval($_POST['post_id']);
$content = wp_kses_post($_POST['content']);
$post_data = array(
'ID' => $post_id,
'post_content' => $content
);
$result = wp_update_post($post_data);
if ($result) {
$edit_link = get_edit_post_link($post_id);
$view_link = get_permalink($post_id);
wp_send_json_success(array(
'edit_link' => $edit_link,
'view_link' => $view_link
));
} else {
wp_send_json_error('Failed to update post');
}
}
// 调用AI API
function aicgo_call_ai_api($prompt, $api_settings) {
$api_provider = $api_settings['api_provider'];
$api_key = $api_settings['api_key'];
$model = $api_settings['model'];
$max_tokens = intval($api_settings['max_tokens']);
$temperature = floatval($api_settings['temperature']);
if (empty($api_key)) {
return false;
}
switch ($api_provider) {
case 'openai':
return aicgo_call_openai_api($prompt, $api_key, $model, $max_tokens, $temperature);
case 'deepseek':
return aicgo_call_deepseek_api($prompt, $api_key, $model, $max_tokens, $temperature);
case 'gemini':
return aicgo_call_gemini_api($prompt, $api_key, $model, $max_tokens, $temperature);
default:
return false;
}
}
// 调用OpenAI API
function aicgo_call_openai_api($prompt, $api_key, $model, $max_tokens, $temperature) {
$url = 'https://api.openai.com/v1/chat/completions';
$headers = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
);
$body = json_encode(array(
'model' => $model,
'messages' => array(
array('role' => 'system', 'content' => '你是一个专业的写作助手,擅长生成高质量、低AI检测率的内容。'),
array('role' => 'user', 'content' => $prompt)
),
'max_tokens' => $max_tokens,
'temperature' => $temperature
));
$response = wp_remote_post($url, array(
'headers' => $headers,
'body' => $body,
'timeout' => 30
));
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['choices'][0]['message']['content'])) {
return $data['choices'][0]['message']['content'];
}
return false;
}
// 调用DeepSeek API
function aicgo_call_deepseek_api($prompt, $api_key, $model, $max_tokens, $temperature) {
$url = 'https://api.deepseek.com/v1/chat/completions';
$headers = array(
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $api_key
);
$body = json_encode(array(
'model' => $model,
'messages' => array(
array('role' => 'system', 'content' => '你是一个专业的写作助手,擅长生成高质量、低AI检测率的内容。'),
array('role' => 'user', 'content' => $prompt)
),
'max_tokens' => $max_tokens,
'temperature' => $temperature
));
$response = wp_remote_post($url, array(
'headers' => $headers,
'body' => $body,
'timeout' => 30
));
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['choices'][0]['message']['content'])) {
return $data['choices'][0]['message']['content'];
}
return false;
}
// 调用Gemini API
function aicgo_call_gemini_api($prompt, $api_key, $model, $max_tokens, $temperature) {
$url = "https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$api_key}";
$headers = array(
'Content-Type' => 'application/json'
);
$body = json_encode(array(
'contents' => array(
array(
'parts' => array(
array('text' => $prompt)
)
)
),
'generationConfig' => array(
'maxOutputTokens' => $max_tokens,
'temperature' => $temperature
)
));
$response = wp_remote_post($url, array(
'headers' => $headers,
'body' => $body,
'timeout' => 30
));
if (is_wp_error($response)) {
return false;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (isset($data['candidates'][0]['content']['parts'][0]['text'])) {
return $data['candidates'][0]['content']['parts'][0]['text'];
}
return false;
}
// 检查AI检测率
function aicgo_check_ai_detection($text, $api_settings) {
// 这里可以集成第三方AI检测API
// 由于API限制,这里返回模拟值
// 实际实现中,可以调用如Originality.ai等AI检测服务的API
// 返回AI检测百分比
// 模拟实现
return rand(10, 90);
}
// 在编辑器中添加AI生成和优化按钮
add_action('admin_head', 'aicgo_add_editor_buttons');
function aicgo_add_editor_buttons() {
if (!current_user_can('edit_posts')) {
return;
}
?>
jQuery(document).ready(function($) {
// 添加AI生成按钮
if ($('wp-content-editor-tools').length) {
$('wp-content-editor-tools').append('');
}
// 添加AI优化按钮
if ($('wp-content-editor-tools').length) {
$('wp-content-editor-tools').append('');
}
// AI生成按钮点击事件
$(document).on('click', 'aicgo-generate-content-btn', function() {
var topic = prompt('Enter topic for content generation:');
if (!topic) return;
var content_type = prompt('Enter content type (blog_post, article, product_description, social_media):', 'blog_post');
if (!content_type) content_type = 'blog_post';
var word_count = prompt('Enter word count:', '500');
if (!word_count) word_count = '500';
var tone = prompt('Enter tone (formal, casual, professional, friendly):', 'professional');
if (!tone) tone = 'professional';
var keywords = prompt('Enter keywords (comma separated):', '');
$('aicgo-generate-content-btn').prop('disabled', true).text('Generating...');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'aicgo_generate_content',
topic: topic,
content_type: content_type,
word_count: word_count,
tone: tone,
keywords: keywords
},
success: function(response) {
if (response.success) {
if (tinymce.activeEditor) {
tinymce.activeEditor.setContent(response.data.content);
} else {
$('content').val(response.data.content);
}
} else {
alert('Error: ' + response.data);
}
$('aicgo-generate-content-btn').prop('disabled', false).text('AI Generate');
},
error: function() {
alert('An error occurred. Please try again.');
$('aicgo-generate-content-btn').prop('disabled', false).text('AI Generate');
}
});
});
// AI优化按钮点击事件
$(document).on('click', 'aicgo-optimize-content-btn', function() {
var content;
if (tinymce.activeEditor) {
content = tinymce.activeEditor.getContent();
} else {
content = $('content').val();
}
if (!content) {
alert('No content to optimize.');
return;
}
var optimization_level = prompt('Enter optimization level (low, medium, high):', 'medium');
if (!optimization_level) optimization_level = 'medium';
var goals_input = prompt('Enter optimization goals (comma separated: reduce_ai_detection, improve_readability, enhance_seo, add_personal_touch):', 'reduce_ai_detection');
var goals = goals_input ? goals_input.split(',').map(function(goal) { return goal.trim(); }) : ['reduce_ai_detection'];
$('aicgo-optimize-content-btn').prop('disabled', true).text('Optimizing...');
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'aicgo_optimize_existing_content',
content: content,
optimization_level: optimization_level,
goals: goals
},
success: function(response) {
if (response.success) {
if (tinymce.activeEditor) {
tinymce.activeEditor.setContent(response.data.optimized_content);
} else {
$('content').val(response.data.optimized_content);
}
if (response.data.ai_detection) {
alert('AI Detection Score - Original: ' + response.data.ai_detection.original + '%, Optimized: ' + response.data.ai_detection.optimized + '%');
}
} else {
alert('Error: ' + response.data);
}
$('aicgo-optimize-content-btn').prop('disabled', false).text('AI Optimize');
},
error: function() {
alert('An error occurred. Please try again.');
$('aicgo-optimize-content-btn').prop('disabled', false).text('AI Optimize');
}
});
});
});
prefix . 'aicgo_settings';
$settings = $wpdb->get_results("SELECT setting_name, setting_value FROM $table_name");
$api_settings = array();
foreach ($settings as $setting) {
$api_settings[$setting->setting_name] = $setting->setting_value;
}
// 构建优化提示词
$prompt = "请优化以下内容,优化级别:{$optimization_level}。nn";
$prompt .= "优化目标:n";
foreach ($goals as $goal) {
$prompt .= "- {$goal}n";
}
$prompt .= "n原始内容:n{$content}nn";
$prompt .= "请保持原意不变,但使内容更自然、更人性化,降低AI检测率。";
// 调用AI API优化内容
$optimized_content = aicgo_call_ai_api($prompt, $api_settings);
if ($optimized_content) {
// 检查AI检测率
$ai_detection = array();
if (in_array('reduce_ai_detection', $goals)) {
$ai_detection['original'] = aicgo_check_ai_detection($content, $api_settings);
$ai_detection['optimized'] = aicgo_check_ai_detection($optimized_content, $api_settings);
}
wp_send_json_success(array(
'optimized_content' => $optimized_content,
'ai_detection' => $ai_detection
));
} else {
wp_send_json_error('Failed to optimize content');
}
}