Initial commit
This commit is contained in:
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
EPUB双语翻译程序 - 保守修复验证脚本
|
||||
验证修复后的系统是否能正确处理EPUB构建
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# 添加项目根目录到 Python 路径
|
||||
project_root = Path(__file__).parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
from src.epub_parser import EPUBParser
|
||||
from src.translator import EPUBTranslator
|
||||
from src.utils import load_config
|
||||
from loguru import logger
|
||||
|
||||
|
||||
async def test_conservative_fix():
|
||||
"""测试保守修复方案"""
|
||||
|
||||
print("🔧 开始验证保守修复方案...")
|
||||
|
||||
try:
|
||||
# 加载配置
|
||||
config = load_config()
|
||||
|
||||
# 查找测试用的EPUB文件
|
||||
test_files = list(Path(".").glob("*.epub"))
|
||||
if not test_files:
|
||||
print("❌ 未找到测试用的EPUB文件")
|
||||
return
|
||||
|
||||
test_epub = test_files[0]
|
||||
print(f"📚 使用测试文件: {test_epub}")
|
||||
|
||||
# 初始化翻译器
|
||||
translator = EPUBTranslator(config)
|
||||
|
||||
# 测试解析
|
||||
print("\n📖 测试EPUB解析...")
|
||||
parser = EPUBParser(str(test_epub))
|
||||
content_items = parser.extract_translatable_content()
|
||||
|
||||
print(f"✅ 成功解析,找到 {len(content_items)} 个内容项目")
|
||||
for i, item in enumerate(content_items[:3], 1): # 只显示前3个
|
||||
print(f" {i}. {item['title']} ({item['type']})")
|
||||
|
||||
# 检查数据类型
|
||||
print("\n🔍 检查数据类型...")
|
||||
for i, item in enumerate(content_items[:2], 1):
|
||||
original_item = item['item']
|
||||
print(f" 项目 {i}: {type(original_item)} - {original_item.__class__.__name__}")
|
||||
|
||||
# 检查是否有get_content方法
|
||||
if hasattr(original_item, 'get_content'):
|
||||
print(f" ✅ 有 get_content 方法")
|
||||
else:
|
||||
print(f" ❌ 没有 get_content 方法")
|
||||
|
||||
# 检查是否有get_name方法
|
||||
if hasattr(original_item, 'get_name'):
|
||||
print(f" ✅ 有 get_name 方法: {original_item.get_name()}")
|
||||
else:
|
||||
print(f" ❌ 没有 get_name 方法")
|
||||
|
||||
# 测试翻译(只翻译第一个项目)
|
||||
print("\n🚀 测试单个项目翻译...")
|
||||
if content_items:
|
||||
test_item = content_items[0]
|
||||
|
||||
# 模拟翻译结果
|
||||
mock_translations = [
|
||||
"这是第一段的模拟翻译。",
|
||||
"这是第二段的模拟翻译。",
|
||||
"这是第三段的模拟翻译。"
|
||||
]
|
||||
|
||||
# 构造翻译数据
|
||||
translated_content = [{
|
||||
'original_item': test_item['item'],
|
||||
'translations': mock_translations,
|
||||
'title': test_item['title'],
|
||||
'type': test_item['type'],
|
||||
'stats': {
|
||||
'total_paragraphs': len(mock_translations),
|
||||
'total_chunks': 1,
|
||||
'cache_hits': 0,
|
||||
'failed_translations': 0
|
||||
}
|
||||
}]
|
||||
|
||||
# 测试双语EPUB构建
|
||||
print("\n📖 测试双语EPUB构建...")
|
||||
from src.bilingual_builder import BilingualEPUBBuilder
|
||||
|
||||
builder = BilingualEPUBBuilder(parser.book, config)
|
||||
|
||||
# 创建测试输出目录
|
||||
test_output_dir = Path("test_output")
|
||||
test_output_dir.mkdir(exist_ok=True)
|
||||
|
||||
try:
|
||||
result_file = builder.create_bilingual_epub(translated_content, str(test_output_dir))
|
||||
print(f"✅ 双语EPUB构建成功: {result_file}")
|
||||
|
||||
# 验证文件是否存在
|
||||
if Path(result_file).exists():
|
||||
file_size = Path(result_file).stat().st_size
|
||||
print(f" 文件大小: {file_size / 1024:.1f} KB")
|
||||
else:
|
||||
print("❌ 输出文件不存在")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 双语EPUB构建失败: {e}")
|
||||
logger.error(f"构建失败详情: {e}")
|
||||
|
||||
print("\n🎉 保守修复验证完成!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 验证过程出错: {e}")
|
||||
logger.error(f"验证失败: {e}")
|
||||
|
||||
|
||||
async def test_full_translation_flow():
|
||||
"""测试完整翻译流程(小规模)"""
|
||||
|
||||
print("\n🧪 测试完整翻译流程...")
|
||||
|
||||
try:
|
||||
# 查找测试用的EPUB文件
|
||||
test_files = list(Path(".").glob("*.epub"))
|
||||
if not test_files:
|
||||
print("❌ 未找到测试用的EPUB文件")
|
||||
return
|
||||
|
||||
test_epub = test_files[0]
|
||||
config = load_config()
|
||||
|
||||
# 修改配置以进行小规模测试
|
||||
config['translation']['chunk_size'] = 1000 # 更小的chunk
|
||||
config['translation']['concurrent_requests'] = 2 # 更少的并发
|
||||
|
||||
# 初始化翻译器
|
||||
translator = EPUBTranslator(config)
|
||||
|
||||
print(f"📚 开始测试翻译: {test_epub}")
|
||||
|
||||
# 运行测试模式
|
||||
result = await translator.translate_epub(str(test_epub), test_mode=True)
|
||||
|
||||
if result.get('status') == 'success':
|
||||
print("✅ 测试模式成功完成")
|
||||
|
||||
# 显示测试结果
|
||||
preface_result = result.get('preface', {})
|
||||
chapter_result = result.get('chapter', {})
|
||||
|
||||
if preface_result.get('status') == 'success':
|
||||
print(f" 序言翻译: ✅ (长度: {preface_result.get('translation_length', 0)})")
|
||||
|
||||
if chapter_result.get('status') == 'success':
|
||||
print(f" 章节翻译: ✅ (段落数: {chapter_result.get('paragraph_count', 0)})")
|
||||
else:
|
||||
print(f"❌ 测试模式失败: {result.get('error', '未知错误')}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 完整流程测试失败: {e}")
|
||||
logger.error(f"完整流程测试失败: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 配置日志
|
||||
logger.remove()
|
||||
logger.add(sys.stdout, level="INFO", format="<green>{time:HH:mm:ss}</green> | <level>{level}</level> | {message}")
|
||||
|
||||
print("🔧 EPUB翻译器 - 保守修复验证")
|
||||
print("=" * 50)
|
||||
|
||||
# 运行保守修复测试
|
||||
asyncio.run(test_conservative_fix())
|
||||
|
||||
# 运行完整流程测试
|
||||
asyncio.run(test_full_translation_flow())
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("🎯 修复总结:")
|
||||
print("1. ✅ 采用保守的EPUB构建策略")
|
||||
print("2. ✅ 深度复制原书结构,最大程度保持完整性")
|
||||
print("3. ✅ 修复了数据传递中的字段名错误")
|
||||
print("4. ✅ 增强了错误处理和类型检查")
|
||||
print("5. ✅ 保守地插入翻译,避免破坏原有格式")
|
||||
print("\n🚀 保守修复验证完成!")
|
||||
Reference in New Issue
Block a user