llm_aided.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. import ast
  7. #@todo: 有的公式以"\"结尾,这样会导致尾部拼接的"$"被转义,也需要修复
  8. formula_optimize_prompt = """请根据以下指南修正LaTeX公式的错误,确保公式能够渲染且符合原始内容:
  9. 1. 修正渲染或编译错误:
  10. - 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.
  11. - 包含KaTeX不支持的关键词等原因导致的无法编译或渲染的错误
  12. 2. 保留原始信息:
  13. - 保留原始公式中的所有重要信息
  14. - 不要添加任何原始公式中没有的新信息
  15. IMPORTANT:请仅返回修正后的公式,不要包含任何介绍、解释或元数据。
  16. LaTeX recognition result:
  17. $FORMULA
  18. Your corrected result:
  19. """
  20. text_optimize_prompt = f"""请根据以下指南修正OCR引起的错误,确保文本连贯并符合原始内容:
  21. 1. 修正OCR引起的拼写错误和错误:
  22. - 修正常见的OCR错误(例如,'rn' 被误读为 'm')
  23. - 使用上下文和常识进行修正
  24. - 只修正明显的错误,不要不必要的修改内容
  25. - 不要添加额外的句号或其他不必要的标点符号
  26. 2. 保持原始结构:
  27. - 保留所有标题和子标题
  28. 3. 保留原始内容:
  29. - 保留原始文本中的所有重要信息
  30. - 不要添加任何原始文本中没有的新信息
  31. - 保留段落之间的换行符
  32. 4. 保持连贯性:
  33. - 确保内容与前文顺畅连接
  34. - 适当处理在句子中间开始或结束的文本
  35. 5. 修正行内公式:
  36. - 去除行内公式前后多余的空格
  37. - 修正公式中的OCR错误
  38. - 确保公式能够通过KaTeX渲染
  39. 6. 修正全角字符
  40. - 修正全角标点符号为半角标点符号
  41. - 修正全角字母为半角字母
  42. - 修正全角数字为半角数字
  43. IMPORTANT:请仅返回修正后的文本,保留所有原始格式,包括换行符。不要包含任何介绍、解释或元数据。
  44. Previous context:
  45. Current chunk to process:
  46. Corrected text:
  47. """
  48. def llm_aided_formula(pdf_info_dict, formula_aided_config):
  49. pass
  50. def llm_aided_text(pdf_info_dict, text_aided_config):
  51. pass
  52. def llm_aided_title(pdf_info_dict, title_aided_config):
  53. client = OpenAI(
  54. api_key=title_aided_config["api_key"],
  55. base_url=title_aided_config["base_url"],
  56. )
  57. title_dict = {}
  58. origin_title_list = []
  59. i = 0
  60. for page_num, page in pdf_info_dict.items():
  61. blocks = page["para_blocks"]
  62. for block in blocks:
  63. if block["type"] == "title":
  64. origin_title_list.append(block)
  65. title_text = merge_para_with_text(block)
  66. page_line_height_list = []
  67. for line in block['lines']:
  68. bbox = line['bbox']
  69. page_line_height_list.append(int(bbox[3] - bbox[1]))
  70. if len(page_line_height_list) > 0:
  71. line_avg_height = sum(page_line_height_list) / len(page_line_height_list)
  72. else:
  73. line_avg_height = int(block['bbox'][3] - block['bbox'][1])
  74. title_dict[f"{i}"] = [title_text, line_avg_height, int(page_num[5:])+1]
  75. i += 1
  76. # logger.info(f"Title list: {title_dict}")
  77. title_optimize_prompt = f"""输入的内容是一篇文档中所有标题组成的字典,请根据以下指南优化标题的结果,使结果符合正常文档的层次结构:
  78. 1. 字典中每个value均为一个list,包含以下元素:
  79. - 标题文本
  80. - 文本行高是标题所在块的平均行高
  81. - 标题所在的页码
  82. 2. 保留原始内容:
  83. - 输入的字典中所有元素都是有效的,不能删除字典中的任何元素
  84. - 请务必保证输出的字典中元素的数量和输入的数量一致
  85. 3. 保持字典内key-value的对应关系不变
  86. 4. 优化层次结构:
  87. - 为每个标题元素添加适当的层次结构
  88. - 行高较大的标题一般是更高级别的标题
  89. - 标题从前至后的层级必须是连续的,不能跳过层级
  90. - 标题层级最多为4级,不要添加过多的层级
  91. - 优化后的标题只保留代表该标题的层级的整数,不要保留其他信息
  92. 5. 合理性检查与微调:
  93. - 在完成初步分级后,仔细检查分级结果的合理性
  94. - 根据上下文关系和逻辑顺序,对不合理的分级进行微调
  95. - 确保最终的分级结果符合文档的实际结构和逻辑
  96. - 字典中可能包含被误当成标题的正文,你可以通过将其层级标记为 0 来排除它们
  97. IMPORTANT:
  98. 请直接返回优化过的由标题层级组成的字典,格式为{{标题id:标题层级}},如下:
  99. {{0:1,1:2,2:2,3:3}}
  100. 不需要对字典格式化,不需要返回任何其他信息。
  101. Input title list:
  102. {title_dict}
  103. Corrected title list:
  104. """
  105. retry_count = 0
  106. max_retries = 3
  107. dict_completion = None
  108. while retry_count < max_retries:
  109. try:
  110. completion = client.chat.completions.create(
  111. model=title_aided_config["model"],
  112. messages=[
  113. {'role': 'user', 'content': title_optimize_prompt}],
  114. temperature=0.7,
  115. )
  116. # logger.info(f"Title completion: {completion.choices[0].message.content}")
  117. dict_completion = ast.literal_eval(completion.choices[0].message.content)
  118. # logger.info(f"len(dict_completion): {len(dict_completion)}, len(title_dict): {len(title_dict)}")
  119. if len(dict_completion) == len(title_dict):
  120. for i, origin_title_block in enumerate(origin_title_list):
  121. origin_title_block["level"] = int(dict_completion[i])
  122. break
  123. else:
  124. logger.warning("The number of titles in the optimized result is not equal to the number of titles in the input.")
  125. retry_count += 1
  126. except Exception as e:
  127. logger.exception(e)
  128. retry_count += 1
  129. if dict_completion is None:
  130. logger.error("Failed to decode dict after maximum retries.")