translate_epub_v4(单线程版本)V3.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. import os
  2. import re
  3. from bs4 import BeautifulSoup
  4. import openai
  5. import time
  6. from tqdm import tqdm
  7. import sqlite3
  8. import json
  9. from datetime import datetime
  10. import logging
  11. from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
  12. import asyncio
  13. import aiohttp
  14. from concurrent.futures import ThreadPoolExecutor
  15. from functools import lru_cache
  16. import hashlib
  17. import yaml
  18. from pathlib import Path
  19. # 配置管理
  20. class Config:
  21. def __init__(self, config_path='config.yaml'):
  22. self.config_path = config_path
  23. self.config = self.load_config()
  24. # 设置日志
  25. self.setup_logging()
  26. # 初始化OpenAI客户端
  27. self.setup_openai()
  28. def load_config(self):
  29. """加载配置文件"""
  30. if not os.path.exists(self.config_path):
  31. # 创建默认配置
  32. default_config = {
  33. 'logging': {
  34. 'level': 'INFO',
  35. 'format': '%(asctime)s - %(levelname)s - %(message)s',
  36. 'file': 'translation.log'
  37. },
  38. 'openai': {
  39. 'base_url': 'https://api.siliconflow.cn/v1',
  40. 'api_key': 'sk-',
  41. 'model_name': 'deepseek-ai/DeepSeek-R1',
  42. 'max_retries': 3,
  43. 'retry_delay': 2,
  44. 'timeout': 30,
  45. 'max_concurrent_requests': 5
  46. },
  47. 'translation': {
  48. 'min_line_count': 1,
  49. 'max_line_count': 5,
  50. 'initial_line_count': 2,
  51. 'error_threshold': 3,
  52. 'success_threshold': 5,
  53. 'error_cooldown': 60,
  54. 'cache_size': 1000
  55. },
  56. 'database': {
  57. 'path': 'translation_progress.db',
  58. 'pool_size': 5
  59. },
  60. 'paths': {
  61. 'input_dir': '002/Ops',
  62. 'output_dir': '002/Ops_translated'
  63. }
  64. }
  65. # 保存默认配置
  66. with open(self.config_path, 'w', encoding='utf-8') as f:
  67. yaml.dump(default_config, f, allow_unicode=True)
  68. return default_config
  69. # 加载现有配置
  70. with open(self.config_path, 'r', encoding='utf-8') as f:
  71. return yaml.safe_load(f)
  72. def setup_logging(self):
  73. """设置日志"""
  74. logging.basicConfig(
  75. level=getattr(logging, self.config['logging']['level']),
  76. format=self.config['logging']['format'],
  77. handlers=[
  78. logging.FileHandler(self.config['logging']['file']),
  79. logging.StreamHandler()
  80. ]
  81. )
  82. def setup_openai(self):
  83. """设置OpenAI客户端"""
  84. self.client = openai.OpenAI(
  85. base_url=self.config['openai']['base_url'],
  86. api_key=self.config['openai']['api_key']
  87. )
  88. def get(self, *keys):
  89. """获取配置值"""
  90. value = self.config
  91. for key in keys:
  92. value = value[key]
  93. return value
  94. def update(self, updates):
  95. """更新配置"""
  96. def deep_update(d, u):
  97. for k, v in u.items():
  98. if isinstance(v, dict):
  99. d[k] = deep_update(d.get(k, {}), v)
  100. else:
  101. d[k] = v
  102. return d
  103. self.config = deep_update(self.config, updates)
  104. # 保存更新后的配置
  105. with open(self.config_path, 'w', encoding='utf-8') as f:
  106. yaml.dump(self.config, f, allow_unicode=True)
  107. # 重新设置日志和OpenAI客户端
  108. self.setup_logging()
  109. self.setup_openai()
  110. # 创建全局的配置实例
  111. config = Config()
  112. # 更新全局变量
  113. MODEL_CONFIG = {
  114. "model_name": config.get('openai', 'model_name'),
  115. "max_retries": config.get('openai', 'max_retries'),
  116. "retry_delay": config.get('openai', 'retry_delay'),
  117. "timeout": config.get('openai', 'timeout'),
  118. "max_concurrent_requests": config.get('openai', 'max_concurrent_requests'),
  119. "cache_size": config.get('translation', 'cache_size')
  120. }
  121. MIN_LINE_COUNT = config.get('translation', 'min_line_count')
  122. MAX_LINE_COUNT = config.get('translation', 'max_line_count')
  123. INITIAL_LINE_COUNT = config.get('translation', 'initial_line_count')
  124. ERROR_THRESHOLD = config.get('translation', 'error_threshold')
  125. SUCCESS_THRESHOLD = config.get('translation', 'success_threshold')
  126. # 更新其他类的初始化参数
  127. class TranslationStats:
  128. def __init__(self):
  129. self.start_time = time.time()
  130. self.total_chars = 0
  131. self.translated_chars = 0
  132. self.total_requests = 0
  133. self.successful_requests = 0
  134. self.failed_requests = 0
  135. def update_stats(self, original_text, translated_text, success=True):
  136. self.total_chars += len(original_text)
  137. self.translated_chars += len(translated_text)
  138. self.total_requests += 1
  139. if success:
  140. self.successful_requests += 1
  141. else:
  142. self.failed_requests += 1
  143. def get_stats(self):
  144. elapsed_time = time.time() - self.start_time
  145. chars_per_second = self.translated_chars / elapsed_time if elapsed_time > 0 else 0
  146. success_rate = (self.successful_requests / self.total_requests * 100) if self.total_requests > 0 else 0
  147. return {
  148. "总字符数": self.total_chars,
  149. "已翻译字符数": self.translated_chars,
  150. "翻译速度": f"{chars_per_second:.2f} 字符/秒",
  151. "成功率": f"{success_rate:.1f}%",
  152. "总请求数": self.total_requests,
  153. "成功请求": self.successful_requests,
  154. "失败请求": self.failed_requests,
  155. "运行时间": f"{elapsed_time:.1f} 秒"
  156. }
  157. # 创建全局的统计对象
  158. translation_stats = TranslationStats()
  159. class DatabaseManager:
  160. def __init__(self):
  161. self.db_path = config.get('database', 'path')
  162. self.conn = None
  163. self.init_db()
  164. def get_connection(self):
  165. """获取数据库连接"""
  166. if self.conn is None:
  167. self.conn = sqlite3.connect(self.db_path)
  168. self.conn.row_factory = sqlite3.Row
  169. return self.conn
  170. def close(self):
  171. """关闭数据库连接"""
  172. if self.conn:
  173. self.conn.close()
  174. self.conn = None
  175. def init_db(self):
  176. """初始化数据库"""
  177. conn = self.get_connection()
  178. c = conn.cursor()
  179. # 创建文件进度表
  180. c.execute('''
  181. CREATE TABLE IF NOT EXISTS file_progress (
  182. file_path TEXT PRIMARY KEY,
  183. total_lines INTEGER,
  184. processed_lines INTEGER,
  185. status TEXT,
  186. last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  187. error_count INTEGER DEFAULT 0,
  188. retry_count INTEGER DEFAULT 0
  189. )
  190. ''')
  191. # 创建行进度表
  192. c.execute('''
  193. CREATE TABLE IF NOT EXISTS line_progress (
  194. id INTEGER PRIMARY KEY AUTOINCREMENT,
  195. file_path TEXT,
  196. line_index INTEGER,
  197. original_text TEXT,
  198. translated_text TEXT,
  199. status TEXT,
  200. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  201. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  202. error_count INTEGER DEFAULT 0,
  203. retry_count INTEGER DEFAULT 0,
  204. UNIQUE(file_path, line_index)
  205. )
  206. ''')
  207. # 创建错误日志表
  208. c.execute('''
  209. CREATE TABLE IF NOT EXISTS error_log (
  210. id INTEGER PRIMARY KEY AUTOINCREMENT,
  211. file_path TEXT,
  212. line_index INTEGER,
  213. error_type TEXT,
  214. error_message TEXT,
  215. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  216. resolved_at TIMESTAMP,
  217. resolution TEXT
  218. )
  219. ''')
  220. conn.commit()
  221. def begin_transaction(self):
  222. """开始事务"""
  223. self.get_connection().execute('BEGIN TRANSACTION')
  224. def commit_transaction(self):
  225. """提交事务"""
  226. self.get_connection().commit()
  227. def rollback_transaction(self):
  228. """回滚事务"""
  229. self.get_connection().rollback()
  230. def get_file_progress(self, file_path):
  231. """获取文件翻译进度"""
  232. c = self.get_connection().cursor()
  233. c.execute('SELECT * FROM file_progress WHERE file_path = ?', (file_path,))
  234. return c.fetchone()
  235. def update_file_progress(self, file_path, total_lines, processed_lines, status):
  236. """更新文件翻译进度"""
  237. c = self.get_connection().cursor()
  238. c.execute('''
  239. INSERT OR REPLACE INTO file_progress
  240. (file_path, total_lines, processed_lines, status, last_updated)
  241. VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
  242. ''', (file_path, total_lines, processed_lines, status))
  243. self.get_connection().commit()
  244. def get_line_progress(self, file_path, line_index):
  245. """获取行翻译进度"""
  246. c = self.get_connection().cursor()
  247. c.execute('''
  248. SELECT * FROM line_progress
  249. WHERE file_path = ? AND line_index = ?
  250. ''', (file_path, line_index))
  251. return c.fetchone()
  252. def update_line_progress(self, file_path, line_index, original_text, translated_text, status):
  253. """更新行翻译进度"""
  254. c = self.get_connection().cursor()
  255. c.execute('''
  256. INSERT OR REPLACE INTO line_progress
  257. (file_path, line_index, original_text, translated_text, status, updated_at)
  258. VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  259. ''', (file_path, line_index, original_text, translated_text, status))
  260. self.get_connection().commit()
  261. def log_error(self, file_path, line_index, error_type, error_message):
  262. """记录错误"""
  263. c = self.get_connection().cursor()
  264. c.execute('''
  265. INSERT INTO error_log
  266. (file_path, line_index, error_type, error_message)
  267. VALUES (?, ?, ?, ?)
  268. ''', (file_path, line_index, error_type, error_message))
  269. self.get_connection().commit()
  270. def get_error_stats(self):
  271. """获取错误统计信息"""
  272. c = self.get_connection().cursor()
  273. c.execute('''
  274. SELECT
  275. COUNT(*) as total_errors,
  276. COUNT(CASE WHEN resolved_at IS NULL THEN 1 END) as unresolved_errors,
  277. COUNT(CASE WHEN created_at > datetime('now', '-1 hour') THEN 1 END) as recent_errors
  278. FROM error_log
  279. ''')
  280. return c.fetchone()
  281. class AsyncTranslationManager:
  282. def __init__(self):
  283. self.semaphore = asyncio.Semaphore(config.get('openai', 'max_concurrent_requests'))
  284. self.session = None
  285. class TranslationCache:
  286. def __init__(self):
  287. self.cache = {}
  288. self.max_size = config.get('translation', 'cache_size')
  289. self.hits = 0
  290. self.misses = 0
  291. # 创建全局实例
  292. line_count_manager = TranslationStats()
  293. db_manager = DatabaseManager()
  294. async_translation_manager = AsyncTranslationManager()
  295. translation_cache = TranslationCache()
  296. # 添加版本控制
  297. VERSION = "1.0.1" # 版本号,用于区分不同版本的翻译
  298. line_count = 2 # 每组行数,越大越快,但越容易出错
  299. def get_completed_groups(conn, file_path):
  300. """获取已完成的翻译行"""
  301. c = conn.cursor()
  302. c.execute('''
  303. SELECT line_index, translated_text
  304. FROM line_progress
  305. WHERE file_path = ? AND status = 'completed'
  306. ORDER BY line_index
  307. ''', (file_path,))
  308. return c.fetchall()
  309. # """ - 输出内容要求用代码块包裹起来
  310. # ,只在必要时提供相应的语言注释
  311. # """
  312. @retry(
  313. stop=stop_after_attempt(MODEL_CONFIG['max_retries']),
  314. wait=wait_exponential(multiplier=1, min=4, max=10),
  315. retry=retry_if_exception_type((openai.APIError, openai.APITimeoutError)),
  316. before_sleep=lambda retry_state: logging.warning(f"重试第 {retry_state.attempt_number} 次...")
  317. )
  318. def translate_text(text):
  319. """翻译文本,使用流式输出"""
  320. try:
  321. messages = [
  322. {
  323. "role": "system",
  324. "content": "- 你名为epub翻译大师,专注于将任意语言的文本翻译成中文。- 你在翻译过程中,力求保留原文语意,确保翻译的准确性和完整性。- 你特别注重翻译结果要贴合现代人的阅读习惯,使译文更加流畅易懂。- 在处理包含代码结构的文本时,你会特别注意保持代码的原样。- 你的服务旨在为用户提供高效、便捷的翻译体验,帮助用户跨越语言障碍。- 在回答问题的时候,尽可能保留原来的代码结构。- 在回答问题的时候,尽可能只返回翻译后的内容和代码结构,不要返回任何其他内容。"
  325. # zhipu
  326. # "content": """
  327. # # 角色
  328. # 你是epub翻译大师,专注于精准翻译任意语言文本至中文。
  329. # # 工作任务
  330. # 翻译文本,确保语义准确、完整,并贴合现代阅读习惯。
  331. # # 输出示例
  332. # ```
  333. # 你好,世界!
  334. # print("你好,世界!")
  335. # ```
  336. # # 注意事项
  337. # 在翻译代码结构时,保持原样,只在必要时添加注释。
  338. # """
  339. },
  340. {
  341. "role": "user",
  342. "content": text
  343. }
  344. ]
  345. # 使用流式输出
  346. stream = config.client.chat.completions.create(
  347. model=MODEL_CONFIG['model_name'],
  348. messages=messages,
  349. timeout=MODEL_CONFIG['timeout'],
  350. stream=True # 启用流式输出
  351. )
  352. # 收集流式输出的内容
  353. translated_text = ""
  354. for chunk in stream:
  355. if chunk.choices[0].delta.content is not None:
  356. content = chunk.choices[0].delta.content
  357. translated_text += content
  358. # 实时打印翻译内容
  359. print(content, end='', flush=True)
  360. print() # 换行
  361. # 更新统计信息
  362. translation_stats.update_stats(text, translated_text, True)
  363. return translated_text
  364. except Exception as e:
  365. logging.error(f"翻译出错: {str(e)}")
  366. # 更新统计信息
  367. translation_stats.update_stats(text, "", False)
  368. raise
  369. def process_html_file(file_path, conn):
  370. """处理HTML文件"""
  371. # 检查文件进度
  372. progress = db_manager.get_file_progress(file_path)
  373. try:
  374. # 尝试不同的编码方式读取文件
  375. encodings = ['utf-8', 'gbk', 'gb2312', 'latin1']
  376. content = None
  377. for encoding in encodings:
  378. try:
  379. with open(file_path, 'r', encoding=encoding) as f:
  380. content = f.read()
  381. break
  382. except UnicodeDecodeError:
  383. continue
  384. if content is None:
  385. raise Exception(f"无法使用支持的编码读取文件: {file_path}")
  386. # 使用正则表达式提取body标签内的内容和title标签
  387. body_pattern = re.compile(r'<body[^>]*>(.*?)</body>', re.DOTALL)
  388. title_pattern = re.compile(r'<title>(.*?)</title>', re.DOTALL)
  389. body_match = body_pattern.search(content)
  390. title_match = title_pattern.search(content)
  391. if not body_match:
  392. print(f"警告: {file_path} 中没有找到body标签")
  393. return
  394. body_content = body_match.group(1)
  395. # 处理title标签
  396. if title_match:
  397. title_content = title_match.group(1).strip()
  398. if title_content: # 只有当标题内容不为空时才处理
  399. print(f"\n翻译标题: {title_content}")
  400. translated_title = translate_text(title_content)
  401. # 替换原始title内容
  402. content = content.replace(f"<title>{title_content}</title>", f"<title>{translated_title}</title>")
  403. else:
  404. print("\n跳过空标题")
  405. # 按行分割body内容
  406. lines = [line.strip() for line in body_content.split('\n') if line.strip()]
  407. total_lines = len(lines)
  408. # 获取已完成的翻译
  409. completed_lines = get_completed_groups(conn, file_path)
  410. completed_indices = {line[0] for line in completed_lines}
  411. # 计算已处理的进度
  412. if progress:
  413. print(f"文件 {file_path} 已处理进度: {progress['processed_lines']}/{progress['total_lines']} 行 ({round(progress['processed_lines']*100/progress['total_lines'], 2)}%)")
  414. # 按4行一组处理内容
  415. translated_lines = []
  416. try:
  417. with tqdm(range(0, len(lines), 4), desc=f"处理文件 {os.path.basename(file_path)}", unit="组") as pbar:
  418. for i in pbar:
  419. # 获取当前组的行
  420. group_lines = lines[i:i+4]
  421. # 检查是否已完成
  422. if all(i+j in completed_indices for j in range(len(group_lines))):
  423. # 使用已完成的翻译
  424. for j in range(len(group_lines)):
  425. for line in completed_lines:
  426. if line[0] == i+j:
  427. translated_lines.append(line[1])
  428. break
  429. continue
  430. # 将当前组的行合并成一个字符串
  431. group_text = '\n'.join(group_lines)
  432. print(f"\n翻译第 {i+1}-{min(i+4, len(lines))}/{len(lines)} 行:")
  433. # 翻译当前组
  434. translated_group = translate_text(group_text)
  435. # 将翻译结果按行分割并添加到结果列表
  436. translated_lines.extend(translated_group.split('\n'))
  437. # 更新文件进度
  438. db_manager.update_file_progress(file_path, total_lines, min(i+4, len(lines)), 'in_progress')
  439. # 显示当前统计信息
  440. stats = translation_stats.get_stats()
  441. pbar.set_postfix(stats)
  442. # 添加较小的延迟以避免API限制
  443. time.sleep(0.1)
  444. # 替换原始内容
  445. if translated_lines:
  446. # 构建新的body内容
  447. new_body_content = '\n'.join(translated_lines)
  448. # 替换原始内容中的body部分
  449. new_content = content.replace(body_content, new_body_content)
  450. # 保存修改后的文件
  451. output_dir = config.get('paths', 'output_dir')
  452. os.makedirs(output_dir, exist_ok=True)
  453. output_path = os.path.join(output_dir, os.path.basename(file_path))
  454. with open(output_path, 'w', encoding='utf-8') as f:
  455. f.write(new_content)
  456. # 更新完成状态
  457. db_manager.update_file_progress(file_path, total_lines, total_lines, 'completed')
  458. print(f"文件 {file_path} 翻译完成,已保存到 {output_path}")
  459. # 显示最终统计信息
  460. print("\n翻译统计信息:")
  461. for key, value in translation_stats.get_stats().items():
  462. print(f"{key}: {value}")
  463. except KeyboardInterrupt:
  464. print("\n检测到中断,保存当前进度...")
  465. if 'processed_lines' in locals():
  466. db_manager.update_file_progress(file_path, total_lines, processed_lines, 'interrupted')
  467. # 显示中断时的统计信息
  468. print("\n中断时的统计信息:")
  469. for key, value in translation_stats.get_stats().items():
  470. print(f"{key}: {value}")
  471. raise
  472. except Exception as e:
  473. print(f"处理文件时出错: {str(e)}")
  474. if 'processed_lines' in locals():
  475. db_manager.update_file_progress(file_path, total_lines, processed_lines, 'error')
  476. raise
  477. except Exception as e:
  478. print(f"读取文件时出错: {str(e)}")
  479. return
  480. def main():
  481. ops_dir = config.get('paths', 'input_dir')
  482. html_files = [f for f in os.listdir(ops_dir) if f.endswith('.htm') or f.endswith('.html')]
  483. # 按文件名排序
  484. html_files.sort()
  485. total_files = len(html_files)
  486. print(f"找到 {total_files} 个HTML文件需要处理")
  487. print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  488. # 初始化数据库连接
  489. conn = db_manager.get_connection()
  490. try:
  491. for file_index, filename in enumerate(html_files, 1):
  492. file_path = os.path.join(ops_dir, filename)
  493. print(f"\n开始处理第 {file_index}/{total_files} 个文件: {filename}")
  494. print("-" * 50)
  495. # 检查文件是否已完成
  496. progress = db_manager.get_file_progress(file_path)
  497. if progress and progress['status'] == 'completed':
  498. print(f"文件 {filename} 已经完成翻译,跳过")
  499. continue
  500. try:
  501. process_html_file(file_path, conn)
  502. print(f"\n完成第 {file_index}/{total_files} 个文件: {filename}")
  503. print("-" * 50)
  504. except Exception as e:
  505. print(f"\n处理文件 {filename} 时出错: {str(e)}")
  506. print("继续处理下一个文件...")
  507. continue
  508. # 显示当前总体进度
  509. completed_files = sum(1 for f in html_files[:file_index]
  510. if db_manager.get_file_progress(os.path.join(ops_dir, f)) and
  511. db_manager.get_file_progress(os.path.join(ops_dir, f))['status'] == 'completed')
  512. print(f"\n总体进度: {completed_files}/{total_files} 个文件完成 "
  513. f"({round(completed_files*100/total_files, 2)}%)")
  514. # 显示统计信息
  515. print("\n当前统计信息:")
  516. for key, value in translation_stats.get_stats().items():
  517. print(f"{key}: {value}")
  518. # 在文件之间添加短暂延迟
  519. if file_index < total_files:
  520. print("\n等待 5 秒后处理下一个文件...")
  521. time.sleep(5)
  522. except KeyboardInterrupt:
  523. print("\n程序被用户中断")
  524. finally:
  525. db_manager.close()
  526. print(f"\n结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  527. print("\n最终统计信息:")
  528. for key, value in translation_stats.get_stats().items():
  529. print(f"{key}: {value}")
  530. if __name__ == "__main__":
  531. main()