import html import markdown import importlib import inspect import gradio as gr import func_box from latex2mathml.converter import convert as tex2mathml from functools import wraps, lru_cache import shutil import os import time import glob import sys import threading ############################### 插件输入输出接驳区 ####################################### pj = os.path.join """ ======================================================================== 第一部分 函数插件输入输出接驳区 - ChatBotWithCookies: 带Cookies的Chatbot类,为实现更多强大的功能做基础 - ArgsGeneralWrapper: 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构 - update_ui: 刷新界面用 yield from update_ui(chatbot, history) - CatchException: 将插件中出的所有问题显示在界面上 - HotReload: 实现插件的热更新 - trimmed_format_exc: 打印traceback,为了安全而隐藏绝对地址 ======================================================================== """ class ChatBotWithCookies(list): def __init__(self, cookie): self._cookies = cookie def write_list(self, list): for t in list: self.append(t) def get_list(self): return [t for t in self] def get_cookies(self): return self._cookies def ArgsGeneralWrapper(f): """ 装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。 """ def decorated(cookies, max_length, llm_model, txt, top_p, temperature, chatbot, history, system_prompt, models, plugin_advanced_arg, ipaddr: gr.Request, *args): """""" # 引入一个有cookie的chatbot start_time = time.time() encrypt, private = get_conf('switch_model')[0]['key'] private_key, = get_conf('private_key') cookies.update({ 'top_p':top_p, 'temperature':temperature, }) llm_kwargs = { 'api_key': cookies['api_key'], 'llm_model': llm_model, 'top_p':top_p, 'max_length': max_length, 'temperature': temperature, 'ipaddr': ipaddr.client.host, 'start_time': start_time } plugin_kwargs = { "advanced_arg": plugin_advanced_arg, "parameters_def": '' } if len(args) > 1: plugin_kwargs.update({'parameters_def': args[1]}) transparent_address_private = f'
' transparent_address = f'' if private in models: if chatbot == []: chatbot.append([None, f'隐私模式, 你的对话记录无法被他人检索 {transparent_address_private}']) else: chatbot[0] = [None, f'隐私模式, 你的对话记录无法被他人检索 {transparent_address_private}'] else: if chatbot == []: chatbot.append([None, f'正常对话模式, 你接来下的对话将会被记录并且可以被所有人检索,你可以到Settings中选择隐私模式 {transparent_address}']) else: chatbot[0] = [None, f'正常对话模式, 你接来下的对话将会被记录并且可以被所有人检索,你可以到Settings中选择隐私模式 {transparent_address}'] chatbot_with_cookie = ChatBotWithCookies(cookies) chatbot_with_cookie.write_list(chatbot) txt_passon = txt if encrypt in models: txt_passon = func_box.encryption_str(txt) yield from f(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, *args) return decorated def update_ui(chatbot, history, msg='正常', *args): # 刷新界面 """ 刷新用户界面 """ assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时,可用clear将其清空,然后用for+append循环重新赋值。" yield chatbot.get_cookies(), chatbot, history, msg threading.Thread(target=func_box.thread_write_chat, args=(chatbot, history)).start() # func_box.thread_write_chat(chatbot, history) def update_ui_lastest_msg(lastmsg, chatbot, history, delay=1): # 刷新界面 """ 刷新用户界面 """ if len(chatbot) == 0: chatbot.append(["update_ui_last_msg", lastmsg]) chatbot[-1] = list(chatbot[-1]) chatbot[-1][-1] = lastmsg yield from update_ui(chatbot=chatbot, history=history) time.sleep(delay) def trimmed_format_exc(): import os, traceback str = traceback.format_exc() current_path = os.getcwd() replace_path = "." return str.replace(current_path, replace_path) def CatchException(f): """ 装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。 """ @wraps(f) def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT=-1): try: yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT) except Exception as e: from check_proxy import check_proxy from toolbox import get_conf proxies, = get_conf('proxies') tb_str = '```\n' + trimmed_format_exc() + '```' if len(chatbot) == 0: chatbot.clear() chatbot.append(["插件调度异常", "异常原因"]) chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n{tb_str} \n\n当前代理可用性: \n\n{check_proxy(proxies)}") yield from update_ui(chatbot=chatbot, history=history, msg=f'异常 {e}') # 刷新界面 return decorated def HotReload(f): """ HotReload的装饰器函数,用于实现Python函数插件的热更新。 函数热更新是指在不停止程序运行的情况下,更新函数代码,从而达到实时更新功能。 在装饰器内部,使用wraps(f)来保留函数的元信息,并定义了一个名为decorated的内部函数。 内部函数通过使用importlib模块的reload函数和inspect模块的getmodule函数来重新加载并获取函数模块, 然后通过getattr函数获取函数名,并在新模块中重新加载函数。 最后,使用yield from语句返回重新加载过的函数,并在被装饰的函数上执行。 最终,装饰器函数返回内部函数。这个内部函数可以将函数的原始定义更新为最新版本,并执行函数的新版本。 """ @wraps(f) def decorated(*args, **kwargs): fn_name = f.__name__ f_hot_reload = getattr(importlib.reload(inspect.getmodule(f)), fn_name) try: yield from f_hot_reload(*args, **kwargs) except TypeError: args = tuple(args[element] for element in range(len(args)) if element != 6) yield from f_hot_reload(*args, **kwargs) return decorated ####################################### 其他小工具 ##################################### """ ======================================================================== 第二部分 其他小工具: - write_results_to_file: 将结果写入markdown文件中 - regular_txt_to_markdown: 将普通文本转换为Markdown格式的文本。 - report_execption: 向chatbot中添加简单的意外错误信息 - text_divide_paragraph: 将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。 - markdown_convertion: 用多种方式组合,将markdown转化为好看的html - format_io: 接管gradio默认的markdown处理方式 - on_file_uploaded: 处理文件的上传(自动解压) - on_report_generated: 将生成的报告自动投射到文件上传区 - clip_history: 当历史上下文过长时,自动截断 - get_conf: 获取设置 - select_api_key: 根据当前的模型类别,抽取可用的api-key ======================================================================== """ def get_reduce_token_percent(text): """ * 此函数未来将被弃用 """ try: # text = "maximum context length is 4097 tokens. However, your messages resulted in 4870 tokens" pattern = r"(\d+)\s+tokens\b" match = re.findall(pattern, text) EXCEED_ALLO = 500 # 稍微留一点余地,否则在回复时会因余量太少出问题 max_limit = float(match[0]) - EXCEED_ALLO current_tokens = float(match[1]) ratio = max_limit/current_tokens assert ratio > 0 and ratio < 1 return ratio, str(int(current_tokens-max_limit)) except: return 0.5, '不详' def write_results_to_file(history, file_name=None): """ 将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。 """ import os import time if file_name is 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: f.write('# chatGPT 分析报告\n') for i, content in enumerate(history): try: if type(content) != str: content = str(content) except: continue if i % 2 == 0: f.write('## ') try: f.write(content) except: # remove everything that cannot be handled by utf8 f.write(content.encode('utf-8', 'ignore').decode()) f.write('\n\n') res = '以上材料已经被写入' + f'./gpt_log/{file_name}' return res def regular_txt_to_markdown(text): """ 将普通文本转换为Markdown格式的文本。 """ text = text.replace('\n', '\n\n') text = text.replace('\n\n\n', '\n\n') text = text.replace('\n\n\n', '\n\n') return text def report_execption(chatbot, history, a, b): """ 向chatbot中添加错误信息 """ chatbot.append((a, b)) history.append(a) history.append(b) import re def text_divide_paragraph(input_str): if input_str: code_blocks = re.findall(r'```[\s\S]*?```', input_str) for i, block in enumerate(code_blocks): input_str = input_str.replace(block, f'{{{{CODE_BLOCK_{i}}}}}') if code_blocks: sections = re.split(r'({{{{\w+}}}})', input_str) for idx, section in enumerate(sections): if 'CODE_BLOCK' in section or section.startswith(' '): continue sections[idx] = re.sub(r'(?!```)(?' suf = '' raw_pre = '' if txt.startswith(pre) and txt.endswith(suf): # print('警告,输入了已经经过转化的字符串,二次转化可能出问题') return txt # 已经被转化过,不需要再次转化 if txt.startswith(raw_pre) and txt.endswith(raw_suf): return txt # 已经被转化过,不需要再次转化 raw_hide = raw_pre + txt + raw_suf markdown_extension_configs = { 'mdx_math': { 'enable_dollar_delimiter': True, 'use_gitlab_delimiters': False, }, } find_equation_pattern = r'\n', '') return content def no_code(txt): if '```' not in txt: return True else: if '```reference' in txt: return True # newbing else: return False if ('$$' in txt) and no_code(txt): # 有$标识的公式符号,且没有代码段```的标识 # convert everything to html format split = markdown.markdown(text='---') txt = re.sub(r'\$\$((?:.|\n)*?)\$\$', lambda match: '$$' + re.sub(r'\n+', '', match.group(1)) + '$$', txt) convert_stage_1 = markdown.markdown(text=txt, extensions=['mdx_math', 'fenced_code', 'tables', 'sane_lists'], extension_configs=markdown_extension_configs) convert_stage_1 = markdown_bug_hunt(convert_stage_1) # re.DOTALL: Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline. Corresponds to the inline flag (?s). # 1. convert to easy-to-copy tex (do not render math) convert_stage_2_1, n = re.subn(find_equation_pattern, replace_math_no_render, convert_stage_1, flags=re.DOTALL) # 2. convert to rendered equation convert_stage_1_resp = convert_stage_1.replace('', '') convert_stage_2_2, n = re.subn(find_equation_pattern, replace_math_render, convert_stage_1_resp, flags=re.DOTALL) # cat them together context = pre + convert_stage_2_1 + f'{split}' + convert_stage_2_2 + suf return raw_hide + context # 破坏html 结构,并显示源码 else: context = pre + markdown.markdown(txt, extensions=['fenced_code', 'codehilite', 'tables', 'sane_lists']) + suf return raw_hide + context # 破坏html 结构,并显示源码 def close_up_code_segment_during_stream(gpt_reply): """ 在gpt输出代码的中途(输出了前面的```,但还没输出完后面的```),补上后面的``` Args: gpt_reply (str): GPT模型返回的回复字符串。 Returns: str: 返回一个新的字符串,将输出代码片段的“后面的```”补上。 """ if '```' not in str(gpt_reply): return gpt_reply if str(gpt_reply).endswith('```'): return gpt_reply # 排除了以上两个情况,我们 segments = gpt_reply.split('```') n_mark = len(segments) - 1 if n_mark % 2 == 1: # print('输出代码片段中!') return gpt_reply+'\n```' else: return gpt_reply def format_io(self, y): """ 将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。 """ if y is None or y == []: return [] i_ask, gpt_reply = y[-1] # 输入部分太自由,预处理一波 if i_ask is not None: i_ask = text_divide_paragraph(i_ask) # 当代码输出半截的时候,试着补上后个``` if gpt_reply is not None: gpt_reply = close_up_code_segment_during_stream(gpt_reply) # process 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_convertion(i_ask), None if gpt_reply is None else markdown_convertion(gpt_reply) ) return y def find_free_port(): """ 返回当前系统中可用的未使用端口。 """ import socket from contextlib import closing with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.bind(('', 0)) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return s.getsockname()[1] 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] # Extract the archive based on its extension if file_extension == '.zip': with zipfile.ZipFile(file_path, 'r') as zipobj: zipobj.extractall(path=dest_dir) print("Successfully extracted zip archive to {}".format(dest_dir)) elif file_extension in ['.tar', '.gz', '.bz2']: with tarfile.open(file_path, 'r:*') as tarobj: 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': 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 format requires additional dependencies to install") return '\n\n解压失败! 需要安装pip install rarfile来解压rar文件' # 第三方库,需要预先pip install py7zr 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 format requires additional dependencies to install") return '\n\n解压失败! 需要安装pip install py7zr来解压7z文件' else: return '' return '' def find_recent_files(directory): """ me: find files that is created with in one minutes under a directory with python, write a function gpt: here it is! """ import os import time current_time = time.time() one_minute_ago = current_time - 60 recent_files = [] for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if file_path.endswith('.log'): continue created_time = os.path.getmtime(file_path) if created_time >= one_minute_ago: if os.path.isdir(file_path): continue recent_files.append(file_path) return recent_files def promote_file_to_downloadzone(file, rename_file=None, chatbot=None): # 将文件复制一份到下载区 import shutil if rename_file is None: rename_file = f'{gen_time_str()}-{os.path.basename(file)}' new_path = os.path.join(f'./gpt_log/', rename_file) if os.path.exists(new_path) and not os.path.samefile(new_path, file): os.remove(new_path) if not os.path.exists(new_path): shutil.copyfile(file, new_path) if chatbot: if 'file_to_promote' in chatbot._cookies: current = chatbot._cookies['file_to_promote'] else: current = [] chatbot._cookies.update({'file_to_promote': [new_path] + current}) def get_user_upload(chatbot, ipaddr: gr.Request): """ 获取用户上传过的文件 """ private_upload = './private_upload' user_history = os.path.join(private_upload, ipaddr.client.host) history = """| 编号 | 目录 | 目录内文件 |\n| --- | --- | --- |\n""" count_num = 1 for root, d, file in os.walk(user_history): file_link = "