translate_epub_v4(单线程版本).py 20 KB

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