llm_aided.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. import json
  3. from loguru import logger
  4. from magic_pdf.dict2md.ocr_mkcontent import merge_para_with_text
  5. from openai import OpenAI
  6. formula_optimize_prompt = """请根据以下指南修正LaTeX公式的错误,确保公式能够渲染且符合原始内容:
  7. 1. 修正渲染或编译错误:
  8. - Some syntax errors such as mismatched/missing/extra tokens. Your task is to fix these syntax errors and make sure corrected results conform to latex math syntax principles.
  9. - 包含KaTeX不支持的关键词等原因导致的无法编译或渲染的错误
  10. 2. 保留原始信息:
  11. - 保留原始公式中的所有重要信息
  12. - 不要添加任何原始公式中没有的新信息
  13. IMPORTANT:请仅返回修正后的公式,不要包含任何介绍、解释或元数据。
  14. LaTeX recognition result:
  15. $FORMULA
  16. Your corrected result:
  17. """
  18. text_optimize_prompt = f"""请根据以下指南修正OCR引起的错误,确保文本连贯并符合原始内容:
  19. 1. 修正OCR引起的拼写错误和错误:
  20. - 修正常见的OCR错误(例如,'rn' 被误读为 'm')
  21. - 使用上下文和常识进行修正
  22. - 只修正明显的错误,不要不必要的修改内容
  23. - 不要添加额外的句号或其他不必要的标点符号
  24. 2. 保持原始结构:
  25. - 保留所有标题和子标题
  26. 3. 保留原始内容:
  27. - 保留原始文本中的所有重要信息
  28. - 不要添加任何原始文本中没有的新信息
  29. - 保留段落之间的换行符
  30. 4. 保持连贯性:
  31. - 确保内容与前文顺畅连接
  32. - 适当处理在句子中间开始或结束的文本
  33. 5. 修正行内公式:
  34. - 去除行内公式前后多余的空格
  35. - 修正公式中的OCR错误
  36. - 确保公式能够通过KaTeX渲染
  37. 6. 修正全角字符
  38. - 修正全角标点符号为半角标点符号
  39. - 修正全角字母为半角字母
  40. - 修正全角数字为半角数字
  41. IMPORTANT:请仅返回修正后的文本,保留所有原始格式,包括换行符。不要包含任何介绍、解释或元数据。
  42. Previous context:
  43. Current chunk to process:
  44. Corrected text:
  45. """
  46. def llm_aided_formula(pdf_info_dict, formula_aided_config):
  47. pass
  48. def llm_aided_text(pdf_info_dict, text_aided_config):
  49. pass
  50. def llm_aided_title(pdf_info_dict, title_aided_config):
  51. client = OpenAI(
  52. api_key=title_aided_config["api_key"],
  53. base_url=title_aided_config["base_url"],
  54. )
  55. title_dict = {}
  56. origin_title_list = []
  57. i = 0
  58. for page_num, page in pdf_info_dict.items():
  59. blocks = page["para_blocks"]
  60. for block in blocks:
  61. if block["type"] == "title":
  62. origin_title_list.append(block)
  63. title_text = merge_para_with_text(block)
  64. title_dict[f"{i}"] = title_text
  65. i += 1
  66. # logger.info(f"Title list: {title_dict}")
  67. title_optimize_prompt = f"""输入的内容是一篇文档中所有标题组成的字典,请根据以下指南优化标题的结果,使结果符合正常文档的层次结构:
  68. 1. 保留原始内容:
  69. - 输入的字典中所有元素都是有效的,不能删除字典中的任何元素
  70. - 请务必保证输出的字典中元素的数量和输入的数量一致
  71. 2. 保持字典内key-value的对应关系不变
  72. 3. 优化层次结构:
  73. - 为每个标题元素添加适当的层次结构
  74. - 标题层级应具有连续性,不能跳过某一层级
  75. - 标题层级最多为4级,不要添加过多的层级
  76. - 优化后的标题为一个整数,代表该标题的层级
  77. IMPORTANT:
  78. 请直接返回优化过的由标题层级组成的json,返回的json不需要格式化。
  79. Input title list:
  80. {title_dict}
  81. Corrected title list:
  82. """
  83. completion = client.chat.completions.create(
  84. model=title_aided_config["model"],
  85. messages=[
  86. {'role': 'user', 'content': title_optimize_prompt}],
  87. temperature=0.7,
  88. )
  89. json_completion = json.loads(completion.choices[0].message.content)
  90. # logger.info(f"Title completion: {json_completion}")
  91. # logger.info(f"len(json_completion): {len(json_completion)}, len(title_dict): {len(title_dict)}")
  92. if len(json_completion) == len(title_dict):
  93. try:
  94. for i, origin_title_block in enumerate(origin_title_list):
  95. origin_title_block["level"] = int(json_completion[str(i)])
  96. except Exception as e:
  97. logger.exception(e)
  98. else:
  99. logger.error("The number of titles in the optimized result is not equal to the number of titles in the input.")