506 lines
16 KiB
Python
506 lines
16 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
小红书图片风格生成功能集成示例
|
|
展示如何将新功能集成到现有工作流中
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import json
|
|
import logging
|
|
from pathlib import Path
|
|
from datetime import datetime
|
|
|
|
# 添加当前目录到Python路径
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
# 配置日志
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def example_1_basic_integration():
|
|
"""示例1: 基本集成 - 在现有发布流程中添加图片生成"""
|
|
print("=" * 60)
|
|
print("示例1: 基本集成 - 在现有发布流程中添加图片生成")
|
|
print("=" * 60)
|
|
|
|
try:
|
|
# 导入现有发布器
|
|
from xiaohongshu_publisher_fixed import XiaohongshuPublisherFixed
|
|
from xiaohongshu_enhanced_publisher import XiaohongshuEnhancedPublisher
|
|
|
|
# 创建现有发布器
|
|
existing_publisher = XiaohongshuPublisherFixed()
|
|
logger.info("现有发布器创建成功")
|
|
|
|
# 创建增强发布器
|
|
enhanced_publisher = XiaohongshuEnhancedPublisher()
|
|
logger.info("增强发布器创建成功")
|
|
|
|
# 示例内容
|
|
content = """# 高效学习法分享
|
|
|
|
掌握高效学习法,让学习事半功倍!
|
|
|
|
## 核心方法
|
|
|
|
1. **番茄工作法**
|
|
- 25分钟专注学习
|
|
- 5分钟短暂休息
|
|
- 每4个番茄钟长休息
|
|
|
|
2. **费曼学习法**
|
|
- 选择一个概念
|
|
- 教授给他人
|
|
- 回顾和简化
|
|
- 组织和完善
|
|
|
|
3. **间隔重复法**
|
|
- 第一天学习
|
|
- 第二天复习
|
|
- 一周后复习
|
|
- 一月后复习
|
|
|
|
坚持使用这些方法,学习效率提升300%!
|
|
"""
|
|
|
|
# 保存为临时文件
|
|
import tempfile
|
|
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
|
|
f.write(content)
|
|
temp_file = f.name
|
|
|
|
logger.info(f"创建临时文件: {temp_file}")
|
|
|
|
# 方法A: 使用现有发布器(无图片生成)
|
|
logger.info("\n方法A: 使用现有发布器(无图片生成)")
|
|
# success_a = existing_publisher.publish_from_markdown(temp_file)
|
|
# logger.info(f"现有发布器结果: {'成功' if success_a else '失败'}")
|
|
|
|
# 方法B: 使用增强发布器(带图片生成)
|
|
logger.info("\n方法B: 使用增强发布器(带图片生成)")
|
|
|
|
# 先分析内容
|
|
analysis = enhanced_publisher.analyze_content(content)
|
|
logger.info(f"内容分析结果:")
|
|
logger.info(f" 类型: {analysis['content_type']}")
|
|
logger.info(f" 推荐风格: {analysis['recommended_style'].value}")
|
|
logger.info(f" 推荐布局: {analysis['recommended_layout'].value}")
|
|
|
|
# 生成图片
|
|
images = enhanced_publisher.generate_images_for_content(
|
|
content,
|
|
analysis['recommended_style'].value,
|
|
analysis['recommended_layout'].value
|
|
)
|
|
|
|
if images:
|
|
logger.info(f"✅ 图片生成成功: {images[0]}")
|
|
else:
|
|
logger.info("⚠️ 图片生成失败或已禁用")
|
|
|
|
# 发布(需要配置API密钥和登录状态)
|
|
# success_b = enhanced_publisher.publish_with_generated_images(temp_file)
|
|
# logger.info(f"增强发布器结果: {'成功' if success_b else '失败'}")
|
|
|
|
# 清理临时文件
|
|
os.unlink(temp_file)
|
|
logger.info(f"清理临时文件: {temp_file}")
|
|
|
|
print("\n✅ 示例1完成")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"示例1失败: {e}")
|
|
return False
|
|
|
|
def example_2_style_selection():
|
|
"""示例2: 风格选择 - 根据内容类型选择最佳风格"""
|
|
print("\n" + "=" * 60)
|
|
print("示例2: 风格选择 - 根据内容类型选择最佳风格")
|
|
print("=" * 60)
|
|
|
|
try:
|
|
from xiaohongshu_enhanced_publisher import XiaohongshuEnhancedPublisher
|
|
|
|
publisher = XiaohongshuEnhancedPublisher()
|
|
|
|
# 不同类型的内容示例
|
|
content_examples = [
|
|
{
|
|
"type": "知识分享",
|
|
"content": "Python编程技巧:列表推导式、装饰器、上下文管理器",
|
|
"expected_style": "notion"
|
|
},
|
|
{
|
|
"type": "生活分享",
|
|
"content": "周末好去处:公园野餐、咖啡馆读书、美术馆看展",
|
|
"expected_style": "cute"
|
|
},
|
|
{
|
|
"type": "健康生活",
|
|
"content": "每日养生习惯:早起一杯水、午间小憩、晚上泡脚",
|
|
"expected_style": "fresh"
|
|
},
|
|
{
|
|
"type": "专业教程",
|
|
"content": "Git使用指南:分支管理、合并冲突、版本回退",
|
|
"expected_style": "minimal"
|
|
}
|
|
]
|
|
|
|
for example in content_examples:
|
|
print(f"\n内容类型: {example['type']}")
|
|
print(f"内容: {example['content'][:50]}...")
|
|
|
|
# 分析内容
|
|
analysis = publisher.analyze_content(example['content'])
|
|
|
|
print(f" 分析结果: {analysis['content_type']}")
|
|
print(f" 推荐风格: {analysis['recommended_style'].value}")
|
|
print(f" 推荐布局: {analysis['recommended_layout'].value}")
|
|
|
|
# 检查是否符合预期
|
|
if analysis['recommended_style'].value == example['expected_style']:
|
|
print(f" ✅ 风格推荐符合预期")
|
|
else:
|
|
print(f" ⚠️ 风格推荐与预期不同")
|
|
|
|
print("\n✅ 示例2完成")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"示例2失败: {e}")
|
|
return False
|
|
|
|
def example_3_batch_processing():
|
|
"""示例3: 批量处理 - 处理多个Markdown文件"""
|
|
print("\n" + "=" * 60)
|
|
print("示例3: 批量处理 - 处理多个Markdown文件")
|
|
print("=" * 60)
|
|
|
|
try:
|
|
from xiaohongshu_enhanced_publisher import XiaohongshuEnhancedPublisher
|
|
|
|
publisher = XiaohongshuEnhancedPublisher()
|
|
|
|
# 创建测试目录和文件
|
|
test_dir = Path("/tmp/xhs_test_batch")
|
|
test_dir.mkdir(exist_ok=True)
|
|
|
|
# 创建多个测试文件
|
|
test_files = [
|
|
{
|
|
"name": "学习技巧.md",
|
|
"content": """# 高效学习技巧
|
|
|
|
1. 主动学习
|
|
2. 间隔重复
|
|
3. 费曼技巧
|
|
4. 思维导图"""
|
|
},
|
|
{
|
|
"name": "健康生活.md",
|
|
"content": """# 健康生活习惯
|
|
|
|
- 规律作息
|
|
- 均衡饮食
|
|
- 适量运动
|
|
- 良好心态"""
|
|
},
|
|
{
|
|
"name": "时间管理.md",
|
|
"content": """# 时间管理方法
|
|
|
|
## 重要工具
|
|
1. 番茄钟
|
|
2. 待办清单
|
|
3. 日历规划
|
|
4. 优先级矩阵"""
|
|
}
|
|
]
|
|
|
|
# 保存文件
|
|
file_paths = []
|
|
for test_file in test_files:
|
|
file_path = test_dir / test_file["name"]
|
|
with open(file_path, 'w', encoding='utf-8') as f:
|
|
f.write(test_file["content"])
|
|
file_paths.append(str(file_path))
|
|
print(f"创建文件: {file_path}")
|
|
|
|
# 模拟批量处理(不实际发布)
|
|
print(f"\n模拟批量处理 {len(file_paths)} 个文件...")
|
|
|
|
for i, file_path in enumerate(file_paths, 1):
|
|
print(f"\n处理文件 {i}/{len(file_paths)}: {file_path}")
|
|
|
|
# 读取内容
|
|
with open(file_path, 'r', encoding='utf-8') as f:
|
|
content = f.read()
|
|
|
|
# 分析内容
|
|
analysis = publisher.analyze_content(content)
|
|
|
|
print(f" 内容类型: {analysis['content_type']}")
|
|
print(f" 推荐风格: {analysis['recommended_style'].value}")
|
|
print(f" 推荐布局: {analysis['recommended_layout'].value}")
|
|
|
|
# 模拟图片生成
|
|
images = publisher.generate_images_for_content(
|
|
content,
|
|
analysis['recommended_style'].value,
|
|
analysis['recommended_layout'].value
|
|
)
|
|
|
|
if images:
|
|
print(f" ✅ 图片生成成功")
|
|
else:
|
|
print(f" ⚠️ 图片生成失败或已禁用")
|
|
|
|
# 清理测试文件
|
|
for file_path in file_paths:
|
|
try:
|
|
os.unlink(file_path)
|
|
except:
|
|
pass
|
|
|
|
# 清理目录
|
|
try:
|
|
test_dir.rmdir()
|
|
except:
|
|
pass
|
|
|
|
print("\n✅ 示例3完成")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"示例3失败: {e}")
|
|
return False
|
|
|
|
def example_4_custom_workflow():
|
|
"""示例4: 自定义工作流 - 结合现有工具创建完整流程"""
|
|
print("\n" + "=" * 60)
|
|
print("示例4: 自定义工作流 - 结合现有工具创建完整流程")
|
|
print("=" * 60)
|
|
|
|
try:
|
|
# 导入各种工具
|
|
from xiaohongshu_enhanced_publisher import XiaohongshuEnhancedPublisher
|
|
from content_converter_fixed import ContentConverterFixed
|
|
|
|
# 初始化工具
|
|
publisher = XiaohongshuEnhancedPublisher()
|
|
converter = ContentConverterFixed()
|
|
|
|
# 模拟从IT资讯系统获取内容
|
|
print("步骤1: 获取内容")
|
|
it_article = {
|
|
"title": "AI技术新突破:文本生成图片质量大幅提升",
|
|
"content": """最近,AI图像生成技术取得了重大突破。新的模型能够生成更加逼真、细节丰富的图片,同时保持高度的创意性。
|
|
|
|
主要改进包括:
|
|
1. 图像质量大幅提升
|
|
2. 创意控制更加精细
|
|
3. 生成速度显著优化
|
|
|
|
这项技术将改变内容创作的方式。""",
|
|
"source": "TechNews",
|
|
"url": "https://example.com/ai-breakthrough"
|
|
}
|
|
|
|
print(f" 标题: {it_article['title']}")
|
|
print(f" 来源: {it_article['source']}")
|
|
|
|
# 步骤2: 转换为小红书格式
|
|
print("\n步骤2: 转换为小红书格式")
|
|
|
|
# 创建Markdown格式
|
|
markdown_content = f"""# {it_article['title']}
|
|
|
|
{it_article['content']}
|
|
|
|
*来源: {it_article['source']}*
|
|
*原文链接: {it_article['url']}*
|
|
"""
|
|
|
|
# 转换为小红书格式
|
|
xhs_content = converter.convert(markdown_content)
|
|
print(f" 转换后内容长度: {len(xhs_content)} 字符")
|
|
print(f" 内容预览: {xhs_content[:100]}...")
|
|
|
|
# 步骤3: 分析内容并生成图片
|
|
print("\n步骤3: 分析内容并生成图片")
|
|
|
|
analysis = publisher.analyze_content(it_article['content'])
|
|
print(f" 内容类型: {analysis['content_type']}")
|
|
print(f" 推荐风格: {analysis['recommended_style'].value}")
|
|
print(f" 推荐布局: {analysis['recommended_layout'].value}")
|
|
|
|
# 生成图片
|
|
images = publisher.generate_images_for_content(
|
|
it_article['content'],
|
|
analysis['recommended_style'].value,
|
|
analysis['recommended_layout'].value
|
|
)
|
|
|
|
if images:
|
|
print(f" ✅ 图片生成成功: {images[0]}")
|
|
else:
|
|
print(f" ⚠️ 图片生成失败或已禁用")
|
|
|
|
# 步骤4: 准备发布
|
|
print("\n步骤4: 准备发布")
|
|
|
|
# 保存为临时文件
|
|
import tempfile
|
|
with tempfile.NamedTemporaryFile(mode='w', suffix='.md', delete=False, encoding='utf-8') as f:
|
|
f.write(markdown_content)
|
|
temp_file = f.name
|
|
|
|
print(f" 临时文件: {temp_file}")
|
|
|
|
# 步骤5: 发布(模拟)
|
|
print("\n步骤5: 发布到小红书")
|
|
print(" 📝 标题:", it_article['title'])
|
|
print(" 🎨 图片风格:", analysis['recommended_style'].value)
|
|
print(" 📐 图片布局:", analysis['recommended_layout'].value)
|
|
print(" 🏷️ 默认标签:", publisher.config['xiaohongshu']['default_tags'][:3])
|
|
|
|
# 清理临时文件
|
|
os.unlink(temp_file)
|
|
|
|
print("\n✅ 完整工作流演示完成")
|
|
print("\n实际发布命令:")
|
|
print(f" python3 xiaohongshu_enhanced_publisher.py publish --markdown {temp_file}")
|
|
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"示例4失败: {e}")
|
|
return False
|
|
|
|
def example_5_integration_with_xhs_cli():
|
|
"""示例5: 与小红书CLI集成"""
|
|
print("\n" + "=" * 60)
|
|
print("示例5: 与小红书CLI集成")
|
|
print("=" * 60)
|
|
|
|
try:
|
|
import subprocess
|
|
|
|
# 检查小红书CLI状态
|
|
print("检查小红书CLI状态...")
|
|
|
|
try:
|
|
result = subprocess.run(
|
|
["xhs", "status"],
|
|
capture_output=True,
|
|
text=True,
|
|
encoding='utf-8',
|
|
timeout=10
|
|
)
|
|
|
|
if result.returncode == 0:
|
|
print("✅ 小红书CLI可用")
|
|
print(f"输出: {result.stdout[:100]}...")
|
|
else:
|
|
print("⚠️ 小红书CLI状态检查失败")
|
|
print(f"错误: {result.stderr}")
|
|
except FileNotFoundError:
|
|
print("❌ 小红书CLI未安装")
|
|
print("安装命令: uv tool install xiaohongshu-cli")
|
|
except subprocess.TimeoutExpired:
|
|
print("⚠️ 小红书CLI检查超时")
|
|
|
|
# 演示发布命令
|
|
print("\n小红书发布命令示例:")
|
|
|
|
commands = [
|
|
"# 基本发布",
|
|
"xhs post --title '高效学习法' --content '分享几个高效学习技巧...' --image generated.png",
|
|
"",
|
|
"# 添加标签",
|
|
"xhs post --title 'AI技术' --content 'AI最新进展...' --tag '#AI' --tag '#科技'",
|
|
"",
|
|
"# 从文件读取内容",
|
|
"xhs post --title '我的笔记' --content-file content.txt --image image1.jpg --image image2.jpg",
|
|
"",
|
|
"# 查看已发布的笔记",
|
|
"xhs my-notes --page 0",
|
|
"",
|
|
"# 搜索内容",
|
|
"xhs search '学习技巧' --sort popular"
|
|
]
|
|
|
|
for cmd in commands:
|
|
if cmd.startswith("#"):
|
|
print(f"\n{cmd}")
|
|
elif cmd:
|
|
print(f" {cmd}")
|
|
|
|
print("\n✅ 示例5完成")
|
|
return True
|
|
|
|
except Exception as e:
|
|
logger.error(f"示例5失败: {e}")
|
|
return False
|
|
|
|
def main():
|
|
"""主函数"""
|
|
print("小红书图片风格生成功能集成示例")
|
|
print("=" * 60)
|
|
|
|
examples = [
|
|
("基本集成", example_1_basic_integration),
|
|
("风格选择", example_2_style_selection),
|
|
("批量处理", example_3_batch_processing),
|
|
("自定义工作流", example_4_custom_workflow),
|
|
("与小红书CLI集成", example_5_integration_with_xhs_cli)
|
|
]
|
|
|
|
results = []
|
|
|
|
for name, func in examples:
|
|
try:
|
|
success = func()
|
|
results.append((name, success))
|
|
except Exception as e:
|
|
logger.error(f"示例 '{name}' 执行失败: {e}")
|
|
results.append((name, False))
|
|
|
|
# 输出结果
|
|
print("\n" + "=" * 60)
|
|
print("集成示例执行结果")
|
|
print("=" * 60)
|
|
|
|
total = len(results)
|
|
passed = sum(1 for _, success in results if success)
|
|
failed = total - passed
|
|
|
|
for name, success in results:
|
|
status = "✅ 通过" if success else "❌ 失败"
|
|
print(f"{name}: {status}")
|
|
|
|
print(f"\n总计: {total} 个示例")
|
|
print(f"通过: {passed} 个")
|
|
print(f"失败: {failed} 个")
|
|
|
|
if failed == 0:
|
|
print("\n🎉 所有集成示例执行成功!")
|
|
print("\n下一步建议:")
|
|
print("1. 配置API密钥以启用图片生成")
|
|
print("2. 登录小红书CLI以启用发布功能")
|
|
print("3. 测试完整发布流程")
|
|
print("4. 集成到现有自动化系统中")
|
|
else:
|
|
print(f"\n⚠️ 有 {failed} 个示例失败,请检查问题。")
|
|
|
|
return failed == 0
|
|
|
|
if __name__ == "__main__":
|
|
success = main()
|
|
sys.exit(0 if success else 1) |