615 lines
22 KiB
Python
615 lines
22 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
小红书增强版发布器
|
||
集成图片风格生成功能,实现从内容到图片到发布的全自动化流程
|
||
"""
|
||
|
||
import argparse
|
||
import logging
|
||
import sys
|
||
import os
|
||
import json
|
||
import time
|
||
import subprocess
|
||
from pathlib import Path
|
||
from typing import List, Dict, Optional, Tuple
|
||
from datetime import datetime
|
||
|
||
# 添加当前目录到Python路径
|
||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||
sys.path.append("/home/ubuntu") # 添加xhs_image_generator路径
|
||
|
||
try:
|
||
from content_converter_fixed import ContentConverterFixed
|
||
from xhs_image_generator import XHSImageGenerator, XHSStyle, XHSLayout
|
||
from xhs_api_generator_fixed import XHSAPIGenerator
|
||
except ImportError as e:
|
||
print(f"导入错误: {e}")
|
||
print("请确保相关模块已安装")
|
||
sys.exit(1)
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
class XiaohongshuEnhancedPublisher:
|
||
"""增强版小红书发布器 - 集成图片风格生成"""
|
||
|
||
def __init__(self, config_path: str = None):
|
||
"""
|
||
初始化增强版发布器
|
||
|
||
Args:
|
||
config_path: 配置文件路径
|
||
"""
|
||
# 初始化组件
|
||
self.content_converter = ContentConverterFixed()
|
||
self.image_generator = XHSImageGenerator()
|
||
|
||
# 加载配置
|
||
self.config = self._load_config(config_path)
|
||
|
||
# 初始化API生成器(延迟初始化,需要API密钥)
|
||
self.api_generator = None
|
||
|
||
logger.info("增强版小红书发布器初始化完成")
|
||
logger.info(f"配置: {json.dumps(self.config, ensure_ascii=False, indent=2)}")
|
||
|
||
def _load_config(self, config_path: str) -> Dict:
|
||
"""加载配置文件"""
|
||
default_config = {
|
||
"xiaohongshu": {
|
||
"cli_path": "xhs",
|
||
"max_images": 9,
|
||
"default_tags": ["#技术资讯", "#科技新闻", "#AI", "#小红书运营"],
|
||
"publish_interval": 3600,
|
||
"auto_generate_images": True,
|
||
"default_style": "notion",
|
||
"default_layout": "balanced"
|
||
},
|
||
"image_generation": {
|
||
"api_key": None,
|
||
"api_base_url": "https://ark.cn-beijing.volces.com/api/v3",
|
||
"model": "doubao-seedream-4-5-251128",
|
||
"max_retries": 3,
|
||
"timeout": 60,
|
||
"output_dir": "/home/ubuntu/xhs_generated_images"
|
||
},
|
||
"content": {
|
||
"max_title_length": 30,
|
||
"max_content_length": 1000,
|
||
"auto_generate_tags": True,
|
||
"add_source_info": True,
|
||
"extract_key_points": True
|
||
}
|
||
}
|
||
|
||
# 如果提供了配置文件,则加载
|
||
if config_path and os.path.exists(config_path):
|
||
try:
|
||
with open(config_path, 'r', encoding='utf-8') as f:
|
||
user_config = json.load(f)
|
||
|
||
# 深度合并配置
|
||
def deep_merge(base, update):
|
||
for key, value in update.items():
|
||
if key in base and isinstance(base[key], dict) and isinstance(value, dict):
|
||
deep_merge(base[key], value)
|
||
else:
|
||
base[key] = value
|
||
return base
|
||
|
||
default_config = deep_merge(default_config, user_config)
|
||
logger.info(f"从 {config_path} 加载配置")
|
||
except Exception as e:
|
||
logger.error(f"加载配置文件失败: {e}")
|
||
|
||
# 确保输出目录存在
|
||
output_dir = default_config["image_generation"]["output_dir"]
|
||
os.makedirs(output_dir, exist_ok=True)
|
||
|
||
return default_config
|
||
|
||
def _init_api_generator(self) -> bool:
|
||
"""初始化API生成器"""
|
||
if self.api_generator is not None:
|
||
return True
|
||
|
||
api_key = self.config["image_generation"]["api_key"]
|
||
if not api_key:
|
||
logger.warning("未配置API密钥,图片生成功能将不可用")
|
||
return False
|
||
|
||
try:
|
||
self.api_generator = XHSAPIGenerator(
|
||
api_key=api_key,
|
||
base_url=self.config["image_generation"]["api_base_url"],
|
||
model=self.config["image_generation"]["model"]
|
||
)
|
||
logger.info("API生成器初始化成功")
|
||
return True
|
||
except Exception as e:
|
||
logger.error(f"API生成器初始化失败: {e}")
|
||
return False
|
||
|
||
def analyze_content(self, content: str) -> Dict:
|
||
"""
|
||
分析内容,推荐最佳风格和布局
|
||
|
||
Args:
|
||
content: 内容文本
|
||
|
||
Returns:
|
||
分析结果字典
|
||
"""
|
||
return self.image_generator.analyze_content(content)
|
||
|
||
def generate_images_for_content(self, content: str, style: str = None, layout: str = None) -> List[str]:
|
||
"""
|
||
为内容生成图片
|
||
|
||
Args:
|
||
content: 内容文本
|
||
style: 风格名称(可选,自动推荐)
|
||
layout: 布局名称(可选,自动推荐)
|
||
|
||
Returns:
|
||
生成的图片路径列表
|
||
"""
|
||
# 检查是否启用图片生成
|
||
if not self.config["xiaohongshu"]["auto_generate_images"]:
|
||
logger.info("图片生成功能已禁用")
|
||
return []
|
||
|
||
# 初始化API生成器
|
||
if not self._init_api_generator():
|
||
logger.warning("API生成器不可用,跳过图片生成")
|
||
return []
|
||
|
||
# 分析内容
|
||
analysis = self.analyze_content(content)
|
||
|
||
# 确定风格和布局
|
||
if style is None:
|
||
style = analysis["recommended_style"].value
|
||
if layout is None:
|
||
layout = analysis["recommended_layout"].value
|
||
|
||
logger.info(f"为内容生成图片 - 风格: {style}, 布局: {layout}")
|
||
|
||
# 生成提示词
|
||
try:
|
||
style_enum = XHSStyle(style)
|
||
layout_enum = XHSLayout(layout)
|
||
except ValueError as e:
|
||
logger.error(f"无效的风格或布局: {e}")
|
||
return []
|
||
|
||
prompt = self.image_generator.generate_prompt(content, style_enum, layout_enum)
|
||
|
||
# 生成图片
|
||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||
output_dir = Path(self.config["image_generation"]["output_dir"])
|
||
image_path = output_dir / f"xhs_{style}_{layout}_{timestamp}.png"
|
||
|
||
logger.info(f"调用API生成图片: {image_path}")
|
||
|
||
success = self.api_generator.generate_image(prompt, str(image_path), style_enum)
|
||
|
||
if success:
|
||
logger.info(f"✅ 图片生成成功: {image_path}")
|
||
return [str(image_path)]
|
||
else:
|
||
logger.error(f"❌ 图片生成失败")
|
||
return []
|
||
|
||
def publish_with_generated_images(self, markdown_file: str, style: str = None, layout: str = None) -> bool:
|
||
"""
|
||
使用生成的图片发布到小红书
|
||
|
||
Args:
|
||
markdown_file: Markdown文件路径
|
||
style: 图片风格(可选)
|
||
layout: 图片布局(可选)
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
try:
|
||
# 检查文件是否存在
|
||
if not os.path.exists(markdown_file):
|
||
logger.error(f"Markdown文件不存在: {markdown_file}")
|
||
return False
|
||
|
||
# 读取Markdown文件
|
||
with open(markdown_file, 'r', encoding='utf-8') as f:
|
||
markdown_content = f.read()
|
||
|
||
logger.info(f"读取Markdown文件: {markdown_file}")
|
||
logger.info(f"文件大小: {len(markdown_content)} 字符")
|
||
|
||
# 转换为小红书格式
|
||
xhs_content = self.content_converter.convert_markdown_to_xiaohongshu(markdown_content)
|
||
|
||
if not xhs_content:
|
||
logger.error("内容转换失败")
|
||
return False
|
||
|
||
logger.info(f"转换后内容大小: {len(xhs_content)} 字符")
|
||
|
||
# 提取关键信息用于图片生成
|
||
title = self._extract_title(markdown_content)
|
||
key_content = self._extract_key_content(markdown_content)
|
||
|
||
# 生成图片
|
||
generated_images = self.generate_images_for_content(key_content, style, layout)
|
||
|
||
# 如果没有生成图片,使用默认图片或现有图片
|
||
images_to_use = generated_images
|
||
if not images_to_use:
|
||
logger.info("使用默认图片或现有图片")
|
||
# 这里可以添加从Markdown中提取现有图片的逻辑
|
||
images_to_use = []
|
||
|
||
# 调用小红书CLI发布
|
||
return self._call_xhs_cli(title, xhs_content, images_to_use)
|
||
|
||
except Exception as e:
|
||
logger.error(f"发布过程中发生错误: {e}")
|
||
return False
|
||
|
||
def _extract_title(self, markdown_content: str) -> str:
|
||
"""从Markdown中提取标题"""
|
||
lines = markdown_content.strip().split('\n')
|
||
for line in lines:
|
||
line = line.strip()
|
||
if line.startswith('# '):
|
||
return line[2:].strip()
|
||
# 如果没有找到标题,使用第一行或默认标题
|
||
if lines and lines[0].strip():
|
||
return lines[0].strip()[:30]
|
||
return "小红书笔记"
|
||
|
||
def _extract_key_content(self, markdown_content: str) -> str:
|
||
"""从Markdown中提取关键内容用于图片生成"""
|
||
# 提取前200个字符作为关键内容
|
||
content = markdown_content.strip()
|
||
if len(content) > 200:
|
||
content = content[:200] + "..."
|
||
|
||
# 移除Markdown标记
|
||
import re
|
||
content = re.sub(r'#+\s*', '', content) # 移除标题标记
|
||
content = re.sub(r'!\[.*?\]\(.*?\)', '', content) # 移除图片标记
|
||
content = re.sub(r'\[.*?\]\(.*?\)', '', content) # 移除链接标记
|
||
content = re.sub(r'`.*?`', '', content) # 移除代码标记
|
||
content = re.sub(r'\*\*.*?\*\*', '', content) # 移除粗体标记
|
||
content = re.sub(r'\*.*?\*', '', content) # 移除斜体标记
|
||
|
||
return content.strip()
|
||
|
||
def _call_xhs_cli(self, title: str, content: str, images: List[str]) -> bool:
|
||
"""
|
||
调用小红书CLI发布内容
|
||
|
||
Args:
|
||
title: 标题
|
||
content: 内容
|
||
images: 图片路径列表
|
||
|
||
Returns:
|
||
是否成功
|
||
"""
|
||
try:
|
||
# 构建命令
|
||
cli_path = self.config["xiaohongshu"]["cli_path"]
|
||
|
||
# 创建临时文件存储内容
|
||
import tempfile
|
||
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:
|
||
f.write(content)
|
||
content_file = f.name
|
||
|
||
# 构建命令参数
|
||
cmd = [cli_path, "post"]
|
||
|
||
# 添加标题
|
||
if title:
|
||
cmd.extend(["--title", title])
|
||
|
||
# 添加内容文件
|
||
cmd.extend(["--content-file", content_file])
|
||
|
||
# 添加图片
|
||
for image in images:
|
||
if os.path.exists(image):
|
||
cmd.extend(["--image", image])
|
||
|
||
# 添加标签
|
||
for tag in self.config["xiaohongshu"]["default_tags"]:
|
||
cmd.extend(["--tag", tag])
|
||
|
||
logger.info(f"执行命令: {' '.join(cmd)}")
|
||
|
||
# 执行命令
|
||
result = subprocess.run(
|
||
cmd,
|
||
capture_output=True,
|
||
text=True,
|
||
encoding='utf-8',
|
||
timeout=self.config["image_generation"]["timeout"]
|
||
)
|
||
|
||
# 清理临时文件
|
||
try:
|
||
os.unlink(content_file)
|
||
except:
|
||
pass
|
||
|
||
if result.returncode == 0:
|
||
logger.info("✅ 小红书发布成功")
|
||
logger.info(f"输出: {result.stdout}")
|
||
return True
|
||
else:
|
||
logger.error(f"❌ 小红书发布失败")
|
||
logger.error(f"错误: {result.stderr}")
|
||
return False
|
||
|
||
except subprocess.TimeoutExpired:
|
||
logger.error("❌ 发布超时")
|
||
return False
|
||
except Exception as e:
|
||
logger.error(f"❌ 调用小红书CLI失败: {e}")
|
||
return False
|
||
|
||
def test_publish(self) -> bool:
|
||
"""测试发布功能"""
|
||
logger.info("开始测试增强版发布功能...")
|
||
|
||
# 创建测试内容
|
||
test_content = """# AI技术新突破:文本生成图片质量大幅提升
|
||
|
||
最近,AI图像生成技术取得了重大突破。新的模型能够生成更加逼真、细节丰富的图片,同时保持高度的创意性。
|
||
|
||
## 主要改进
|
||
|
||
1. **图像质量提升**
|
||
- 分辨率从512×512提升到1024×1024
|
||
- 细节更加丰富,纹理更加真实
|
||
- 色彩更加鲜艳自然
|
||
|
||
2. **创意控制增强**
|
||
- 支持更复杂的提示词
|
||
- 可以指定艺术风格和构图
|
||
- 支持多图生成和一致性保持
|
||
|
||
3. **生成速度优化**
|
||
- 推理时间减少30%
|
||
- 支持批量生成
|
||
- 内存占用优化
|
||
|
||
这项技术将改变内容创作的方式,让每个人都能轻松生成高质量的视觉内容。
|
||
"""
|
||
|
||
# 保存测试文件
|
||
test_file = "/tmp/test_enhanced_article.md"
|
||
with open(test_file, 'w', encoding='utf-8') as f:
|
||
f.write(test_content)
|
||
|
||
logger.info(f"创建测试文件: {test_file}")
|
||
|
||
# 测试图片生成
|
||
logger.info("测试图片生成功能...")
|
||
images = self.generate_images_for_content(test_content, "notion", "dense")
|
||
|
||
if images:
|
||
logger.info(f"✅ 图片生成成功: {images}")
|
||
else:
|
||
logger.warning("⚠️ 图片生成失败或已禁用")
|
||
|
||
# 测试发布
|
||
logger.info("测试发布功能...")
|
||
success = self.publish_with_generated_images(test_file, "notion", "dense")
|
||
|
||
if success:
|
||
logger.info("✅ 测试发布成功")
|
||
else:
|
||
logger.error("❌ 测试发布失败")
|
||
|
||
# 清理测试文件
|
||
try:
|
||
os.remove(test_file)
|
||
logger.info(f"清理测试文件: {test_file}")
|
||
except:
|
||
pass
|
||
|
||
return success
|
||
|
||
def batch_process_directory(self, directory: str, style: str = None, layout: str = None) -> Dict[str, bool]:
|
||
"""
|
||
批量处理目录中的Markdown文件
|
||
|
||
Args:
|
||
directory: 目录路径
|
||
style: 图片风格(可选)
|
||
layout: 图片布局(可选)
|
||
|
||
Returns:
|
||
处理结果字典 {文件名: 是否成功}
|
||
"""
|
||
results = {}
|
||
|
||
if not os.path.isdir(directory):
|
||
logger.error(f"目录不存在: {directory}")
|
||
return results
|
||
|
||
# 查找所有Markdown文件
|
||
md_files = []
|
||
for root, dirs, files in os.walk(directory):
|
||
for file in files:
|
||
if file.lower().endswith('.md'):
|
||
md_files.append(os.path.join(root, file))
|
||
|
||
logger.info(f"找到 {len(md_files)} 个Markdown文件")
|
||
|
||
# 逐个处理
|
||
for i, md_file in enumerate(md_files, 1):
|
||
logger.info(f"处理文件 {i}/{len(md_files)}: {md_file}")
|
||
|
||
try:
|
||
success = self.publish_with_generated_images(md_file, style, layout)
|
||
results[md_file] = success
|
||
|
||
if success:
|
||
logger.info(f"✅ 文件处理成功: {md_file}")
|
||
else:
|
||
logger.error(f"❌ 文件处理失败: {md_file}")
|
||
|
||
# 避免发布频率过高
|
||
if i < len(md_files):
|
||
interval = self.config["xiaohongshu"]["publish_interval"]
|
||
logger.info(f"等待 {interval} 秒后处理下一个文件...")
|
||
time.sleep(interval)
|
||
|
||
except Exception as e:
|
||
logger.error(f"处理文件时发生错误: {e}")
|
||
results[md_file] = False
|
||
|
||
return results
|
||
|
||
|
||
def main():
|
||
"""主函数"""
|
||
parser = argparse.ArgumentParser(description='小红书增强版发布器 - 集成图片风格生成')
|
||
subparsers = parser.add_subparsers(dest='command', help='命令')
|
||
|
||
# publish命令
|
||
publish_parser = subparsers.add_parser('publish', help='发布文章')
|
||
publish_parser.add_argument('--markdown', type=str, required=True, help='Markdown文件路径')
|
||
publish_parser.add_argument('--style', type=str, help='图片风格 (cute, fresh, notion, minimal等)')
|
||
publish_parser.add_argument('--layout', type=str, help='图片布局 (sparse, balanced, dense等)')
|
||
publish_parser.add_argument('--config', type=str, help='配置文件路径')
|
||
|
||
# batch命令
|
||
batch_parser = subparsers.add_parser('batch', help='批量处理目录')
|
||
batch_parser.add_argument('--directory', type=str, required=True, help='目录路径')
|
||
batch_parser.add_argument('--style', type=str, help='图片风格')
|
||
batch_parser.add_argument('--layout', type=str, help='图片布局')
|
||
batch_parser.add_argument('--config', type=str, help='配置文件路径')
|
||
|
||
# analyze命令
|
||
analyze_parser = subparsers.add_parser('analyze', help='分析内容')
|
||
analyze_parser.add_argument('--content', type=str, required=True, help='内容文本')
|
||
analyze_parser.add_argument('--file', type=str, help='文件路径(替代--content)')
|
||
|
||
# generate命令
|
||
generate_parser = subparsers.add_parser('generate', help='生成图片')
|
||
generate_parser.add_argument('--content', type=str, required=True, help='内容文本')
|
||
generate_parser.add_argument('--style', type=str, help='图片风格')
|
||
generate_parser.add_argument('--layout', type=str, help='图片布局')
|
||
generate_parser.add_argument('--output', type=str, help='输出文件路径')
|
||
generate_parser.add_argument('--config', type=str, help='配置文件路径')
|
||
|
||
# test命令
|
||
subparsers.add_parser('test', help='测试发布功能')
|
||
|
||
# config命令
|
||
config_parser = subparsers.add_parser('config', help='查看配置')
|
||
config_parser.add_argument('--show', action='store_true', help='显示完整配置')
|
||
|
||
args = parser.parse_args()
|
||
|
||
# 配置日志
|
||
logging.basicConfig(
|
||
level=logging.INFO,
|
||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||
)
|
||
|
||
# 创建发布器
|
||
publisher = XiaohongshuEnhancedPublisher(args.config if hasattr(args, 'config') else None)
|
||
|
||
if args.command == 'publish':
|
||
success = publisher.publish_with_generated_images(
|
||
args.markdown,
|
||
args.style,
|
||
args.layout
|
||
)
|
||
sys.exit(0 if success else 1)
|
||
|
||
elif args.command == 'batch':
|
||
results = publisher.batch_process_directory(
|
||
args.directory,
|
||
args.style,
|
||
args.layout
|
||
)
|
||
|
||
# 输出结果统计
|
||
total = len(results)
|
||
success_count = sum(1 for r in results.values() if r)
|
||
failure_count = total - success_count
|
||
|
||
print(f"\n批量处理完成:")
|
||
print(f" 总计: {total} 个文件")
|
||
print(f" 成功: {success_count} 个")
|
||
print(f" 失败: {failure_count} 个")
|
||
|
||
if failure_count > 0:
|
||
print(f"\n失败的文件:")
|
||
for file, success in results.items():
|
||
if not success:
|
||
print(f" - {file}")
|
||
|
||
sys.exit(0 if failure_count == 0 else 1)
|
||
|
||
elif args.command == 'analyze':
|
||
content = args.content
|
||
if args.file:
|
||
with open(args.file, 'r', encoding='utf-8') as f:
|
||
content = f.read()
|
||
|
||
analysis = publisher.analyze_content(content)
|
||
|
||
print(f"内容分析结果:")
|
||
print(f" 内容类型: {analysis['content_type']}")
|
||
print(f" 推荐风格: {analysis['recommended_style'].value}")
|
||
print(f" 推荐布局: {analysis['recommended_layout'].value}")
|
||
print(f" 建议图片数: {analysis['image_count']}")
|
||
|
||
if 'key_points' in analysis:
|
||
print(f" 关键点: {analysis['key_points']}")
|
||
|
||
elif args.command == 'generate':
|
||
images = publisher.generate_images_for_content(
|
||
args.content,
|
||
args.style,
|
||
args.layout
|
||
)
|
||
|
||
if images:
|
||
print(f"✅ 图片生成成功:")
|
||
for img in images:
|
||
print(f" - {img}")
|
||
else:
|
||
print("❌ 图片生成失败")
|
||
sys.exit(1)
|
||
|
||
elif args.command == 'test':
|
||
success = publisher.test_publish()
|
||
sys.exit(0 if success else 1)
|
||
|
||
elif args.command == 'config':
|
||
if args.show:
|
||
print(json.dumps(publisher.config, ensure_ascii=False, indent=2))
|
||
else:
|
||
print("当前配置摘要:")
|
||
print(f" 小红书CLI路径: {publisher.config['xiaohongshu']['cli_path']}")
|
||
print(f" 自动生成图片: {publisher.config['xiaohongshu']['auto_generate_images']}")
|
||
print(f" 默认风格: {publisher.config['xiaohongshu']['default_style']}")
|
||
print(f" 默认布局: {publisher.config['xiaohongshu']['default_layout']}")
|
||
print(f" API密钥配置: {'已配置' if publisher.config['image_generation']['api_key'] else '未配置'}")
|
||
|
||
else:
|
||
parser.print_help()
|
||
sys.exit(1)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |