rectify_transcript.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import requests
  2. import json
  3. from typing import Optional
  4. import config.config
  5. class RectifyClient_transcript:
  6. """
  7. 使用 DeepSeek API 整理 OCR 文本,去除无关标记,保留原文内容。
  8. """
  9. def __init__(self, api_key: str = None, model: str = "deepseek-chat",
  10. temperature: float = 0.0, max_tokens: int = 4000):
  11. """
  12. 初始化 OCR 文本清理器。
  13. Args:
  14. api_key (str): DeepSeek API 密钥
  15. model (str): 使用的模型名称,默认为 "deepseek-chat"
  16. temperature (float): 温度参数,控制随机性,0 表示最确定
  17. max_tokens (int): 最大输出 token 数,根据文本长度调整
  18. """
  19. self.api_key = config.config.DEEPSEEK_API
  20. self.model = model
  21. self.temperature = temperature
  22. self.max_tokens = max_tokens
  23. self.api_url = "https://api.deepseek.com/v1/chat/completions"
  24. # 系统提示,明确任务要求
  25. self.system_prompt = """你是一个文本整理助手。请将用户提供的OCR提取文本整理为纯文本,要求:
  26. 1. 去除明显的OCR标记、页码、页眉页脚、行号等无关信息(例如"--- Page X ---"、"Process finished with exit code 0"等);
  27. 2. 保留所有原始文本内容,包括姓名、身份证号、电话号码、统一社会信用代码、金额、日期等数字信息必须与原文完全一致;
  28. 3. 不要修改或压缩任何正文文字;
  29. 4. 不要使用任何Markdown格式(如#、*、`等),直接输出纯文本。"""
  30. def clean_text(self, ocr_text: str) -> Optional[str]:
  31. """
  32. 清理 OCR 文本。
  33. Args:
  34. ocr_text (str): OCR 提取的原始文本
  35. Returns:
  36. Optional[str]: 清理后的纯文本,如果调用失败则返回 None
  37. """
  38. headers = {
  39. "Content-Type": "application/json",
  40. "Authorization": f"Bearer {self.api_key}"
  41. }
  42. payload = {
  43. "model": self.model,
  44. "messages": [
  45. {"role": "system", "content": self.system_prompt},
  46. {"role": "user", "content": f"请整理以下OCR文本:\n\n{ocr_text}"}
  47. ],
  48. "temperature": self.temperature,
  49. "max_tokens": self.max_tokens
  50. }
  51. try:
  52. response = requests.post(self.api_url, headers=headers, json=payload)
  53. response.raise_for_status()
  54. result = response.json()
  55. cleaned_text = result['choices'][0]['message']['content']
  56. return cleaned_text
  57. except requests.exceptions.RequestException as e:
  58. print(f"HTTP 请求失败: {e}")
  59. except KeyError as e:
  60. print(f"API 返回格式异常: {e}")
  61. except Exception as e:
  62. print(f"未知错误: {e}")
  63. return None
  64. def clean_file(self, input_file: str, output_file: str, encoding: str = "utf-8") -> bool:
  65. """
  66. 清理文件中的 OCR 文本,并将结果保存到另一个文件。
  67. Args:
  68. input_file (str): 输入文件路径(包含 OCR 原始文本)
  69. output_file (str): 输出文件路径(保存清理后的文本)
  70. encoding (str): 文件编码,默认为 utf-8
  71. Returns:
  72. bool: 是否成功处理
  73. """
  74. try:
  75. with open(input_file, "r", encoding=encoding) as f:
  76. ocr_text = f.read()
  77. cleaned = self.clean_text(ocr_text)
  78. if cleaned is None:
  79. return False
  80. with open(output_file, "w", encoding=encoding) as f:
  81. f.write(cleaned)
  82. return True
  83. except IOError as e:
  84. print(f"文件读写错误: {e}")
  85. return False
  86. # 使用示例
  87. if __name__ == "__main__":
  88. # 请替换为你的 DeepSeek API 密钥
  89. API_KEY = "your-deepseek-api-key"
  90. # 创建清理器实例
  91. cleaner = RectifyClient_transcript(api_key=API_KEY)
  92. # 方式1:直接清理字符串
  93. ocr_sample = """--- Page 1 ---
  94. 苏州市劳动人事争议仲裁委员会
  95. 庭审笔录
  96. 苏劳人仲案字〔2023〕第1号
  97. 2023年1月19日13时30分
  98. ...(省略)...
  99. Process finished with exit code 0"""
  100. cleaned = cleaner.clean_text(ocr_sample)
  101. if cleaned:
  102. print("清理后的文本:")
  103. print(cleaned)
  104. # 方式2:处理文件
  105. # success = cleaner.clean_file("ocr_output.txt", "cleaned_output.txt")
  106. # if success:
  107. # print("文件处理成功")