TravelContentCreator/utils/tweet/content_judger.py
2025-07-08 18:24:23 +08:00

74 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
内容审核模块
"""
import logging
import json
from json_repair import loads as json_repair_loads
from typing import Dict, Any
from core.ai import AIAgent
# We'll need a specific config for the judger
# from core.config import ContentJudgerConfig
from utils.prompts import JudgerPromptBuilder
logger = logging.getLogger(__name__)
class ContentJudger:
"""内容审核类使用AI评估和修正内容"""
def __init__(self, ai_agent: AIAgent, system_prompt_path: str):
"""
初始化内容审核器
Args:
ai_agent: AIAgent实例
system_prompt_path: 审核系统提示的文件路径
"""
self.ai_agent = ai_agent
self.prompt_builder = JudgerPromptBuilder(system_prompt_path)
def judge(self, product_info: str, generated_content: str) -> Dict[str, Any]:
"""
审核内容,返回一个包含分析和修正后内容的字典
Args:
product_info: 用作参考的产品资料
generated_content: 需要审核的原始生成内容
Returns:
一个包含审核结果的字典,可能包括 "analysis", "title", "content"
"""
logger.info("开始内容审核...")
# 1. 构建提示
prompts = self.prompt_builder.build_prompts(product_info, generated_content)
# 2. 调用AI
try:
raw_result, _, _, _ = self.ai_agent.work(
system_prompt=prompts["system"],
user_prompt=prompts["user"]
)
except Exception as e:
logger.critical(f"内容审核时AI调用失败: {e}", exc_info=True)
return {"judge_success": False, "error": str(e)}
# 3. 解析结果
try:
# 假设结果是一个JSON字符串
judged_data = json_repair_loads(raw_result)
if isinstance(judged_data, dict) and "title" in judged_data and "content" in judged_data:
judged_data["judge_success"] = True
logger.info("内容审核成功完成。")
return judged_data
else:
logger.warning(f"审核响应JSON格式不正确或缺少键: {judged_data}")
return {"judge_success": False, "error": "Invalid JSON response", "raw_response": raw_result}
except (json.JSONDecodeError, ValueError) as e:
logger.error(f"解析审核响应JSON失败: {e}")
return {"judge_success": False, "error": "JSONDecodeError", "raw_response": raw_result}