Files
SillyTavern_replica/convert_worldbooks.py
2026-05-01 15:44:14 +08:00

88 lines
2.7 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.
"""
将现有的 SillyTavern 格式世界书转换为内部格式
"""
import json
from pathlib import Path
import sys
# 添加backend目录到Python路径
backend_dir = Path(__file__).parent / "backend"
sys.path.insert(0, str(backend_dir))
from models.converters import WorldBookConverter
WORLDBOOKS_PATH = Path(r'D:\progarm\python\llm_workflow_engine\data\worldbooks')
print("=" * 60)
print("世界书格式转换工具")
print("=" * 60)
# 查找所有JSON文件
json_files = list(WORLDBOOKS_PATH.glob("*.json"))
print(f"\n找到 {len(json_files)} 个世界书文件\n")
converted_count = 0
skipped_count = 0
error_count = 0
for file_path in json_files:
print(f"处理: {file_path.name}")
try:
# 读取文件
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# 检测格式
format_type = WorldBookConverter.detect_format(data)
print(f" 当前格式: {format_type}")
if format_type == "sillytavern":
# 需要转换
name = data.get("name", file_path.stem)
print(f" 世界书名称: {name}")
print(f" 条目数量: {len(data.get('entries', {}))}")
# 转换为内部格式
internal_data = WorldBookConverter.st_to_internal(data, name)
# 备份原文件
backup_path = file_path.with_suffix('.json.bak')
file_path.rename(backup_path)
print(f" ✓ 已备份原文件为: {backup_path.name}")
# 保存转换后的文件
with open(file_path, 'w', encoding='utf-8') as f:
json.dump(internal_data, f, ensure_ascii=False, indent=2)
print(f" ✓ 转换完成并保存")
print(f" - 新格式: internal")
print(f" - 条目数量: {len(internal_data.get('entries', []))}")
converted_count += 1
elif format_type == "internal":
print(f" 已是内部格式,跳过")
skipped_count += 1
else:
print(f" ⚠️ 未知格式,跳过")
skipped_count += 1
except Exception as e:
print(f" ❌ 错误: {e}")
import traceback
traceback.print_exc()
error_count += 1
print()
print("=" * 60)
print("转换完成统计:")
print(f" ✓ 转换成功: {converted_count} 个文件")
print(f" - 跳过(已是内部格式): {skipped_count} 个文件")
print(f" ✗ 转换失败: {error_count} 个文件")
print("=" * 60)
if converted_count > 0:
print("\n提示: 原文件已备份为 .bak 后缀,确认无误后可删除")