CoolFace
Apppublic

jaylen/Chat_polish

sourceHugging Faceupdated 3y agoView on Hugging Face
0likes
toolbox.py140 linesDownload Raw Back to root
1import markdown, mdtex2html, threading2from 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=[]):6    """7        调用简单的predict_no_ui接口,但是依然保留了些许界面心跳功能,当对话太长时,会自动采用二分法截断8    """9    import time10    try: from config_private import TIMEOUT_SECONDS, MAX_RETRY11    except: from config import TIMEOUT_SECONDS, MAX_RETRY12    from predict import predict_no_ui13    mutable = [None, '']14    def mt(i_say, history): 15        while True:16            try:17                mutable[0] = predict_no_ui(inputs=i_say, top_p=top_p, temperature=temperature, history=history)18                break19            except ConnectionAbortedError as e:20                if len(history) > 0:21                    history = [his[len(his)//2:] for his in history if his is not None]22                    mutable[1] = 'Warning! History conversation is too long, cut into half. '23                else:24                    i_say = i_say[:len(i_say)//2]25                    mutable[1] = 'Warning! Input file is too long, cut into half. '26            except TimeoutError as e:27                mutable[0] = '[Local Message] Failed with timeout'28 29    thread_name = threading.Thread(target=mt, args=(i_say, history)); thread_name.start()30    cnt = 031    while thread_name.is_alive():32        cnt += 133        chatbot[-1] = (i_say_show_user, f"[Local Message] {mutable[1]}waiting gpt response {cnt}/{TIMEOUT_SECONDS*2*(MAX_RETRY+1)}"+''.join(['.']*(cnt%4)))34        yield chatbot, history, '正常'35        time.sleep(1)36    gpt_say = mutable[0]37    return gpt_say38 39def write_results_to_file(history, file_name=None):40    """41        将对话记录history以Markdown格式写入文件中。如果没有指定文件名,则使用当前时间生成文件名。42    """43    import os, time44    if file_name is None:45        file_name = time.strftime("chatGPT分析报告%Y-%m-%d-%H-%M-%S", time.localtime()) + '.md'46    os.makedirs('./gpt_log/', exist_ok=True)47    with open(f'./gpt_log/{file_name}', 'w') as f:48        f.write('# chatGPT 分析报告\n')49        for i, content in enumerate(history):50            if i%2==0: f.write('## ')51            f.write(content)52            f.write('\n\n')53    res = '以上材料已经被写入' + os.path.abspath(f'./gpt_log/{file_name}')54    print(res)55    return res56 57def regular_txt_to_markdown(text):58    """59        将普通文本转换为Markdown格式的文本。60    """61    text = text.replace('\n', '\n\n')62    text = text.replace('\n\n\n', '\n\n')63    text = text.replace('\n\n\n', '\n\n')64    return text65 66def CatchException(f):67    """68        装饰器函数,捕捉函数f中的异常并封装到一个生成器中返回,并显示到聊天当中。69    """70    @wraps(f)71    def decorated(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT):72        try:73            yield from f(txt, top_p, temperature, chatbot, history, systemPromptTxt, WEB_PORT)74        except Exception as e:75            import traceback76            from check_proxy import check_proxy77            try: from config_private import proxies78            except: from config import proxies79            tb_str = regular_txt_to_markdown(traceback.format_exc())80            chatbot[-1] = (chatbot[-1][0], f"[Local Message] 实验性函数调用出错: \n\n {tb_str} \n\n 当前代理可用性: \n\n {check_proxy(proxies)}")81            yield chatbot, history, f'异常 {e}'82    return decorated83 84def report_execption(chatbot, history, a, b):85    """86        向chatbot中添加错误信息87    """88    chatbot.append((a, b))89    history.append(a); history.append(b)90 91def text_divide_paragraph(text):92    """93        将文本按照段落分隔符分割开,生成带有段落标签的HTML代码。94    """95    if '```' in text:96        # careful input97        return text98    else:99        # wtf input100        lines = text.split("\n")101        for i, line in enumerate(lines):102            if i!=0: lines[i] = "<p>"+lines[i].replace(" ", "&nbsp;")+"</p>"103        text = "".join(lines)104        return text105 106def markdown_convertion(txt):107    """108        将Markdown格式的文本转换为HTML格式。如果包含数学公式,则先将公式转换为HTML格式。109    """110    if ('$' in txt) and ('```' not in txt):111        return markdown.markdown(txt,extensions=['fenced_code','tables']) + '<br><br>' + \112            markdown.markdown(convert_math(txt, splitParagraphs=False),extensions=['fenced_code','tables'])113    else:114        return markdown.markdown(txt,extensions=['fenced_code','tables'])115 116 117def format_io(self, y):118    """119        将输入和输出解析为HTML格式。将y中最后一项的输入部分段落化,并将输出部分的Markdown和数学公式转换为HTML格式。120    """121    if y is None: return []122    i_ask, gpt_reply = y[-1]123    i_ask = text_divide_paragraph(i_ask) # 输入部分太自由,预处理一波124    y[-1] = (125        None if i_ask is None else markdown.markdown(i_ask, extensions=['fenced_code','tables']),126        None if gpt_reply is None else markdown_convertion(gpt_reply)127    )128    return y129 130 131def find_free_port():132    """133        返回当前系统中可用的未使用端口。134    """135    import socket136    from contextlib import closing137    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:138        s.bind(('', 0))139        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)140        return s.getsockname()[1]