From a360cd7e74f4cd20af6a677ef71c51ed33a6ba62 Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 15:24:01 +0800 Subject: [PATCH 1/7] =?UTF-8?q?feat(=E6=94=AF=E6=8C=81rar=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E4=B8=8E7z=E6=A0=BC=E5=BC=8F=E8=A7=A3=E5=8E=8B)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 11 ++++-- toolbox.py | 91 +++++++++++++++++++++++++++++++++++------------- 2 files changed, 76 insertions(+), 26 deletions(-) diff --git a/requirements.txt b/requirements.txt index 84ced64..3f39924 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,10 @@ gradio>=3.23 -requests[socks] -mdtex2html +requests[socks]~=2.28.2 +mdtex2html~=1.2.0 + +markdown~=3.4.3 +latex2mathml~=3.75.1 +numpy~=1.21.6 + +rarfile~=4.0 +py7zr~=0.20.4 \ No newline at end of file diff --git a/toolbox.py b/toolbox.py index d96b3f6..899cca4 100644 --- a/toolbox.py +++ b/toolbox.py @@ -2,6 +2,7 @@ import markdown, mdtex2html, threading, importlib, traceback from show_math import convert as convert_math from functools import wraps + def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[], sys_prompt=''): """ 调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断 @@ -13,36 +14,43 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp # 多线程的时候,需要一个mutable结构在不同线程之间传递信息 # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息 mutable = [None, ''] + # multi-threading worker def mt(i_say, history): while True: try: - mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt) + mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history, + sys_prompt=sys_prompt) break except ConnectionAbortedError as e: if len(history) > 0: - history = [his[len(his)//2:] for his in history if his is not None] + history = [his[len(his) // 2:] for his in history if his is not None] mutable[1] = 'Warning! History conversation is too long, cut into half. ' else: - i_say = i_say[:len(i_say)//2] + i_say = i_say[:len(i_say) // 2] mutable[1] = 'Warning! Input file is too long, cut into half. ' except TimeoutError as e: mutable[0] = '[Local Message] Failed with timeout.' raise TimeoutError + # 创建新线程发出http请求 - thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start() + thread_name = threading.Thread(target=mt, args=(i_say, history)); + thread_name.start() # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成 cnt = 0 while thread_name.is_alive(): cnt += 1 - chatbot[-1] = (i_say_show_user, f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt%4))) + chatbot[-1] = (i_say_show_user, + f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS * 2 * (MAX_RETRY + 1)}" + ''.join( + ['.'] * (cnt % 4))) yield chatbot, history, '正常' time.sleep(1) # 把gpt的输出从mutable中取出来 gpt_say = mutable[0] - if gpt_say=='[Local Message] Failed with timeout.': raise TimeoutError + if gpt_say == '[Local Message] Failed with timeout.': raise TimeoutError return gpt_say + def write_results_to_file(history, file_name=None): """ 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。 @@ -52,16 +60,17 @@ def write_results_to_file(history, file_name=None): # file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md' file_name = 'chatGPT分析报告' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md' os.makedirs('./gpt_log/', exist_ok=True) - with open(f'./gpt_log/{file_name}', 'w', encoding = 'utf8') as f: + with open(f'./gpt_log/{file_name}', 'w', encoding='utf8') as f: f.write('# chatGPT 分析报告\n') for i, content in enumerate(history): - if i%2==0: f.write('## ') + if i % 2 == 0: f.write('## ') f.write(content) f.write('\n\n') res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}') print(res) return res + def regular_txt_to_markdown(text): """ 将普通文本转换为Markdown格式的文本。 @@ -71,10 +80,12 @@ def regular_txt_to_markdown(text): text = text.replace('\n\n\n', '\n\n') return text + def CatchException(f): """ 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。 """ + @wraps(f) def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT): try: @@ -84,16 +95,21 @@ def CatchException(f): from toolbox import get_conf proxies, = get_conf('proxies') tb_str = regular_txt_to_markdown(traceback.format_exc()) - chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}") + chatbot[-1] = ( + chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}") yield chatbot, history, f'异常 {e}' + return decorated + def report_execption(chatbot, history, a, b): """ 向chatbot中添加错误信息 """ chatbot.append((a, b)) - history.append(a); history.append(b) + history.append(a); + history.append(b) + def text_divide_paragraph(text): """ @@ -110,15 +126,16 @@ def text_divide_paragraph(text): text = "
".join(lines) return text + def markdown_convertion(txt): """ 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。 """ if ('$' in txt) and ('```' not in txt): - return markdown.markdown(txt,extensions=['fenced_code','tables']) + '

' + \ - markdown.markdown(convert_math(txt, splitParagraphs=False),extensions=['fenced_code','tables']) + return markdown.markdown(txt, extensions=['fenced_code', 'tables']) + '

' + \ + markdown.markdown(convert_math(txt, splitParagraphs=False), extensions=['fenced_code', 'tables']) else: - return markdown.markdown(txt,extensions=['fenced_code','tables']) + return markdown.markdown(txt, extensions=['fenced_code', 'tables']) def format_io(self, y): @@ -127,9 +144,9 @@ def format_io(self, y): """ if y is None or y == []: return [] i_ask, gpt_reply = y[-1] - i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波 + i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波 y[-1] = ( - None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code','tables']), + None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code', 'tables']), None if gpt_reply is None else markdown_convertion(gpt_reply) ) return y @@ -151,6 +168,7 @@ def extract_archive(file_path, dest_dir): import zipfile import tarfile import os + # Get the file extension of the input file file_extension = os.path.splitext(file_path)[1] @@ -164,9 +182,28 @@ def extract_archive(file_path, dest_dir): with tarfile.open(file_path, 'r:*') as tarobj: tarobj.extractall(path=dest_dir) print("Successfully extracted tar archive to {}".format(dest_dir)) + + elif file_extension == '.rar': + # 这是个第三方库,需要预先pip install rarfile + # 此外,Windows上还需要安装winrar软件,配置其Path环境变量,如"C:\Program Files\WinRAR"才可以正常运行 + try: + import rarfile + with rarfile.RarFile(file_path) as rf: + rf.extractall(path=dest_dir) + print("Successfully extracted rar archive to {}".format(dest_dir)) + except: + print("rar格式需要安装额外依赖") + elif file_extension == '.7z': + try: + import py7zr + with py7zr.SevenZipFile(file_path, mode='r') as f: + f.extractall(path=dest_dir) + except: + print("7z格式需要安装额外依赖") else: return + def find_recent_files(directory): """ me: find files that is created with in one minutes under a directory with python, write a function @@ -193,19 +230,21 @@ def on_file_uploaded(files, chatbot, txt): if len(files) == 0: return chatbot, txt import shutil, os, time, glob from toolbox import extract_archive - try: shutil.rmtree('./private_upload/') - except: pass + try: + shutil.rmtree('./private_upload/') + except: + pass time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) os.makedirs(f'private_upload/{time_tag}', exist_ok=True) for file in files: file_origin_name = os.path.basename(file.orig_name) shutil.copy(file.name, f'private_upload/{time_tag}/{file_origin_name}') - extract_archive(f'private_upload/{time_tag}/{file_origin_name}', + extract_archive(f'private_upload/{time_tag}/{file_origin_name}', dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract') moved_files = [fp for fp in glob.glob('private_upload/**/*', recursive=True)] txt = f'private_upload/{time_tag}' moved_files_str = '\t\n\n'.join(moved_files) - chatbot.append(['我上传了文件,请查收', + chatbot.append(['我上传了文件,请查收', f'[Local Message] 收到以下文件: \n\n{moved_files_str}\n\n调用路径参数已自动修正到: \n\n{txt}\n\n现在您点击任意实验功能时,以上文件将被作为输入参数']) return chatbot, txt @@ -218,21 +257,25 @@ def on_report_generated(files, chatbot): chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。']) return report_files, chatbot + def get_conf(*args): # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到 res = [] for arg in args: - try: r = getattr(importlib.import_module('config_private'), arg) - except: r = getattr(importlib.import_module('config'), arg) + try: + r = getattr(importlib.import_module('config_private'), arg) + except: + r = getattr(importlib.import_module('config'), arg) res.append(r) # 在读取API_KEY时,检查一下是不是忘了改config - if arg=='API_KEY' and len(r) != 51: + if arg == 'API_KEY' and len(r) != 51: assert False, "正确的API_KEY密钥是51位,请在config文件中修改API密钥, 添加海外代理之后再运行。" + \ - "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)" + "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)" return res + def clear_line_break(txt): txt = txt.replace('\n', ' ') txt = txt.replace(' ', ' ') txt = txt.replace(' ', ' ') - return txt \ No newline at end of file + return txt From e470ee1f7f7d82a1f5dfbf12701402c6c41f3b3b Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 15:45:58 +0800 Subject: [PATCH 2/7] =?UTF-8?q?feat(toolbox):=20=E6=94=AF=E6=8C=81rar?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=B8=8E7z=E6=A0=BC=E5=BC=8F=E8=A7=A3?= =?UTF-8?q?=E5=8E=8B=EF=BC=8C=E4=BF=AE=E6=94=B9=E4=BA=86=E4=B8=8B=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py | 1 + toolbox.py | 2 ++ 2 files changed, 3 insertions(+) diff --git a/config.py b/config.py index a513f44..b445fa7 100644 --- a/config.py +++ b/config.py @@ -14,6 +14,7 @@ if USE_PROXY: # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284) proxies = { "http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", } + print('网络代理状态:运行。') else: proxies = None diff --git a/toolbox.py b/toolbox.py index 899cca4..43fafd3 100644 --- a/toolbox.py +++ b/toolbox.py @@ -193,11 +193,13 @@ def extract_archive(file_path, dest_dir): print("Successfully extracted rar archive to {}".format(dest_dir)) except: print("rar格式需要安装额外依赖") + elif file_extension == '.7z': try: import py7zr with py7zr.SevenZipFile(file_path, mode='r') as f: f.extractall(path=dest_dir) + print("Successfully extracted 7z archive to {}".format(dest_dir)) except: print("7z格式需要安装额外依赖") else: From d57d529aa1f92d37d48511e1333e854e8a9fed56 Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 15:47:18 +0800 Subject: [PATCH 3/7] =?UTF-8?q?feat(toolbox):=20=E6=94=AF=E6=8C=81rar?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=B8=8E7z=E6=A0=BC=E5=BC=8F=E8=A7=A3?= =?UTF-8?q?=E5=8E=8B=EF=BC=8C=E4=BF=AE=E6=94=B9=E4=BA=86=E4=B8=8B=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- toolbox.py | 1 + 1 file changed, 1 insertion(+) diff --git a/toolbox.py b/toolbox.py index 43fafd3..3813709 100644 --- a/toolbox.py +++ b/toolbox.py @@ -202,6 +202,7 @@ def extract_archive(file_path, dest_dir): print("Successfully extracted 7z archive to {}".format(dest_dir)) except: print("7z格式需要安装额外依赖") + else: return From 6d8c8cd3f0b9d2b6fe8d412b83f902cbd43fa0bd Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 15:48:00 +0800 Subject: [PATCH 4/7] =?UTF-8?q?feat(toolbox):=20=E6=94=AF=E6=8C=81rar?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=B8=8E7z=E6=A0=BC=E5=BC=8F=E8=A7=A3?= =?UTF-8?q?=E5=8E=8B=EF=BC=8C=E4=BF=AE=E6=94=B9=E4=BA=86=E4=B8=8B=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.py | 1 - 1 file changed, 1 deletion(-) diff --git a/config.py b/config.py index b445fa7..a513f44 100644 --- a/config.py +++ b/config.py @@ -14,7 +14,6 @@ if USE_PROXY: # 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284) proxies = { "http": "socks5h://localhost:11284", "https": "socks5h://localhost:11284", } - print('网络代理状态:运行。') else: proxies = None From 80e0c4e388dbaf39033819815ba57098c799801a Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 15:48:55 +0800 Subject: [PATCH 5/7] =?UTF-8?q?feat(toolbox):=20=E6=94=AF=E6=8C=81rar?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E4=B8=8E7z=E6=A0=BC=E5=BC=8F=E8=A7=A3?= =?UTF-8?q?=E5=8E=8B=EF=BC=8C=E4=BF=AE=E6=94=B9=E4=BA=86=E4=B8=8B=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- toolbox.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/toolbox.py b/toolbox.py index 3813709..968ca60 100644 --- a/toolbox.py +++ b/toolbox.py @@ -185,7 +185,7 @@ def extract_archive(file_path, dest_dir): elif file_extension == '.rar': # 这是个第三方库,需要预先pip install rarfile - # 此外,Windows上还需要安装winrar软件,配置其Path环境变量,如"C:\Program Files\WinRAR"才可以正常运行 + # 此外,Windows上还需要安装winrar软件,配置其Path环境变量,如"C:\Program Files\WinRAR"才可以 try: import rarfile with rarfile.RarFile(file_path) as rf: From 44e77dc741dc434dd301e4f419ada512005c0a65 Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 20:28:15 +0800 Subject: [PATCH 6/7] =?UTF-8?q?feat(toolbox):=E8=B0=83=E6=95=B4=E4=BA=86?= =?UTF-8?q?=E7=A9=BA=E6=A0=BC=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- requirements.txt | 11 ++----- toolbox.py | 78 +++++++++++++++++------------------------------- 2 files changed, 29 insertions(+), 60 deletions(-) diff --git a/requirements.txt b/requirements.txt index 3f39924..265a3cb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,10 +1,3 @@ gradio>=3.23 -requests[socks]~=2.28.2 -mdtex2html~=1.2.0 - -markdown~=3.4.3 -latex2mathml~=3.75.1 -numpy~=1.21.6 - -rarfile~=4.0 -py7zr~=0.20.4 \ No newline at end of file +requests[socks] +mdtex2html \ No newline at end of file diff --git a/toolbox.py b/toolbox.py index 968ca60..30399de 100644 --- a/toolbox.py +++ b/toolbox.py @@ -2,7 +2,6 @@ import markdown, mdtex2html, threading, importlib, traceback from show_math import convert as convert_math from functools import wraps - def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[], sys_prompt=''): """ 调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断 @@ -14,43 +13,36 @@ def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temp # 多线程的时候,需要一个mutable结构在不同线程之间传递信息 # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息 mutable = [None, ''] - # multi-threading worker def mt(i_say, history): while True: try: - mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history, - sys_prompt=sys_prompt) + mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt) break except ConnectionAbortedError as e: if len(history) > 0: - history = [his[len(his) // 2:] for his in history if his is not None] + history = [his[len(his)//2:] for his in history if his is not None] mutable[1] = 'Warning! History conversation is too long, cut into half. ' else: - i_say = i_say[:len(i_say) // 2] + i_say = i_say[:len(i_say)//2] mutable[1] = 'Warning! Input file is too long, cut into half. ' except TimeoutError as e: mutable[0] = '[Local Message] Failed with timeout.' raise TimeoutError - # 创建新线程发出http请求 - thread_name = threading.Thread(target=mt, args=(i_say, history)); - thread_name.start() + thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start() # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成 cnt = 0 while thread_name.is_alive(): cnt += 1 - chatbot[-1] = (i_say_show_user, - f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS * 2 * (MAX_RETRY + 1)}" + ''.join( - ['.'] * (cnt % 4))) + chatbot[-1] = (i_say_show_user, f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt%4))) yield chatbot, history, '正常' time.sleep(1) # 把gpt的输出从mutable中取出来 gpt_say = mutable[0] - if gpt_say == '[Local Message] Failed with timeout.': raise TimeoutError + if gpt_say=='[Local Message] Failed with timeout.': raise TimeoutError return gpt_say - def write_results_to_file(history, file_name=None): """ 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。 @@ -60,17 +52,16 @@ def write_results_to_file(history, file_name=None): # file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md' file_name = 'chatGPT分析报告' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md' os.makedirs('./gpt_log/', exist_ok=True) - with open(f'./gpt_log/{file_name}', 'w', encoding='utf8') as f: + with open(f'./gpt_log/{file_name}', 'w', encoding = 'utf8') as f: f.write('# chatGPT 分析报告\n') for i, content in enumerate(history): - if i % 2 == 0: f.write('## ') + if i%2==0: f.write('## ') f.write(content) f.write('\n\n') res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}') print(res) return res - def regular_txt_to_markdown(text): """ 将普通文本转换为Markdown格式的文本。 @@ -80,12 +71,10 @@ def regular_txt_to_markdown(text): text = text.replace('\n\n\n', '\n\n') return text - def CatchException(f): """ 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。 """ - @wraps(f) def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT): try: @@ -95,21 +84,16 @@ def CatchException(f): from toolbox import get_conf proxies, = get_conf('proxies') tb_str = regular_txt_to_markdown(traceback.format_exc()) - chatbot[-1] = ( - chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}") + chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}") yield chatbot, history, f'异常 {e}' - return decorated - def report_execption(chatbot, history, a, b): """ 向chatbot中添加错误信息 """ chatbot.append((a, b)) - history.append(a); - history.append(b) - + history.append(a); history.append(b) def text_divide_paragraph(text): """ @@ -126,16 +110,15 @@ def text_divide_paragraph(text): text = "
".join(lines) return text - def markdown_convertion(txt): """ 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。 """ if ('$' in txt) and ('```' not in txt): - return markdown.markdown(txt, extensions=['fenced_code', 'tables']) + '

' + \ - markdown.markdown(convert_math(txt, splitParagraphs=False), extensions=['fenced_code', 'tables']) + return markdown.markdown(txt,extensions=['fenced_code','tables']) + '

' + \ + markdown.markdown(convert_math(txt, splitParagraphs=False),extensions=['fenced_code','tables']) else: - return markdown.markdown(txt, extensions=['fenced_code', 'tables']) + return markdown.markdown(txt,extensions=['fenced_code','tables']) def format_io(self, y): @@ -144,9 +127,9 @@ def format_io(self, y): """ if y is None or y == []: return [] i_ask, gpt_reply = y[-1] - i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波 + i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波 y[-1] = ( - None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code', 'tables']), + None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code','tables']), None if gpt_reply is None else markdown_convertion(gpt_reply) ) return y @@ -168,7 +151,6 @@ def extract_archive(file_path, dest_dir): import zipfile import tarfile import os - # Get the file extension of the input file file_extension = os.path.splitext(file_path)[1] @@ -183,17 +165,18 @@ def extract_archive(file_path, dest_dir): tarobj.extractall(path=dest_dir) print("Successfully extracted tar archive to {}".format(dest_dir)) + # 第三方库,需要预先pip install rarfile + # 此外,Windows上还需要安装winrar软件,配置其Path环境变量,如"C:\Program Files\WinRAR"才可以 elif file_extension == '.rar': - # 这是个第三方库,需要预先pip install rarfile - # 此外,Windows上还需要安装winrar软件,配置其Path环境变量,如"C:\Program Files\WinRAR"才可以 try: import rarfile with rarfile.RarFile(file_path) as rf: rf.extractall(path=dest_dir) print("Successfully extracted rar archive to {}".format(dest_dir)) except: - print("rar格式需要安装额外依赖") + print("Rar format requires additional dependencies to install") + # 第三方库,需要预先pip install py7zr elif file_extension == '.7z': try: import py7zr @@ -201,12 +184,11 @@ def extract_archive(file_path, dest_dir): f.extractall(path=dest_dir) print("Successfully extracted 7z archive to {}".format(dest_dir)) except: - print("7z格式需要安装额外依赖") + print("7z format requires additional dependencies to install") else: return - def find_recent_files(directory): """ me: find files that is created with in one minutes under a directory with python, write a function @@ -233,10 +215,8 @@ def on_file_uploaded(files, chatbot, txt): if len(files) == 0: return chatbot, txt import shutil, os, time, glob from toolbox import extract_archive - try: - shutil.rmtree('./private_upload/') - except: - pass + try: shutil.rmtree('./private_upload/') + except: pass time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) os.makedirs(f'private_upload/{time_tag}', exist_ok=True) for file in files: @@ -260,25 +240,21 @@ def on_report_generated(files, chatbot): chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。']) return report_files, chatbot - def get_conf(*args): # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到 res = [] for arg in args: - try: - r = getattr(importlib.import_module('config_private'), arg) - except: - r = getattr(importlib.import_module('config'), arg) + try: r = getattr(importlib.import_module('config_private'), arg) + except: r = getattr(importlib.import_module('config'), arg) res.append(r) # 在读取API_KEY时,检查一下是不是忘了改config - if arg == 'API_KEY' and len(r) != 51: + if arg=='API_KEY' and len(r) != 51: assert False, "正确的API_KEY密钥是51位,请在config文件中修改API密钥, 添加海外代理之后再运行。" + \ - "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)" + "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)" return res - def clear_line_break(txt): txt = txt.replace('\n', ' ') txt = txt.replace(' ', ' ') txt = txt.replace(' ', ' ') - return txt + return txt \ No newline at end of file From ac4fce05cfab8d9d2671aca6b1323ee04327927c Mon Sep 17 00:00:00 2001 From: JasonGuo1 <1515893624@qq.com> Date: Thu, 30 Mar 2023 23:23:41 +0800 Subject: [PATCH 7/7] =?UTF-8?q?feat(=E6=80=BB=E7=BB=93word=E6=96=87?= =?UTF-8?q?=E6=A1=A3):=E5=A2=9E=E5=8A=A0=E8=AF=BB=E5=8F=96docx=E3=80=81doc?= =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E7=9A=84=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crazy_functions/总结word文档.py | 123 ++++++++++++++++++++++++++++++++ functional_crazy.py | 4 ++ 2 files changed, 127 insertions(+) create mode 100644 crazy_functions/总结word文档.py diff --git a/crazy_functions/总结word文档.py b/crazy_functions/总结word文档.py new file mode 100644 index 0000000..b7cef5b --- /dev/null +++ b/crazy_functions/总结word文档.py @@ -0,0 +1,123 @@ +from predict import predict_no_ui +from toolbox import CatchException, report_execption, write_results_to_file, predict_no_ui_but_counting_down +fast_debug = False + + +def 解析docx(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt): + import time, os + # pip install python-docx 用于docx格式,跨平台 + # pip install pywin32 用于doc格式,仅支持Win平台 + + print('begin analysis on:', file_manifest) + for index, fp in enumerate(file_manifest): + if fp.split(".")[-1] == "docx": + from docx import Document + doc = Document(fp) + file_content = "\n".join([para.text for para in doc.paragraphs]) + else: + import win32com.client + word = win32com.client.Dispatch("Word.Application") + word.visible = False + # 打开文件 + print('fp', os.getcwd()) + doc = word.Documents.Open(os.getcwd() + '/' + fp) + # file_content = doc.Content.Text + doc = word.ActiveDocument + file_content = doc.Range().Text + doc.Close() + word.Quit() + + print(file_content) + + prefix = "接下来请你逐文件分析下面的论文文件," if index == 0 else "" + # private_upload里面的文件名在解压zip后容易出现乱码(rar和7z格式正常),故可以只分析文章内容,不输入文件名 + i_say = prefix + f'请对下面的文章片段用中英文做概述,文件名是{os.path.relpath(fp, project_folder)},' \ + f'文章内容是 ```{file_content}```' + i_say_show_user = prefix + f'[{index+1}/{len(file_manifest)}] 假设你是论文审稿专家,请对下面的文章片段做概述: {os.path.abspath(fp)}' + chatbot.append((i_say_show_user, "[Local Message] waiting gpt response.")) + yield chatbot, history, '正常' + + if not fast_debug: + msg = '正常' + # ** gpt request ** + gpt_say = yield from predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, + history=[]) # 带超时倒计时 + chatbot[-1] = (i_say_show_user, gpt_say) + history.append(i_say_show_user); + history.append(gpt_say) + yield chatbot, history, msg + if not fast_debug: time.sleep(2) + + """ + # 可按需启用 + i_say = f'根据你上述的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一篇英文的。' + chatbot.append((i_say, "[Local Message] waiting gpt response.")) + yield chatbot, history, '正常' + + + i_say = f'我想让你做一个论文写作导师。您的任务是使用人工智能工具(例如自然语言处理)提供有关如何改进其上述文章的反馈。' \ + f'您还应该利用您在有效写作技巧方面的修辞知识和经验来建议作者可以更好地以书面形式表达他们的想法和想法的方法。' \ + f'根据你之前的分析,提出建议' + chatbot.append((i_say, "[Local Message] waiting gpt response.")) + yield chatbot, history, '正常' + + """ + + if not fast_debug: + msg = '正常' + # ** gpt request ** + gpt_say = yield from predict_no_ui_but_counting_down(i_say, i_say, chatbot, top_p, temperature, + history=history) # 带超时倒计时 + + chatbot[-1] = (i_say, gpt_say) + history.append(i_say) + history.append(gpt_say) + yield chatbot, history, msg + res = write_results_to_file(history) + chatbot.append(("完成了吗?", res)) + yield chatbot, history, msg + + +@CatchException +def 总结word文档(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT): + import glob, os + + yield chatbot, history, '正常' + + # 尝试导入依赖,如果缺少依赖,则给出安装建议 + try: + from docx import Document + except: + report_execption(chatbot, history, + a=f"解析项目: {txt}", + b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pymupdf```。") + yield chatbot, history, '正常' + return + + # 清空历史,以免输入溢出 + history = [] + + # 检测输入参数,如没有给定输入参数,直接退出 + if os.path.exists(txt): + project_folder = txt + else: + if txt == "": txt = '空空如也的输入栏' + report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到本地项目或无权访问: {txt}") + yield chatbot, history, '正常' + return + + # 搜索需要处理的文件清单 + file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.docx', recursive=True)] + \ + [f for f in glob.glob(f'{project_folder}/**/*.doc', recursive=True)] + # [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \ + # [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \ + # [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)] + + # 如果没找到任何文件 + if len(file_manifest) == 0: + report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到任何.docx或doc文件: {txt}") + yield chatbot, history, '正常' + return + + # 开始正式执行任务 + yield from 解析docx(file_manifest, project_folder, top_p, temperature, chatbot, history, systemPromptTxt) diff --git a/functional_crazy.py b/functional_crazy.py index 3f13853..5bab039 100644 --- a/functional_crazy.py +++ b/functional_crazy.py @@ -13,6 +13,7 @@ def get_crazy_functionals(): from crazy_functions.解析项目源代码 import 解析一个C项目 from crazy_functions.高级功能函数模板 import 高阶功能模板函数 from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文 + from crazy_functions.总结word文档 import 总结word文档 function_plugins = { "请解析并解构此项目本身": { @@ -44,6 +45,9 @@ def get_crazy_functionals(): "[函数插件模板demo] 历史上的今天": { "Function": 高阶功能模板函数 }, + "[总结word文档demo] 解析word文档": { + "Function": 总结word文档 + }, } # VisibleLevel=1 经过测试,但功能未达到理想状态