translate_epub_v3.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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 LineCountManager:
  128. def __init__(self):
  129. self.current_line_count = INITIAL_LINE_COUNT
  130. self.consecutive_errors = 0
  131. self.consecutive_successes = 0
  132. self.last_error_time = None
  133. self.error_cooldown = config.get('translation', 'error_cooldown')
  134. self.version = f"1.0.{INITIAL_LINE_COUNT}"
  135. self.error_history = []
  136. def adjust_line_count(self, success):
  137. """根据翻译结果调整行数"""
  138. current_time = time.time()
  139. # 检查是否在冷却期内
  140. if self.last_error_time and (current_time - self.last_error_time) < self.error_cooldown:
  141. return self.current_line_count
  142. if success:
  143. self.consecutive_errors = 0
  144. self.consecutive_successes += 1
  145. # 如果连续成功次数达到阈值,尝试增加行数
  146. if self.consecutive_successes >= SUCCESS_THRESHOLD:
  147. if self.current_line_count < MAX_LINE_COUNT:
  148. self.current_line_count += 1
  149. self.consecutive_successes = 0
  150. self.version = f"1.0.{self.current_line_count}"
  151. logging.info(f"翻译连续成功,增加行数到 {self.current_line_count},版本更新为 {self.version}")
  152. else:
  153. self.consecutive_successes = 0
  154. self.consecutive_errors += 1
  155. self.last_error_time = current_time
  156. # 记录错误
  157. self.error_history.append({
  158. 'time': current_time,
  159. 'line_count': self.current_line_count
  160. })
  161. # 如果连续错误次数达到阈值,减少行数
  162. if self.consecutive_errors >= ERROR_THRESHOLD:
  163. if self.current_line_count > MIN_LINE_COUNT:
  164. self.current_line_count -= 1
  165. self.consecutive_errors = 0
  166. self.version = f"1.0.{self.current_line_count}"
  167. logging.warning(f"翻译连续失败,减少行数到 {self.current_line_count},版本更新为 {self.version}")
  168. return self.current_line_count
  169. def get_error_stats(self):
  170. """获取错误统计信息"""
  171. if not self.error_history:
  172. return "无错误记录"
  173. recent_errors = [e for e in self.error_history if time.time() - e['time'] < 3600] # 最近一小时的错误
  174. return {
  175. "总错误数": len(self.error_history),
  176. "最近一小时错误数": len(recent_errors),
  177. "当前行数": self.current_line_count,
  178. "连续错误": self.consecutive_errors,
  179. "连续成功": self.consecutive_successes
  180. }
  181. class DatabaseManager:
  182. def __init__(self):
  183. self.db_path = config.get('database', 'path')
  184. self.conn = None
  185. self.init_db()
  186. def get_connection(self):
  187. """获取数据库连接"""
  188. if self.conn is None:
  189. self.conn = sqlite3.connect(self.db_path)
  190. self.conn.row_factory = sqlite3.Row
  191. return self.conn
  192. def close(self):
  193. """关闭数据库连接"""
  194. if self.conn:
  195. self.conn.close()
  196. self.conn = None
  197. def init_db(self):
  198. """初始化数据库"""
  199. conn = self.get_connection()
  200. c = conn.cursor()
  201. # 创建文件进度表
  202. c.execute('''
  203. CREATE TABLE IF NOT EXISTS file_progress (
  204. file_path TEXT PRIMARY KEY,
  205. total_lines INTEGER,
  206. processed_lines INTEGER,
  207. status TEXT,
  208. version TEXT,
  209. last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  210. error_count INTEGER DEFAULT 0,
  211. retry_count INTEGER DEFAULT 0
  212. )
  213. ''')
  214. # 创建翻译组进度表
  215. c.execute('''
  216. CREATE TABLE IF NOT EXISTS group_progress (
  217. id INTEGER PRIMARY KEY AUTOINCREMENT,
  218. file_path TEXT,
  219. group_index INTEGER,
  220. original_text TEXT,
  221. translated_text TEXT,
  222. status TEXT,
  223. version TEXT,
  224. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  225. updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  226. error_count INTEGER DEFAULT 0,
  227. retry_count INTEGER DEFAULT 0,
  228. UNIQUE(file_path, group_index, version)
  229. )
  230. ''')
  231. # 创建错误日志表
  232. c.execute('''
  233. CREATE TABLE IF NOT EXISTS error_log (
  234. id INTEGER PRIMARY KEY AUTOINCREMENT,
  235. file_path TEXT,
  236. group_index INTEGER,
  237. error_type TEXT,
  238. error_message TEXT,
  239. created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  240. resolved_at TIMESTAMP,
  241. resolution TEXT
  242. )
  243. ''')
  244. conn.commit()
  245. def begin_transaction(self):
  246. """开始事务"""
  247. self.get_connection().execute('BEGIN TRANSACTION')
  248. def commit_transaction(self):
  249. """提交事务"""
  250. self.get_connection().commit()
  251. def rollback_transaction(self):
  252. """回滚事务"""
  253. self.get_connection().rollback()
  254. def get_file_progress(self, file_path):
  255. """获取文件翻译进度"""
  256. c = self.get_connection().cursor()
  257. c.execute('SELECT * FROM file_progress WHERE file_path = ?', (file_path,))
  258. return c.fetchone()
  259. def update_file_progress(self, file_path, total_lines, processed_lines, status):
  260. """更新文件翻译进度"""
  261. c = self.get_connection().cursor()
  262. c.execute('''
  263. INSERT OR REPLACE INTO file_progress
  264. (file_path, total_lines, processed_lines, status, version, last_updated)
  265. VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  266. ''', (file_path, total_lines, processed_lines, status, line_count_manager.version))
  267. self.get_connection().commit()
  268. def get_group_progress(self, file_path, group_index):
  269. """获取翻译组进度"""
  270. c = self.get_connection().cursor()
  271. c.execute('''
  272. SELECT * FROM group_progress
  273. WHERE file_path = ? AND group_index = ? AND version = ?
  274. ''', (file_path, group_index, line_count_manager.version))
  275. return c.fetchone()
  276. def update_group_progress(self, file_path, group_index, original_text, translated_text, status):
  277. """更新翻译组进度"""
  278. c = self.get_connection().cursor()
  279. c.execute('''
  280. INSERT OR REPLACE INTO group_progress
  281. (file_path, group_index, original_text, translated_text, status, version, updated_at)
  282. VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
  283. ''', (file_path, group_index, original_text, translated_text, status, line_count_manager.version))
  284. self.get_connection().commit()
  285. def log_error(self, file_path, group_index, error_type, error_message):
  286. """记录错误"""
  287. c = self.get_connection().cursor()
  288. c.execute('''
  289. INSERT INTO error_log
  290. (file_path, group_index, error_type, error_message)
  291. VALUES (?, ?, ?, ?)
  292. ''', (file_path, group_index, error_type, error_message))
  293. self.get_connection().commit()
  294. def get_error_stats(self):
  295. """获取错误统计信息"""
  296. c = self.get_connection().cursor()
  297. c.execute('''
  298. SELECT
  299. COUNT(*) as total_errors,
  300. COUNT(CASE WHEN resolved_at IS NULL THEN 1 END) as unresolved_errors,
  301. COUNT(CASE WHEN created_at > datetime('now', '-1 hour') THEN 1 END) as recent_errors
  302. FROM error_log
  303. ''')
  304. return c.fetchone()
  305. class AsyncTranslationManager:
  306. def __init__(self):
  307. self.semaphore = asyncio.Semaphore(config.get('openai', 'max_concurrent_requests'))
  308. self.session = None
  309. class TranslationCache:
  310. def __init__(self):
  311. self.cache = {}
  312. self.max_size = config.get('translation', 'cache_size')
  313. self.hits = 0
  314. self.misses = 0
  315. # 创建全局实例
  316. line_count_manager = LineCountManager()
  317. db_manager = DatabaseManager()
  318. async_translation_manager = AsyncTranslationManager()
  319. translation_cache = TranslationCache()
  320. # 添加版本控制
  321. VERSION = "1.0.1" # 版本号,用于区分不同版本的翻译
  322. line_count = 2 # 每组行数,越大越快,但越容易出错
  323. class TranslationStats:
  324. def __init__(self):
  325. self.start_time = time.time()
  326. self.total_chars = 0
  327. self.translated_chars = 0
  328. self.total_requests = 0
  329. self.successful_requests = 0
  330. self.failed_requests = 0
  331. def update_stats(self, original_text, translated_text, success=True):
  332. self.total_chars += len(original_text)
  333. self.translated_chars += len(translated_text)
  334. self.total_requests += 1
  335. if success:
  336. self.successful_requests += 1
  337. else:
  338. self.failed_requests += 1
  339. def get_stats(self):
  340. elapsed_time = time.time() - self.start_time
  341. chars_per_second = self.translated_chars / elapsed_time if elapsed_time > 0 else 0
  342. success_rate = (self.successful_requests / self.total_requests * 100) if self.total_requests > 0 else 0
  343. return {
  344. "总字符数": self.total_chars,
  345. "已翻译字符数": self.translated_chars,
  346. "翻译速度": f"{chars_per_second:.2f} 字符/秒",
  347. "成功率": f"{success_rate:.1f}%",
  348. "总请求数": self.total_requests,
  349. "成功请求": self.successful_requests,
  350. "失败请求": self.failed_requests,
  351. "运行时间": f"{elapsed_time:.1f} 秒"
  352. }
  353. # 创建全局的统计对象
  354. translation_stats = TranslationStats()
  355. def get_completed_groups(conn, file_path):
  356. """获取已完成的翻译组"""
  357. c = conn.cursor()
  358. c.execute('''
  359. SELECT group_index, translated_text
  360. FROM group_progress
  361. WHERE file_path = ? AND status = 'completed' AND version = ?
  362. ORDER BY group_index
  363. ''', (file_path, line_count_manager.version))
  364. return c.fetchall()
  365. # """ - 输出内容要求用代码块包裹起来
  366. # ,只在必要时提供相应的语言注释
  367. # """
  368. @retry(
  369. stop=stop_after_attempt(MODEL_CONFIG['max_retries']),
  370. wait=wait_exponential(multiplier=1, min=4, max=10),
  371. retry=retry_if_exception_type((openai.APIError, openai.APITimeoutError)),
  372. before_sleep=lambda retry_state: logging.warning(f"重试第 {retry_state.attempt_number} 次...")
  373. )
  374. def translate_text(text):
  375. """翻译文本,使用tenacity进行重试"""
  376. try:
  377. messages = [
  378. {
  379. "role": "system",
  380. "content": "- 你名为epub翻译大师,专注于将任意语言的文本翻译成中文。- 你在翻译过程中,力求保留原文语意,确保翻译的准确性和完整性。- 你特别注重翻译结果要贴合现代人的阅读习惯,使译文更加流畅易懂。- 在处理包含代码结构的文本时,你会特别注意保持代码的原样。- 你的服务旨在为用户提供高效、便捷的翻译体验,帮助用户跨越语言障碍。- 在回答问题的时候,尽可能保留原来的代码结构。"
  381. },
  382. {
  383. "role": "user",
  384. "content": text
  385. }
  386. ]
  387. response = config.client.chat.completions.create(
  388. model=MODEL_CONFIG['model_name'],
  389. messages=messages,
  390. timeout=MODEL_CONFIG['timeout']
  391. )
  392. translated_text = response.choices[0].message.content
  393. line_count_manager.adjust_line_count(True)
  394. return translated_text
  395. except Exception as e:
  396. logging.error(f"翻译出错: {str(e)}")
  397. line_count_manager.adjust_line_count(False)
  398. raise
  399. def process_html_file(file_path, conn):
  400. """处理HTML文件"""
  401. # 检查文件进度
  402. progress = db_manager.get_file_progress(file_path)
  403. try:
  404. # 尝试不同的编码方式读取文件
  405. encodings = ['utf-8', 'gbk', 'gb2312', 'latin1']
  406. content = None
  407. for encoding in encodings:
  408. try:
  409. with open(file_path, 'r', encoding=encoding) as f:
  410. content = f.read()
  411. break
  412. except UnicodeDecodeError:
  413. continue
  414. if content is None:
  415. raise Exception(f"无法使用支持的编码读取文件: {file_path}")
  416. # 使用正则表达式提取body标签内的内容
  417. body_pattern = re.compile(r'<body[^>]*>(.*?)</body>', re.DOTALL)
  418. body_match = body_pattern.search(content)
  419. if not body_match:
  420. print(f"警告: {file_path} 中没有找到body标签")
  421. return
  422. body_content = body_match.group(1)
  423. # 按行分割内容,保留所有HTML标签行,但只翻译包含 <p class 的行
  424. lines = []
  425. for line in body_content.split('\n'):
  426. line = line.strip()
  427. if line and line.startswith('<'):
  428. lines.append(line)
  429. total_lines = len(lines)
  430. # 获取已完成的翻译组
  431. completed_groups = get_completed_groups(conn, file_path)
  432. completed_indices = {group[0] for group in completed_groups}
  433. # 计算已处理的进度
  434. if progress:
  435. print(f"文件 {file_path} 已处理进度: {progress[2]}/{progress[1]} 行 ({round(progress[2]*100/progress[1], 2)}%)")
  436. # 按组处理内容
  437. translated_lines = []
  438. try:
  439. with tqdm(range(0, len(lines), line_count_manager.current_line_count),
  440. desc=f"处理文件 {os.path.basename(file_path)}",
  441. unit="组") as pbar:
  442. for i in pbar:
  443. group_index = i // line_count_manager.current_line_count
  444. # 检查是否已完成
  445. if group_index in completed_indices:
  446. # 使用已完成的翻译
  447. for group in completed_groups:
  448. if group[0] == group_index:
  449. translated_lines.extend(group[1].split('\n'))
  450. break
  451. continue
  452. group = lines[i:i+line_count_manager.current_line_count]
  453. if group:
  454. # 保存原始文本
  455. original_text = "\n".join(group)
  456. # 收集需要翻译的段落
  457. paragraphs_to_translate = []
  458. paragraph_indices = []
  459. for idx, line in enumerate(group):
  460. if '<p class' in line:
  461. paragraphs_to_translate.append(line)
  462. paragraph_indices.append(idx)
  463. # 如果有需要翻译的段落,进行翻译
  464. if paragraphs_to_translate:
  465. translated_paragraphs = []
  466. for paragraph in paragraphs_to_translate:
  467. translated_paragraph = translate_text(paragraph)
  468. translated_paragraphs.append(translated_paragraph)
  469. # 将翻译后的段落放回原位置
  470. translated_group = group.copy()
  471. for idx, translated in zip(paragraph_indices, translated_paragraphs):
  472. translated_group[idx] = translated
  473. else:
  474. translated_group = group
  475. translated_text = "\n".join(translated_group)
  476. # 更新翻译组进度
  477. db_manager.update_group_progress(file_path, group_index, original_text, translated_text, 'completed')
  478. # 分割翻译后的文本
  479. translated_lines.extend(translated_group)
  480. # 更新文件进度
  481. processed_lines = min((group_index + 1) * line_count_manager.current_line_count, total_lines)
  482. db_manager.update_file_progress(file_path, total_lines, processed_lines, 'in_progress')
  483. # 显示当前统计信息
  484. stats = translation_stats.get_stats()
  485. pbar.set_postfix(stats)
  486. # 添加较小的延迟以避免API限制
  487. time.sleep(0.1) # 减少延迟时间
  488. # 替换原始内容
  489. if translated_lines:
  490. # 构建新的body内容
  491. new_body_content = []
  492. current_index = 0
  493. # 遍历原始内容,替换需要翻译的部分
  494. for line in body_content.split('\n'):
  495. line = line.strip()
  496. if not line:
  497. new_body_content.append('')
  498. continue
  499. if line.startswith('<'):
  500. if '<p class' in line and current_index < len(translated_lines):
  501. # 替换翻译后的内容
  502. new_body_content.append(translated_lines[current_index])
  503. current_index += 1
  504. else:
  505. # 保持原样
  506. new_body_content.append(line)
  507. else:
  508. # 保持非HTML内容原样
  509. new_body_content.append(line)
  510. # 将新内容重新组合
  511. new_body_content = '\n'.join(new_body_content)
  512. # 替换原始内容中的body部分
  513. new_content = content.replace(body_content, new_body_content)
  514. # 保存修改后的文件
  515. output_dir = config.get('paths', 'output_dir')
  516. os.makedirs(output_dir, exist_ok=True)
  517. output_path = os.path.join(output_dir, os.path.basename(file_path))
  518. with open(output_path, 'w', encoding='utf-8') as f:
  519. f.write(new_content)
  520. # 更新完成状态
  521. db_manager.update_file_progress(file_path, total_lines, total_lines, 'completed')
  522. print(f"文件 {file_path} 翻译完成,已保存到 {output_path}")
  523. # 显示最终统计信息
  524. print("\n翻译统计信息:")
  525. for key, value in translation_stats.get_stats().items():
  526. print(f"{key}: {value}")
  527. except KeyboardInterrupt:
  528. print("\n检测到中断,保存当前进度...")
  529. if 'processed_lines' in locals():
  530. db_manager.update_file_progress(file_path, total_lines, processed_lines, 'interrupted')
  531. # 显示中断时的统计信息
  532. print("\n中断时的统计信息:")
  533. for key, value in translation_stats.get_stats().items():
  534. print(f"{key}: {value}")
  535. raise
  536. except Exception as e:
  537. print(f"处理文件时出错: {str(e)}")
  538. if 'processed_lines' in locals():
  539. db_manager.update_file_progress(file_path, total_lines, processed_lines, 'error')
  540. raise
  541. except Exception as e:
  542. print(f"读取文件时出错: {str(e)}")
  543. return
  544. def main():
  545. ops_dir = "002/Ops"
  546. html_files = [f for f in os.listdir(ops_dir) if f.endswith('.html')]
  547. print(f"找到 {len(html_files)} 个HTML文件需要处理")
  548. print(f"开始时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  549. # 初始化数据库连接
  550. conn = db_manager.get_connection()
  551. try:
  552. for filename in tqdm(html_files, desc="处理文件", unit="文件"):
  553. file_path = os.path.join(ops_dir, filename)
  554. process_html_file(file_path, conn)
  555. except KeyboardInterrupt:
  556. print("\n程序被用户中断")
  557. finally:
  558. db_manager.close()
  559. print(f"\n结束时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  560. print("\n最终统计信息:")
  561. for key, value in translation_stats.get_stats().items():
  562. print(f"{key}: {value}")
  563. if __name__ == "__main__":
  564. main()