llm_aided.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # Copyright (c) Opendatalab. All rights reserved.
  2. from loguru import logger
  3. from openai import OpenAI
  4. import ast
  5. from mineru.backend.pipeline.pipeline_middle_json_mkcontent import merge_para_with_text
  6. def llm_aided_title(page_info_list, title_aided_config):
  7. client = OpenAI(
  8. api_key=title_aided_config["api_key"],
  9. base_url=title_aided_config["base_url"],
  10. )
  11. title_dict = {}
  12. origin_title_list = []
  13. i = 0
  14. for page_info in page_info_list:
  15. blocks = page_info["para_blocks"]
  16. for block in blocks:
  17. if block["type"] == "title":
  18. origin_title_list.append(block)
  19. title_text = merge_para_with_text(block)
  20. page_line_height_list = []
  21. for line in block['lines']:
  22. bbox = line['bbox']
  23. page_line_height_list.append(int(bbox[3] - bbox[1]))
  24. if len(page_line_height_list) > 0:
  25. line_avg_height = sum(page_line_height_list) / len(page_line_height_list)
  26. else:
  27. line_avg_height = int(block['bbox'][3] - block['bbox'][1])
  28. title_dict[f"{i}"] = [title_text, line_avg_height, int(page_info['page_idx']) + 1]
  29. i += 1
  30. # logger.info(f"Title list: {title_dict}")
  31. title_optimize_prompt = f"""输入的内容是一篇文档中所有标题组成的字典,请根据以下指南优化标题的结果,使结果符合正常文档的层次结构:
  32. 1. 字典中每个value均为一个list,包含以下元素:
  33. - 标题文本
  34. - 文本行高是标题所在块的平均行高
  35. - 标题所在的页码
  36. 2. 保留原始内容:
  37. - 输入的字典中所有元素都是有效的,不能删除字典中的任何元素
  38. - 请务必保证输出的字典中元素的数量和输入的数量一致
  39. 3. 保持字典内key-value的对应关系不变
  40. 4. 优化层次结构:
  41. - 为每个标题元素添加适当的层次结构
  42. - 行高较大的标题一般是更高级别的标题
  43. - 标题从前至后的层级必须是连续的,不能跳过层级
  44. - 标题层级最多为4级,不要添加过多的层级
  45. - 优化后的标题只保留代表该标题的层级的整数,不要保留其他信息
  46. 5. 合理性检查与微调:
  47. - 在完成初步分级后,仔细检查分级结果的合理性
  48. - 根据上下文关系和逻辑顺序,对不合理的分级进行微调
  49. - 确保最终的分级结果符合文档的实际结构和逻辑
  50. - 字典中可能包含被误当成标题的正文,你可以通过将其层级标记为 0 来排除它们
  51. IMPORTANT:
  52. 请直接返回优化过的由标题层级组成的字典,格式为{{标题id:标题层级}},如下:
  53. {{
  54. 0:1,
  55. 1:2,
  56. 2:2,
  57. 3:3
  58. }}
  59. 不需要对字典格式化,不需要返回任何其他信息。
  60. Input title list:
  61. {title_dict}
  62. Corrected title list:
  63. """
  64. retry_count = 0
  65. max_retries = 3
  66. dict_completion = None
  67. while retry_count < max_retries:
  68. try:
  69. completion = client.chat.completions.create(
  70. model=title_aided_config["model"],
  71. messages=[
  72. {'role': 'user', 'content': title_optimize_prompt}],
  73. temperature=0.7,
  74. stream=True,
  75. )
  76. content_pieces = []
  77. for chunk in completion:
  78. if chunk.choices:
  79. content_pieces.append(chunk.choices[0].delta.content)
  80. content = "".join(content_pieces)
  81. # logger.info(f"Title completion: {content}")
  82. if "</think>" in content:
  83. idx = content.index("</think>") + len("</think>")
  84. content = content[idx:].strip()
  85. import json_repair
  86. dict_completion = json_repair.loads(content)
  87. dict_completion = {int(k): int(v) for k, v in dict_completion.items()}
  88. # logger.info(f"len(dict_completion): {len(dict_completion)}, len(title_dict): {len(title_dict)}")
  89. if len(dict_completion) == len(title_dict):
  90. for i, origin_title_block in enumerate(origin_title_list):
  91. origin_title_block["level"] = int(dict_completion[i])
  92. break
  93. else:
  94. logger.warning(
  95. "The number of titles in the optimized result is not equal to the number of titles in the input.")
  96. retry_count += 1
  97. except Exception as e:
  98. logger.exception(e)
  99. retry_count += 1
  100. if dict_completion is None:
  101. logger.error("Failed to decode dict after maximum retries.")