批量翻译PDF文档_NOUGAT.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. from toolbox import CatchException, report_exception, get_log_folder, gen_time_str
  2. from toolbox import update_ui, promote_file_to_downloadzone, update_ui_lastest_msg, disable_auto_promotion
  3. from toolbox import write_history_to_file, promote_file_to_downloadzone
  4. from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
  5. from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
  6. from .crazy_utils import read_and_clean_pdf_text
  7. from .pdf_fns.parse_pdf import parse_pdf, get_avail_grobid_url, translate_pdf
  8. from colorful import *
  9. import copy
  10. import os
  11. import math
  12. import logging
  13. def markdown_to_dict(article_content):
  14. import markdown
  15. from bs4 import BeautifulSoup
  16. cur_t = ""
  17. cur_c = ""
  18. results = {}
  19. for line in article_content:
  20. if line.startswith('#'):
  21. if cur_t!="":
  22. if cur_t not in results:
  23. results.update({cur_t:cur_c.lstrip('\n')})
  24. else:
  25. # 处理重名的章节
  26. results.update({cur_t + " " + gen_time_str():cur_c.lstrip('\n')})
  27. cur_t = line.rstrip('\n')
  28. cur_c = ""
  29. else:
  30. cur_c += line
  31. results_final = {}
  32. for k in list(results.keys()):
  33. if k.startswith('# '):
  34. results_final['title'] = k.split('# ')[-1]
  35. results_final['authors'] = results.pop(k).lstrip('\n')
  36. if k.startswith('###### Abstract'):
  37. results_final['abstract'] = results.pop(k).lstrip('\n')
  38. results_final_sections = []
  39. for k,v in results.items():
  40. results_final_sections.append({
  41. 'heading':k.lstrip("# "),
  42. 'text':v if len(v) > 0 else f"The beginning of {k.lstrip('# ')} section."
  43. })
  44. results_final['sections'] = results_final_sections
  45. return results_final
  46. @CatchException
  47. def 批量翻译PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
  48. disable_auto_promotion(chatbot)
  49. # 基本信息:功能、贡献者
  50. chatbot.append([
  51. "函数插件功能?",
  52. "批量翻译PDF文档。函数插件贡献者: Binary-Husky"])
  53. yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
  54. # 清空历史,以免输入溢出
  55. history = []
  56. from .crazy_utils import get_files_from_everything
  57. success, file_manifest, project_folder = get_files_from_everything(txt, type='.pdf')
  58. if len(file_manifest) > 0:
  59. # 尝试导入依赖,如果缺少依赖,则给出安装建议
  60. try:
  61. import nougat
  62. import tiktoken
  63. except:
  64. report_exception(chatbot, history,
  65. a=f"解析项目: {txt}",
  66. b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade nougat-ocr tiktoken```。")
  67. yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
  68. return
  69. success_mmd, file_manifest_mmd, _ = get_files_from_everything(txt, type='.mmd')
  70. success = success or success_mmd
  71. file_manifest += file_manifest_mmd
  72. chatbot.append(["文件列表:", ", ".join([e.split('/')[-1] for e in file_manifest])]);
  73. yield from update_ui( chatbot=chatbot, history=history)
  74. # 检测输入参数,如没有给定输入参数,直接退出
  75. if not success:
  76. if txt == "": txt = '空空如也的输入栏'
  77. # 如果没找到任何文件
  78. if len(file_manifest) == 0:
  79. report_exception(chatbot, history,
  80. a=f"解析项目: {txt}", b=f"找不到任何.pdf拓展名的文件: {txt}")
  81. yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
  82. return
  83. # 开始正式执行任务
  84. yield from 解析PDF_基于NOUGAT(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)
  85. def 解析PDF_基于NOUGAT(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt):
  86. import copy
  87. import tiktoken
  88. TOKEN_LIMIT_PER_FRAGMENT = 1024
  89. generated_conclusion_files = []
  90. generated_html_files = []
  91. DST_LANG = "中文"
  92. from crazy_functions.crazy_utils import nougat_interface
  93. from crazy_functions.pdf_fns.report_gen_html import construct_html
  94. nougat_handle = nougat_interface()
  95. for index, fp in enumerate(file_manifest):
  96. if fp.endswith('pdf'):
  97. chatbot.append(["当前进度:", f"正在解析论文,请稍候。(第一次运行时,需要花费较长时间下载NOUGAT参数)"]); yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
  98. fpp = yield from nougat_handle.NOUGAT_parse_pdf(fp, chatbot, history)
  99. promote_file_to_downloadzone(fpp, rename_file=os.path.basename(fpp)+'.nougat.mmd', chatbot=chatbot)
  100. else:
  101. chatbot.append(["当前论文无需解析:", fp]); yield from update_ui( chatbot=chatbot, history=history)
  102. fpp = fp
  103. with open(fpp, 'r', encoding='utf8') as f:
  104. article_content = f.readlines()
  105. article_dict = markdown_to_dict(article_content)
  106. logging.info(article_dict)
  107. yield from translate_pdf(article_dict, llm_kwargs, chatbot, fp, generated_conclusion_files, TOKEN_LIMIT_PER_FRAGMENT, DST_LANG)
  108. chatbot.append(("给出输出文件清单", str(generated_conclusion_files + generated_html_files)))
  109. yield from update_ui(chatbot=chatbot, history=history) # 刷新界面