- 新增项目配置文件(.gitignore, config.json)和核心文档(Todo.md, mcp.md) - 实现配置管理模块(config_manager.py),支持单例模式和自动保存 - 实现LLM服务模块(llm_service.py),包含文案生成、热点分析、评论回复等Prompt模板 - 实现SD服务模块(sd_service.py),封装Stable Diffusion WebUI API调用 - 实现MCP客户端模块(mcp_client.py),封装小红书MCP服务HTTP调用 - 实现主程序(main.py),构建Gradio界面,包含内容创作、热点探测、评论管家、账号登录、数据看板五大功能模块 - 保留V1版本备份(main_v1_backup.py)供参考 - 添加项目依赖文件(requirements.txt)
83 lines
2.2 KiB
Python
83 lines
2.2 KiB
Python
"""
|
|
配置管理模块
|
|
支持多配置项、默认值回退、自动保存
|
|
"""
|
|
import json
|
|
import os
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
CONFIG_FILE = "config.json"
|
|
OUTPUT_DIR = "xhs_workspace"
|
|
|
|
DEFAULT_CONFIG = {
|
|
"api_key": "",
|
|
"base_url": "https://api.openai.com/v1",
|
|
"sd_url": "http://127.0.0.1:7860",
|
|
"mcp_url": "http://localhost:18060/mcp",
|
|
"model": "gpt-3.5-turbo",
|
|
"persona": "温柔知性的时尚博主",
|
|
"auto_reply_enabled": False,
|
|
"schedule_enabled": False,
|
|
}
|
|
|
|
|
|
class ConfigManager:
|
|
"""配置管理器 - 单例模式"""
|
|
|
|
_instance = None
|
|
_config = None
|
|
|
|
def __new__(cls):
|
|
if cls._instance is None:
|
|
cls._instance = super().__new__(cls)
|
|
return cls._instance
|
|
|
|
def __init__(self):
|
|
if self._config is None:
|
|
self._config = self._load()
|
|
|
|
def _load(self) -> dict:
|
|
"""从文件加载配置,缺失项用默认值填充"""
|
|
config = DEFAULT_CONFIG.copy()
|
|
if os.path.exists(CONFIG_FILE):
|
|
try:
|
|
with open(CONFIG_FILE, "r", encoding="utf-8") as f:
|
|
saved = json.load(f)
|
|
config.update(saved)
|
|
except (json.JSONDecodeError, IOError) as e:
|
|
logger.warning("配置文件读取失败,使用默认值: %s", e)
|
|
return config
|
|
|
|
def save(self):
|
|
"""保存配置到文件"""
|
|
try:
|
|
with open(CONFIG_FILE, "w", encoding="utf-8") as f:
|
|
json.dump(self._config, f, indent=4, ensure_ascii=False)
|
|
except IOError as e:
|
|
logger.error("配置保存失败: %s", e)
|
|
|
|
def get(self, key: str, default=None):
|
|
"""获取配置项"""
|
|
return self._config.get(key, default)
|
|
|
|
def set(self, key: str, value):
|
|
"""设置配置项并自动保存"""
|
|
self._config[key] = value
|
|
self.save()
|
|
|
|
def update(self, data: dict):
|
|
"""批量更新配置"""
|
|
self._config.update(data)
|
|
self.save()
|
|
|
|
@property
|
|
def all(self) -> dict:
|
|
"""返回全部配置(副本)"""
|
|
return self._config.copy()
|
|
|
|
def ensure_workspace(self):
|
|
"""确保工作空间目录存在"""
|
|
os.makedirs(OUTPUT_DIR, exist_ok=True)
|