import markdown import importlib import time import inspect import re import gradio as gr import func_box import os from latex2mathml.converter import convert as tex2mathml from functools import wraps, lru_cache import logging import shutil import os import time import glob import sys from concurrent.futures import ThreadPoolExecutor import html ############################### 插件输入输出接驳区 ####################################### """ ======================================================================== 第一部分 函数插件输入输出接驳区 - 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 } 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) if txt_passon == '' and len(args) > 1: msgs = f'### Warning 输入框为空\n' \ f'tips: 使用基础功能或{func_box.html_tag_color("高亮插件", "#b522c5", "ffffff")}功能时,请在输入区输入需要处理的内容' yield from update_ui(chatbot=chatbot_with_cookie, history=history, msg=msgs) # 刷新界面 return yield from f(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, *args) return decorated pool = ThreadPoolExecutor(200) def update_ui(chatbot, history, msg='正常', *args): # 刷新界面 """ 刷新用户界面 """ assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时,可用clear将其清空,然后用for+append循环重新赋值。" yield chatbot.get_cookies(), chatbot, history, msg pool.submit(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 = '' if txt.startswith(pre) and txt.endswith(suf): # print('警告,输入了已经经过转化的字符串,二次转化可能出问题') return txt # 已经被转化过,不需要再次转化 markdown_extension_configs = { 'mdx_math': { 'enable_dollar_delimiter': True, 'use_gitlab_delimiters': False, }, } def tex2mathml_catch_exception(content, *args, **kwargs): try: content = tex2mathml(content, *args, **kwargs) except: content = content return content def replace_math_no_render(match): content = match.group(1) if 'mode=display' in match.group(0): content = content.replace('\n', '') return f"$${content}$$" else: return f"${content}$" def replace_math_render(match): content = match.group(1) if 'mode=display' in match.group(0): if '\\begin{aligned}' in content: content = content.replace('\\begin{aligned}', '\\begin{array}') content = content.replace('\\end{aligned}', '\\end{array}') content = content.replace('&', ' ') content = tex2mathml_catch_exception(content, display="block") return content else: return tex2mathml_catch_exception(content) def markdown_bug_hunt(content): """ 解决一个mdx_math的bug(单$包裹begin命令时多余\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='---') find_equation_pattern = r'