binary-husky commited on
Commit
149ef28
2 Parent(s): 87c0936 16caf34

Merge pull request #174 from Euclid-Jie/Euclid_Test

Browse files
crazy_functions/批量总结PDF文档pdfminer.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from predict import predict_no_ui
2
+ from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down
3
+
4
+ fast_debug = False
5
+
6
+ def readPdf(pdfPath):
7
+ """
8
+ 读取pdf文件,返回文本内容
9
+ """
10
+ import pdfminer
11
+ from pdfminer.pdfparser import PDFParser
12
+ from pdfminer.pdfdocument import PDFDocument
13
+ from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
14
+ from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
15
+ from pdfminer.pdfdevice import PDFDevice
16
+ from pdfminer.layout import LAParams
17
+ from pdfminer.converter import PDFPageAggregator
18
+
19
+ fp = open(pdfPath, 'rb')
20
+
21
+ # Create a PDF parser object associated with the file object
22
+ parser = PDFParser(fp)
23
+
24
+ # Create a PDF document object that stores the document structure.
25
+ # Password for initialization as 2nd parameter
26
+ document = PDFDocument(parser)
27
+ # Check if the document allows text extraction. If not, abort.
28
+ if not document.is_extractable:
29
+ raise PDFTextExtractionNotAllowed
30
+
31
+ # Create a PDF resource manager object that stores shared resources.
32
+ rsrcmgr = PDFResourceManager()
33
+
34
+ # Create a PDF device object.
35
+ # device = PDFDevice(rsrcmgr)
36
+
37
+ # BEGIN LAYOUT ANALYSIS.
38
+ # Set parameters for analysis.
39
+ laparams = LAParams(
40
+ char_margin=10.0,
41
+ line_margin=0.2,
42
+ boxes_flow=0.2,
43
+ all_texts=False,
44
+ )
45
+ # Create a PDF page aggregator object.
46
+ device = PDFPageAggregator(rsrcmgr, laparams=laparams)
47
+ # Create a PDF interpreter object.
48
+ interpreter = PDFPageInterpreter(rsrcmgr, device)
49
+
50
+ # loop over all pages in the document
51
+ outTextList = []
52
+ for page in PDFPage.create_pages(document):
53
+ # read the page into a layout object
54
+ interpreter.process_page(page)
55
+ layout = device.get_result()
56
+ for obj in layout._objs:
57
+ if isinstance(obj, pdfminer.layout.LTTextBoxHorizontal):
58
+ # print(obj.get_text())
59
+ outTextList.append(obj.get_text())
60
+
61
+ return outTextList
62
+
63
+
64
+ def 解析Paper(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt):
65
+ import time, glob, os
66
+ from bs4 import BeautifulSoup
67
+ print('begin analysis on:', file_manifest)
68
+ for index, fp in enumerate(file_manifest):
69
+ if ".tex" in fp:
70
+ with open(fp, 'r', encoding='utf-8') as f:
71
+ file_content = f.read()
72
+ if ".pdf" in fp.lower():
73
+ file_content = readPdf(fp)
74
+ file_content = BeautifulSoup(''.join(file_content), features="lxml").body.text.encode('gbk', 'ignore').decode('gbk')
75
+
76
+ prefix = "接下来请你逐文件分析下面的论文文件,概括其内容" if index==0 else ""
77
+ i_say = prefix + f'请对下面的文章片段用中文做一个概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{file_content}```'
78
+ i_say_show_user = prefix + f'[{index}/{len(file_manifest)}] 请对下面的文章片段做一个概述: {os.path.abspath(fp)}'
79
+ chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
80
+ print('[1] yield chatbot, history')
81
+ yield chatbot, history, '正常'
82
+
83
+ if not fast_debug:
84
+ msg = '正常'
85
+ # ** gpt request **
86
+ gpt_say = yield from predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[]) # 带超时倒计时
87
+
88
+ print('[2] end gpt req')
89
+ chatbot[-1] = (i_say_show_user, gpt_say)
90
+ history.append(i_say_show_user); history.append(gpt_say)
91
+ print('[3] yield chatbot, history')
92
+ yield chatbot, history, msg
93
+ print('[4] next')
94
+ if not fast_debug: time.sleep(2)
95
+
96
+ all_file = ', '.join([os.path.relpath(fp, project_folder) for index, fp in enumerate(file_manifest)])
97
+ i_say = f'根据以上你自己的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一段英文摘要(包括{all_file})。'
98
+ chatbot.append((i_say, "[Local Message] waiting gpt response."))
99
+ yield chatbot, history, '正常'
100
+
101
+ if not fast_debug:
102
+ msg = '正常'
103
+ # ** gpt request **
104
+ gpt_say = yield from predict_no_ui_but_counting_down(i_say, i_say, chatbot, top_p, temperature, history=history) # 带超时倒计时
105
+
106
+ chatbot[-1] = (i_say, gpt_say)
107
+ history.append(i_say); history.append(gpt_say)
108
+ yield chatbot, history, msg
109
+ res = write_results_to_file(history)
110
+ chatbot.append(("完成了吗?", res))
111
+ yield chatbot, history, msg
112
+
113
+
114
+
115
+ @CatchException
116
+ def 批量总结PDF文档pdfminer(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):
117
+ history = [] # 清空历史,以免输入溢出
118
+ import glob, os
119
+
120
+ # 基本信息:功能、贡献者
121
+ chatbot.append([
122
+ "函数插件功能?",
123
+ "批量总结PDF文档,此版本使用pdfminer插件,带token约简功能。函数插件贡献者: Euclid-Jie。"])
124
+ yield chatbot, history, '正常'
125
+
126
+ # 尝试导入依赖,如果缺少依赖,则给出安装建议
127
+ try:
128
+ import pdfminer, bs4
129
+ except:
130
+ report_execption(chatbot, history,
131
+ a = f"解析项目: {txt}",
132
+ b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pdfminer beautifulsoup4```。")
133
+ yield chatbot, history, '正常'
134
+ return
135
+ if os.path.exists(txt):
136
+ project_folder = txt
137
+ else:
138
+ if txt == "": txt = '空空如也的输入栏'
139
+ report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
140
+ yield chatbot, history, '正常'
141
+ return
142
+ file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \
143
+ [f for f in glob.glob(f'{project_folder}/**/*.pdf', recursive=True)] # + \
144
+ # [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
145
+ # [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
146
+ if len(file_manifest) == 0:
147
+ report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex或pdf文件: {txt}")
148
+ yield chatbot, history, '正常'
149
+ return
150
+ yield from 解析Paper(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt)
151
+
functional_crazy.py CHANGED
@@ -55,12 +55,17 @@ def get_crazy_functionals():
55
  # VisibleLevel=1 经过测试,但功能未达到理想状态
56
  if UserVisibleLevel >= 1:
57
  from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
 
58
  function_plugins.update({
59
  "[仅供开发调试] 批量总结PDF文档": {
60
  "Color": "stop",
61
  # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
62
  "Function": HotReload(批量总结PDF文档)
63
  },
 
 
 
 
64
  })
65
 
66
  # VisibleLevel=2 尚未充分测试的函数插件,放在这里
 
55
  # VisibleLevel=1 经过测试,但功能未达到理想状态
56
  if UserVisibleLevel >= 1:
57
  from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
58
+ from crazy_functions.批量总结PDF文档pdfminer import 批量总结PDF文档pdfminer
59
  function_plugins.update({
60
  "[仅供开发调试] 批量总结PDF文档": {
61
  "Color": "stop",
62
  # HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
63
  "Function": HotReload(批量总结PDF文档)
64
  },
65
+ "[仅供开发调试] 批量总结PDF文档pdfminer": {
66
+ "Color": "stop",
67
+ "Function": HotReload(批量总结PDF文档pdfminer)
68
+ },
69
  })
70
 
71
  # VisibleLevel=2 尚未充分测试的函数插件,放在这里
requirements.txt CHANGED
@@ -1,3 +1,5 @@
1
  gradio>=3.23
2
  requests[socks]
3
  mdtex2html
 
 
 
1
  gradio>=3.23
2
  requests[socks]
3
  mdtex2html
4
+ Markdown
5
+ latex2mathml