translate_epub_v4(单线程版本)V2.py 28 KB

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