CoolFace
Apppublic

maminghui/ChatGPT

sourceHugging Facegpl-3.0updated 3y agoView on Hugging Face
1likes
utils.py387 linesDownload Raw Back to root
1# -*- coding:utf-8 -*-2from __future__ import annotations3from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type4import logging5import json6import os7import datetime8import hashlib9import csv10import requests11import re12 13import gradio as gr14from pypinyin import lazy_pinyin15import tiktoken16import mdtex2html17from markdown import markdown18from pygments import highlight19from pygments.lexers import get_lexer_by_name20from pygments.formatters import HtmlFormatter21 22from presets import *23 24# logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s")25 26if TYPE_CHECKING:27    from typing import TypedDict28 29    class DataframeData(TypedDict):30        headers: List[str]31        data: List[List[str | int | bool]]32 33 34def count_token(message):35    encoding = tiktoken.get_encoding("cl100k_base")36    input_str = f"role: {message['role']}, content: {message['content']}"37    length = len(encoding.encode(input_str))38    return length39 40 41def markdown_to_html_with_syntax_highlight(md_str):42    def replacer(match):43        lang = match.group(1) or "text"44        code = match.group(2)45 46        try:47            lexer = get_lexer_by_name(lang, stripall=True)48        except ValueError:49            lexer = get_lexer_by_name("text", stripall=True)50 51        formatter = HtmlFormatter()52        highlighted_code = highlight(code, lexer, formatter)53 54        return f'<pre><code class="{lang}">{highlighted_code}</code></pre>'55 56    code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```"57    md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE)58 59    html_str = markdown(md_str)60    return html_str61 62 63def normalize_markdown(md_text: str) -> str:64    lines = md_text.split("\n")65    normalized_lines = []66    inside_list = False67 68    for i, line in enumerate(lines):69        if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()):70            if not inside_list and i > 0 and lines[i - 1].strip() != "":71                normalized_lines.append("")72            inside_list = True73            normalized_lines.append(line)74        elif inside_list and line.strip() == "":75            if i < len(lines) - 1 and not re.match(76                r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip()77            ):78                normalized_lines.append(line)79            continue80        else:81            inside_list = False82            normalized_lines.append(line)83 84    return "\n".join(normalized_lines)85 86 87def convert_mdtext(md_text):88    code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL)89    inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL)90    code_blocks = code_block_pattern.findall(md_text)91    non_code_parts = code_block_pattern.split(md_text)[::2]92 93    result = []94    for non_code, code in zip(non_code_parts, code_blocks + [""]):95        if non_code.strip():96            non_code = normalize_markdown(non_code)97            if inline_code_pattern.search(non_code):98                result.append(markdown(non_code, extensions=["tables"]))99            else:100                result.append(mdtex2html.convert(non_code, extensions=["tables"]))101        if code.strip():102            # _, code = detect_language(code)  # 暂时去除代码高亮功能,因为在大段代码的情况下会出现问题103            # code = code.replace("\n\n", "\n") # 暂时去除代码中的空行,因为在大段代码的情况下会出现问题104            code = f"```{code}\n\n```"105            code = markdown_to_html_with_syntax_highlight(code)106            result.append(code)107    result = "".join(result)108    return result109 110 111def detect_language(code):112    if code.startswith("\n"):113        first_line = ""114    else:115        first_line = code.strip().split("\n", 1)[0]116    language = first_line.lower() if first_line else ""117    code_without_language = code[len(first_line) :].lstrip() if first_line else code118    return language, code_without_language119 120 121def construct_text(role, text):122    return {"role": role, "content": text}123 124 125def construct_user(text):126    return construct_text("user", text)127 128 129def construct_system(text):130    return construct_text("system", text)131 132 133def construct_assistant(text):134    return construct_text("assistant", text)135 136 137def construct_token_message(token, stream=False):138    return f"Token 计数: {token}"139 140 141def delete_last_conversation(chatbot, history, previous_token_count):142    if len(chatbot) > 0 and standard_error_msg in chatbot[-1][1]:143        logging.info("由于包含报错信息,只删除chatbot记录")144        chatbot.pop()145        return chatbot, history146    if len(history) > 0:147        logging.info("删除了一组对话历史")148        history.pop()149        history.pop()150    if len(chatbot) > 0:151        logging.info("删除了一组chatbot对话")152        chatbot.pop()153    if len(previous_token_count) > 0:154        logging.info("删除了一组对话的token计数记录")155        previous_token_count.pop()156    return (157        chatbot,158        history,159        previous_token_count,160        construct_token_message(sum(previous_token_count)),161    )162 163 164def save_file(filename, system, history, chatbot):165    logging.info("保存对话历史中……")166    os.makedirs(HISTORY_DIR, exist_ok=True)167    if filename.endswith(".json"):168        json_s = {"system": system, "history": history, "chatbot": chatbot}169        print(json_s)170        with open(os.path.join(HISTORY_DIR, filename), "w") as f:171            json.dump(json_s, f)172    elif filename.endswith(".md"):173        md_s = f"system: \n- {system} \n"174        for data in history:175            md_s += f"\n{data['role']}: \n- {data['content']} \n"176        with open(os.path.join(HISTORY_DIR, filename), "w", encoding="utf8") as f:177            f.write(md_s)178    logging.info("保存对话历史完毕")179    return os.path.join(HISTORY_DIR, filename)180 181 182def save_chat_history(filename, system, history, chatbot):183    if filename == "":184        return185    if not filename.endswith(".json"):186        filename += ".json"187    return save_file(filename, system, history, chatbot)188 189 190def export_markdown(filename, system, history, chatbot):191    if filename == "":192        return193    if not filename.endswith(".md"):194        filename += ".md"195    return save_file(filename, system, history, chatbot)196 197 198def load_chat_history(filename, system, history, chatbot):199    logging.info("加载对话历史中……")200    if type(filename) != str:201        filename = filename.name202    try:203        with open(os.path.join(HISTORY_DIR, filename), "r") as f:204            json_s = json.load(f)205        try:206            if type(json_s["history"][0]) == str:207                logging.info("历史记录格式为旧版,正在转换……")208                new_history = []209                for index, item in enumerate(json_s["history"]):210                    if index % 2 == 0:211                        new_history.append(construct_user(item))212                    else:213                        new_history.append(construct_assistant(item))214                json_s["history"] = new_history215                logging.info(new_history)216        except:217            # 没有对话历史218            pass219        logging.info("加载对话历史完毕")220        return filename, json_s["system"], json_s["history"], json_s["chatbot"]221    except FileNotFoundError:222        logging.info("没有找到对话历史文件,不执行任何操作")223        return filename, system, history, chatbot224 225 226def sorted_by_pinyin(list):227    return sorted(list, key=lambda char: lazy_pinyin(char)[0][0])228 229 230def get_file_names(dir, plain=False, filetypes=[".json"]):231    logging.info(f"获取文件名列表,目录为{dir},文件类型为{filetypes},是否为纯文本列表{plain}")232    files = []233    try:234        for type in filetypes:235            files += [f for f in os.listdir(dir) if f.endswith(type)]236    except FileNotFoundError:237        files = []238    files = sorted_by_pinyin(files)239    if files == []:240        files = [""]241    if plain:242        return files243    else:244        return gr.Dropdown.update(choices=files)245 246 247def get_history_names(plain=False):248    logging.info("获取历史记录文件名列表")249    return get_file_names(HISTORY_DIR, plain)250 251 252def load_template(filename, mode=0):253    logging.info(f"加载模板文件{filename},模式为{mode}(0为返回字典和下拉菜单,1为返回下拉菜单,2为返回字典)")254    lines = []255    logging.info("Loading template...")256    if filename.endswith(".json"):257        with open(os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8") as f:258            lines = json.load(f)259        lines = [[i["act"], i["prompt"]] for i in lines]260    else:261        with open(262            os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8"263        ) as csvfile:264            reader = csv.reader(csvfile)265            lines = list(reader)266        lines = lines[1:]267    if mode == 1:268        return sorted_by_pinyin([row[0] for row in lines])269    elif mode == 2:270        return {row[0]: row[1] for row in lines}271    else:272        choices = sorted_by_pinyin([row[0] for row in lines])273        return {row[0]: row[1] for row in lines}, gr.Dropdown.update(274            choices=choices, value=choices[0]275        )276 277 278def get_template_names(plain=False):279    logging.info("获取模板文件名列表")280    return get_file_names(TEMPLATES_DIR, plain, filetypes=[".csv", "json"])281 282 283def get_template_content(templates, selection, original_system_prompt):284    logging.info(f"应用模板中,选择为{selection},原始系统提示为{original_system_prompt}")285    try:286        return templates[selection]287    except:288        return original_system_prompt289 290 291def reset_state():292    logging.info("重置状态")293    return [], [], [], construct_token_message(0)294 295 296def reset_textbox():297    return gr.update(value="")298 299 300def reset_default():301    global API_URL302    API_URL = "https://api.openai.com/v1/chat/completions"303    os.environ.pop("HTTPS_PROXY", None)304    os.environ.pop("https_proxy", None)305    return gr.update(value=API_URL), gr.update(value=""), "API URL 和代理已重置"306 307 308def change_api_url(url):309    global API_URL310    API_URL = url311    msg = f"API地址更改为了{url}"312    logging.info(msg)313    return msg314 315 316def change_proxy(proxy):317    os.environ["HTTPS_PROXY"] = proxy318    msg = f"代理更改为了{proxy}"319    logging.info(msg)320    return msg321 322 323def hide_middle_chars(s):324    if len(s) <= 8:325        return s326    else:327        head = s[:4]328        tail = s[-4:]329        hidden = "*" * (len(s) - 8)330        return head + hidden + tail331 332 333def submit_key(key):334    key = key.strip()335    msg = f"API密钥更改为了{hide_middle_chars(key)}"336    logging.info(msg)337    return key, msg338 339 340def sha1sum(filename):341    sha1 = hashlib.sha1()342    sha1.update(filename.encode("utf-8"))343    return sha1.hexdigest()344 345 346def replace_today(prompt):347    today = datetime.datetime.today().strftime("%Y-%m-%d")348    return prompt.replace("{current_date}", today)349 350 351def get_geoip():352    response = requests.get("https://ipapi.co/json/", timeout=5)353    try:354        data = response.json()355    except:356        data = {"error": True, "reason": "连接ipapi失败"}357    if "error" in data.keys():358        logging.warning(f"无法获取IP地址信息。\n{data}")359        if data["reason"] == "RateLimited":360            return (361                f"获取IP地理位置失败,因为达到了检测IP的速率限制。聊天功能可能仍然可用,但请注意,如果您的IP地址在不受支持的地区,您可能会遇到问题。"362            )363        else:364            return f"获取IP地理位置失败。原因:{data['reason']}。你仍然可以使用聊天功能。"365    else:366        country = data["country_name"]367        if country == "China":368            text = "**您的IP区域:中国。请立即检查代理设置,在不受支持的地区使用API可能导致账号被封禁。**"369        else:370            text = f"您的IP区域:{country}。"371        logging.info(text)372        return text373 374 375def find_n(lst, max_num):376    n = len(lst)377    total = sum(lst)378 379    if total < max_num:380        return n381 382    for i in range(len(lst)):383        if total - lst[i] < max_num:384            return n - i -1385        total = total - lst[i]386    return 1387