fufa/chatgpt
0
1import markdown, mdtex2html, threading, importlib, traceback2from show_math import convert as convert_math3from functools import wraps4 5def predict_no_ui_but_counting_down(i_say, i_say_show_user, chatbot, top_p, temperature, history=[], sys_prompt=''):6 """7 调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断8 """9 import time10 from predict import predict_no_ui11 from toolbox import get_conf12 TIMEOUT_SECONDS, MAX_RETRY = get_conf('TIMEOUT_SECONDS', 'MAX_RETRY')13 # 多线程的时候,需要一个mutable结构在不同线程之间传递信息14 # list就是最简单的mutable结构,我们第一个位置放gpt输出,第二个位置传递报错信息15 mutable = [None, '']16 # multi-threading worker17 def mt(i_say, history):18 while True:19 try:20 mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history, sys_prompt=sys_prompt)21 break22 except ConnectionAbortedError as e:23 if len(history) > 0:24 history = [his[len(his)//2:] for his in history if his is not None]25 mutable[1] = 'Warning! History conversation is too long, cut into half. '26 else:27 i_say = i_say[:len(i_say)//2]28 mutable[1] = 'Warning! Input file is too long, cut into half. '29 except TimeoutError as e:30 mutable[0] = '[Local Message] Failed with timeout.'31 raise TimeoutError32 # 创建新线程发出http请求33 thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start()34 # 原来的线程则负责持续更新UI,实现一个超时倒计时,并等待新线程的任务完成35 cnt = 036 while thread_name.is_alive():37 cnt += 138 chatbot[-1] = (i_say_show_user, f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt%4)))39 yield chatbot, history, '正常'40 time.sleep(1)41 # 把gpt的输出从mutable中取出来42 gpt_say = mutable[0]43 if gpt_say=='[Local Message] Failed with timeout.': raise TimeoutError44 return gpt_say45 46def write_results_to_file(history, file_name=None):47 """48 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。49 """50 import os, time51 if file_name is None:52 # file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'53 file_name = 'chatGPT分析报告' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'54 os.makedirs('./gpt_log/', exist_ok=True)55 with open(f'./gpt_log/{file_name}', 'w', encoding = 'utf8') as f:56 f.write('# chatGPT 分析报告\n')57 for i, content in enumerate(history):58 if i%2==0: f.write('## ')59 f.write(content)60 f.write('\n\n')61 res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}')62 print(res)63 return res64 65def regular_txt_to_markdown(text):66 """67 将普通文本转换为Markdown格式的文本。68 """69 text = text.replace('\n', '\n\n')70 text = text.replace('\n\n\n', '\n\n')71 text = text.replace('\n\n\n', '\n\n')72 return text73 74def CatchException(f):75 """76 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。77 """78 @wraps(f)79 def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):80 try:81 yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)82 except Exception as e:83 from check_proxy import check_proxy84 from toolbox import get_conf85 proxies, = get_conf('proxies')86 tb_str = regular_txt_to_markdown(traceback.format_exc())87 chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}")88 yield chatbot, history, f'异常 {e}'89 return decorated90 91def report_execption(chatbot, history, a, b):92 """93 向chatbot中添加错误信息94 """95 chatbot.append((a, b))96 history.append(a); history.append(b)97 98def text_divide_paragraph(text):99 """100 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。101 """102 if '```' in text:103 # careful input104 return text105 else:106 # wtf input107 lines = text.split("\n")108 for i, line in enumerate(lines):109 lines[i] = lines[i].replace(" ", " ")110 text = "</br>".join(lines)111 return text112 113def markdown_convertion(txt):114 """115 将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。116 """117 if ('$' in txt) and ('```' not in txt):118 return markdown.markdown(txt,extensions=['fenced_code','tables']) + '<br><br>' + \119 markdown.markdown(convert_math(txt, splitParagraphs=False),extensions=['fenced_code','tables'])120 else:121 return markdown.markdown(txt,extensions=['fenced_code','tables'])122 123 124def format_io(self, y):125 """126 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。127 """128 if y is None or y == []: return []129 i_ask, gpt_reply = y[-1]130 i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波131 y[-1] = (132 None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code','tables']),133 None if gpt_reply is None else markdown_convertion(gpt_reply)134 )135 return y136 137 138def find_free_port():139 """140 返回当前系统中可用的未使用端口。141 """142 import socket143 from contextlib import closing144 with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:145 s.bind(('', 0))146 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)147 return s.getsockname()[1]148 149 150def extract_archive(file_path, dest_dir):151 import zipfile152 import tarfile153 import os154 # Get the file extension of the input file155 file_extension = os.path.splitext(file_path)[1]156 157 # Extract the archive based on its extension158 if file_extension == '.zip':159 with zipfile.ZipFile(file_path, 'r') as zipobj:160 zipobj.extractall(path=dest_dir)161 print("Successfully extracted zip archive to {}".format(dest_dir))162 163 elif file_extension in ['.tar', '.gz', '.bz2']:164 with tarfile.open(file_path, 'r:*') as tarobj:165 tarobj.extractall(path=dest_dir)166 print("Successfully extracted tar archive to {}".format(dest_dir))167 else:168 return169 170def find_recent_files(directory):171 """172 me: find files that is created with in one minutes under a directory with python, write a function173 gpt: here it is!174 """175 import os176 import time177 current_time = time.time()178 one_minute_ago = current_time - 60179 recent_files = []180 181 for filename in os.listdir(directory):182 file_path = os.path.join(directory, filename)183 if file_path.endswith('.log'): continue184 created_time = os.path.getctime(file_path)185 if created_time >= one_minute_ago:186 if os.path.isdir(file_path): continue187 recent_files.append(file_path)188 189 return recent_files190 191 192def on_file_uploaded(files, chatbot, txt):193 if len(files) == 0: return chatbot, txt194 import shutil, os, time, glob195 from toolbox import extract_archive196 try: shutil.rmtree('./private_upload/')197 except: pass198 time_tag = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())199 os.makedirs(f'private_upload/{time_tag}', exist_ok=True)200 for file in files:201 file_origin_name = os.path.basename(file.orig_name)202 shutil.copy(file.name, f'private_upload/{time_tag}/{file_origin_name}')203 extract_archive(f'private_upload/{time_tag}/{file_origin_name}', 204 dest_dir=f'private_upload/{time_tag}/{file_origin_name}.extract')205 moved_files = [fp for fp in glob.glob('private_upload/**/*', recursive=True)]206 txt = f'private_upload/{time_tag}'207 moved_files_str = '\t\n\n'.join(moved_files)208 chatbot.append(['我上传了文件,请查收', 209 f'[Local Message] 收到以下文件: \n\n{moved_files_str}\n\n调用路径参数已自动修正到: \n\n{txt}\n\n现在您点击任意实验功能时,以上文件将被作为输入参数'])210 return chatbot, txt211 212 213def on_report_generated(files, chatbot):214 from toolbox import find_recent_files215 report_files = find_recent_files('gpt_log')216 if len(report_files) == 0: return report_files, chatbot217 # files.extend(report_files)218 chatbot.append(['汇总报告如何远程获取?', '汇总报告已经添加到右侧文件上传区,请查收。'])219 return report_files, chatbot220 221def get_conf(*args):222 # 建议您复制一个config_private.py放自己的秘密, 如API和代理网址, 避免不小心传github被别人看到223 res = []224 for arg in args:225 try: r = getattr(importlib.import_module('config_private'), arg)226 except: r = getattr(importlib.import_module('config'), arg)227 res.append(r)228 # 在读取API_KEY时,检查一下是不是忘了改config229 if arg=='API_KEY' and len(r) != 51:230 assert False, "正确的API_KEY密钥是51位,请在config文件中修改API密钥, 添加海外代理之后再运行。" + \231 "(如果您刚更新过代码,请确保旧版config_private文件中没有遗留任何新增键值)"232 return res233 234def clear_line_break(txt):235 txt = txt.replace('\n', ' ')236 txt = txt.replace(' ', ' ')237 txt = txt.replace(' ', ' ')238 return txt