|
|
|
from __future__ import annotations |
|
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple, Type |
|
import logging |
|
import json |
|
import os |
|
import datetime |
|
import hashlib |
|
import csv |
|
import requests |
|
import re |
|
import html |
|
import sys |
|
import subprocess |
|
import pytz |
|
import pymysql |
|
import random |
|
|
|
import gradio as gr |
|
from pypinyin import lazy_pinyin |
|
import tiktoken |
|
import mdtex2html |
|
from markdown import markdown |
|
from pygments import highlight |
|
from pygments.lexers import get_lexer_by_name |
|
from pygments.formatters import HtmlFormatter |
|
|
|
from modules.presets import * |
|
import modules.shared as shared |
|
|
|
logging.basicConfig( |
|
level=logging.INFO, |
|
format="%(asctime)s [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s", |
|
) |
|
|
|
if TYPE_CHECKING: |
|
from typing import TypedDict |
|
|
|
class DataframeData(TypedDict): |
|
headers: List[str] |
|
data: List[List[str | int | bool]] |
|
|
|
def gen_sys_prompt(): |
|
tz = pytz.timezone('Asia/Shanghai') |
|
now = datetime.datetime.now(tz) |
|
timestamp = now.strftime("%Y年%m月%d日 %H:%M") |
|
sys_prompt = f"""现在是{timestamp},有些信息可能已经过时。 |
|
你的目的是如实解答用户问题,对于不知道的问题,你需要回复你不知道,或者让用户勾选右边的“使用在线搜索”再重试。 |
|
""" |
|
return sys_prompt |
|
|
|
|
|
def get_mmdd_hhmi(): |
|
tz = pytz.timezone('Asia/Shanghai') |
|
now = datetime.datetime.now(tz) |
|
timestamp = now.strftime("_%m%d_%H%M") |
|
return timestamp |
|
|
|
|
|
def fetch_data(query): |
|
|
|
conn = pymysql.connect(host = os.environ.get('db_host'), port=3306, |
|
user = os.environ.get('db_user'), |
|
password = os.environ.get('db_pass'), |
|
db = os.environ.get('db_db'), |
|
charset = 'utf8mb4') |
|
cur = conn.cursor() |
|
cur.execute(query) |
|
result = cur.fetchall() |
|
cur.close() |
|
conn.close() |
|
return result |
|
|
|
|
|
def auth_check(username, password): |
|
global logged_in_user |
|
if_pass = False |
|
for user in user_tuple: |
|
|
|
if user[0] == username and user[1] == password: |
|
if_pass = True |
|
logged_in_user = username |
|
break |
|
if if_pass: |
|
logging.info(f"Logged in as {username}") |
|
gr.current_user = gr.State(username) |
|
ding_send(f"【成功登录】用户名:{username}") |
|
|
|
else: |
|
logging.info(f"Login attempt failed:[{username},{password}]") |
|
ding_send(f"【异常登录】用户名:{username},密码:{password}") |
|
return if_pass |
|
|
|
|
|
try: |
|
user_tuple = fetch_data("SELECT username, password FROM credentials") |
|
source = "db" |
|
except: |
|
user_tuple = eval(os.environ.get('user_tuple')) |
|
source = "env" |
|
|
|
logging.info(f"based on {source}") |
|
|
|
def count_token(message): |
|
encoding = tiktoken.get_encoding("cl100k_base") |
|
input_str = f"role: {message['role']}, content: {message['content']}" |
|
length = len(encoding.encode(input_str)) |
|
return length |
|
|
|
|
|
def markdown_to_html_with_syntax_highlight(md_str): |
|
def replacer(match): |
|
lang = match.group(1) or "text" |
|
code = match.group(2) |
|
|
|
try: |
|
lexer = get_lexer_by_name(lang, stripall=True) |
|
except ValueError: |
|
lexer = get_lexer_by_name("text", stripall=True) |
|
|
|
formatter = HtmlFormatter() |
|
highlighted_code = highlight(code, lexer, formatter) |
|
|
|
return f'<pre><code class="{lang}">{highlighted_code}</code></pre>' |
|
|
|
code_block_pattern = r"```(\w+)?\n([\s\S]+?)\n```" |
|
md_str = re.sub(code_block_pattern, replacer, md_str, flags=re.MULTILINE) |
|
|
|
html_str = markdown(md_str) |
|
return html_str |
|
|
|
|
|
def normalize_markdown(md_text: str) -> str: |
|
lines = md_text.split("\n") |
|
normalized_lines = [] |
|
inside_list = False |
|
|
|
for i, line in enumerate(lines): |
|
if re.match(r"^(\d+\.|-|\*|\+)\s", line.strip()): |
|
if not inside_list and i > 0 and lines[i - 1].strip() != "": |
|
normalized_lines.append("") |
|
inside_list = True |
|
normalized_lines.append(line) |
|
elif inside_list and line.strip() == "": |
|
if i < len(lines) - 1 and not re.match( |
|
r"^(\d+\.|-|\*|\+)\s", lines[i + 1].strip() |
|
): |
|
normalized_lines.append(line) |
|
continue |
|
else: |
|
inside_list = False |
|
normalized_lines.append(line) |
|
|
|
return "\n".join(normalized_lines) |
|
|
|
|
|
def convert_mdtext(md_text): |
|
code_block_pattern = re.compile(r"```(.*?)(?:```|$)", re.DOTALL) |
|
inline_code_pattern = re.compile(r"`(.*?)`", re.DOTALL) |
|
code_blocks = code_block_pattern.findall(md_text) |
|
non_code_parts = code_block_pattern.split(md_text)[::2] |
|
|
|
result = [] |
|
for non_code, code in zip(non_code_parts, code_blocks + [""]): |
|
if non_code.strip(): |
|
non_code = normalize_markdown(non_code) |
|
if inline_code_pattern.search(non_code): |
|
result.append(markdown(non_code, extensions=["tables"])) |
|
else: |
|
result.append(mdtex2html.convert(non_code, extensions=["tables"])) |
|
if code.strip(): |
|
|
|
|
|
code = f"\n```{code}\n\n```" |
|
code = markdown_to_html_with_syntax_highlight(code) |
|
result.append(code) |
|
result = "".join(result) |
|
result += ALREADY_CONVERTED_MARK |
|
return result |
|
|
|
|
|
def convert_asis(userinput): |
|
return ( |
|
f'<p style="white-space:pre-wrap;">{html.escape(userinput)}</p>' |
|
+ ALREADY_CONVERTED_MARK |
|
) |
|
|
|
|
|
def detect_converted_mark(userinput): |
|
if userinput.endswith(ALREADY_CONVERTED_MARK): |
|
return True |
|
else: |
|
return False |
|
|
|
|
|
def detect_language(code): |
|
if code.startswith("\n"): |
|
first_line = "" |
|
else: |
|
first_line = code.strip().split("\n", 1)[0] |
|
language = first_line.lower() if first_line else "" |
|
code_without_language = code[len(first_line) :].lstrip() if first_line else code |
|
return language, code_without_language |
|
|
|
|
|
def construct_text(role, text): |
|
return {"role": role, "content": text} |
|
|
|
|
|
def construct_user(text): |
|
return construct_text("user", text) |
|
|
|
|
|
def construct_system(text): |
|
return construct_text("system", text) |
|
|
|
|
|
def construct_assistant(text): |
|
return construct_text("assistant", text) |
|
|
|
|
|
def construct_token_message(token, stream=False): |
|
return f"Token 计数: {token}" |
|
|
|
|
|
def delete_first_conversation(history, previous_token_count): |
|
if history: |
|
del history[:2] |
|
del previous_token_count[0] |
|
return ( |
|
history, |
|
previous_token_count, |
|
construct_token_message(sum(previous_token_count)), |
|
) |
|
|
|
|
|
def delete_last_conversation(chatbot, history, previous_token_count): |
|
if len(chatbot) > 0 and standard_error_msg in chatbot[-1][1]: |
|
logging.info("由于包含报错信息,只删除chatbot记录") |
|
chatbot.pop() |
|
return chatbot, history |
|
if len(history) > 0: |
|
logging.info("删除了一组对话历史") |
|
history.pop() |
|
history.pop() |
|
if len(chatbot) > 0: |
|
logging.info("删除了一组chatbot对话") |
|
chatbot.pop() |
|
if len(previous_token_count) > 0: |
|
logging.info("删除了一组对话的token计数记录") |
|
previous_token_count.pop() |
|
return ( |
|
chatbot, |
|
history, |
|
previous_token_count, |
|
construct_token_message(sum(previous_token_count)), |
|
) |
|
|
|
|
|
def save_file(filename, system, history, chatbot): |
|
|
|
os.makedirs(HISTORY_DIR, exist_ok=True) |
|
if filename.endswith(".json"): |
|
filename = filename.replace(".json", "") + get_mmdd_hhmi() + ".json" |
|
json_s = {"system": system, "history": history, "chatbot": chatbot} |
|
|
|
with open(os.path.join(HISTORY_DIR, filename), "w", encoding="utf8") as f: |
|
json.dump(json_s, f, ensure_ascii=False) |
|
elif filename.endswith(".md"): |
|
filename = filename.replace(".md", "") + get_mmdd_hhmi() + ".md" |
|
md_s = f"system: \n- {system} \n" |
|
for data in history: |
|
md_s += f"\n{data['role']}: \n- {data['content']} \n" |
|
with open(os.path.join(HISTORY_DIR, filename), "w", encoding="utf8") as f: |
|
f.write(md_s) |
|
logging.info(f"保存成功:{filename}") |
|
return os.path.join(HISTORY_DIR, filename) |
|
|
|
|
|
def save_chat_history(filename, system, history, chatbot): |
|
if filename == "": |
|
return |
|
if not filename.endswith(".json"): |
|
filename += ".json" |
|
return save_file(filename, system, history, chatbot) |
|
|
|
|
|
def export_markdown(filename, system, history, chatbot): |
|
if filename == "": |
|
return |
|
if not filename.endswith(".md"): |
|
filename += ".md" |
|
return save_file(filename, system, history, chatbot) |
|
|
|
|
|
def load_chat_history(filename, system, history, chatbot): |
|
|
|
if type(filename) != str: |
|
filename = filename.name |
|
try: |
|
with open(os.path.join(HISTORY_DIR, filename), "r", encoding="utf8") as f: |
|
json_s = json.load(f) |
|
try: |
|
if type(json_s["history"][0]) == str: |
|
|
|
new_history = [] |
|
for index, item in enumerate(json_s["history"]): |
|
if index % 2 == 0: |
|
new_history.append(construct_user(item)) |
|
else: |
|
new_history.append(construct_assistant(item)) |
|
json_s["history"] = new_history |
|
logging.info(new_history) |
|
except: |
|
|
|
pass |
|
|
|
return filename, json_s["system"], json_s["history"], json_s["chatbot"] |
|
except FileNotFoundError: |
|
|
|
return filename, system, history, chatbot |
|
|
|
|
|
def sorted_by_pinyin(list): |
|
return sorted(list, key=lambda char: lazy_pinyin(char)[0][0]) |
|
|
|
|
|
def get_file_names(dir, plain=False, filetypes=[".json"]): |
|
|
|
files = [] |
|
try: |
|
for type in filetypes: |
|
files += [f for f in os.listdir(dir) if f.endswith(type)] |
|
except FileNotFoundError: |
|
files = [] |
|
files = sorted_by_pinyin(files) |
|
if files == []: |
|
files = [""] |
|
if plain: |
|
return files |
|
else: |
|
return gr.Dropdown.update(choices=files) |
|
|
|
|
|
def get_history_names(plain=False): |
|
|
|
return get_file_names(HISTORY_DIR, plain) |
|
|
|
|
|
def load_template(filename, mode=0): |
|
|
|
lines = [] |
|
|
|
if filename.endswith(".json"): |
|
with open(os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8") as f: |
|
lines = json.load(f) |
|
lines = [[i["act"], i["prompt"]] for i in lines] |
|
else: |
|
with open( |
|
os.path.join(TEMPLATES_DIR, filename), "r", encoding="utf8" |
|
) as csvfile: |
|
reader = csv.reader(csvfile) |
|
lines = list(reader) |
|
lines = lines[1:] |
|
if mode == 1: |
|
return sorted_by_pinyin([row[0] for row in lines]) |
|
elif mode == 2: |
|
return {row[0]: row[1] for row in lines} |
|
else: |
|
choices = sorted_by_pinyin([row[0] for row in lines]) |
|
return {row[0]: row[1] for row in lines}, gr.Dropdown.update( |
|
choices=choices, value=choices[0] |
|
) |
|
|
|
|
|
def get_template_names(plain=False): |
|
|
|
return get_file_names(TEMPLATES_DIR, plain, filetypes=[".csv", "json"]) |
|
|
|
|
|
def get_template_content(templates, selection, original_system_prompt): |
|
|
|
try: |
|
return templates[selection] |
|
except: |
|
return original_system_prompt |
|
|
|
|
|
def reset_state(): |
|
logging.info("🧹清空对话") |
|
return [], [], [], construct_token_message(0) |
|
|
|
|
|
def reset_textbox(): |
|
logging.debug("重置文本框") |
|
return gr.update(value="") |
|
|
|
|
|
def reset_default(): |
|
newurl = shared.state.reset_api_url() |
|
os.environ.pop("HTTPS_PROXY", None) |
|
os.environ.pop("https_proxy", None) |
|
return gr.update(value=newurl), gr.update(value=""), "API URL 和代理已重置" |
|
|
|
|
|
def change_api_url(url): |
|
shared.state.set_api_url(url) |
|
msg = f"API地址更改为:{url}" |
|
logging.info(msg) |
|
return msg |
|
|
|
|
|
def change_proxy(proxy): |
|
os.environ["HTTPS_PROXY"] = proxy |
|
msg = f"代理更改为:{proxy}" |
|
logging.info(msg) |
|
return msg |
|
|
|
|
|
def hide_middle_chars(s): |
|
if len(s) <= 8: |
|
return s |
|
else: |
|
head = s[:4] |
|
tail = s[-4:] |
|
hidden = "*" * (len(s) - 8) |
|
return head + hidden + tail |
|
|
|
|
|
def submit_key(key): |
|
key = key.strip() |
|
msg = f"API密钥更改为了{hide_middle_chars(key)}" |
|
logging.info(msg) |
|
return key, msg |
|
|
|
|
|
def replace_today(prompt): |
|
today = datetime.datetime.today().strftime("%Y-%m-%d") |
|
return prompt.replace("{current_date}", today) |
|
|
|
|
|
def get_geoip(): |
|
response = requests.get("https://ipapi.co/json/", timeout=5) |
|
try: |
|
data = response.json() |
|
except: |
|
data = {"error": True, "reason": "连接ipapi失败"} |
|
if "error" in data.keys(): |
|
logging.warning(f"无法获取IP地址信息。\n{data}") |
|
if data["reason"] == "RateLimited": |
|
return ( |
|
f"获取IP地理位置失败,因为达到了检测IP的速率限制。聊天功能可能仍然可用,但请注意,如果您的IP地址在不受支持的地区,您可能会遇到问题。" |
|
) |
|
else: |
|
return f"获取IP地理位置失败。原因:{data['reason']}。你仍然可以使用聊天功能。" |
|
else: |
|
country = data["country_name"] |
|
if country == "China": |
|
text = "**您的IP区域:中国。请立即检查代理设置,在不受支持的地区使用API可能导致账号被封禁。**" |
|
else: |
|
text = f"您的IP区域:{country}。" |
|
logging.info(text) |
|
return text |
|
|
|
|
|
def find_n(lst, max_num): |
|
n = len(lst) |
|
total = sum(lst) |
|
|
|
if total < max_num: |
|
return n |
|
|
|
for i in range(len(lst)): |
|
if total - lst[i] < max_num: |
|
return n - i - 1 |
|
total = total - lst[i] |
|
return 1 |
|
|
|
|
|
def start_outputing(): |
|
logging.debug("显示取消按钮,隐藏发送按钮") |
|
return gr.Button.update(visible=False), gr.Button.update(visible=True) |
|
|
|
|
|
def end_outputing(): |
|
return ( |
|
gr.Button.update(visible=True), |
|
gr.Button.update(visible=False), |
|
) |
|
|
|
|
|
def cancel_outputing(): |
|
logging.info("中止输出...") |
|
shared.state.interrupt() |
|
|
|
|
|
def transfer_input(inputs): |
|
|
|
textbox = reset_textbox() |
|
outputing = start_outputing() |
|
return ( |
|
inputs, |
|
gr.update(value=""), |
|
gr.Button.update(visible=False), |
|
gr.Button.update(visible=True), |
|
) |
|
|
|
|
|
def get_proxies(): |
|
|
|
http_proxy = os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy") |
|
https_proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") |
|
|
|
|
|
proxies = {} |
|
if http_proxy: |
|
logging.info(f"使用 HTTP 代理: {http_proxy}") |
|
proxies["http"] = http_proxy |
|
if https_proxy: |
|
logging.info(f"使用 HTTPS 代理: {https_proxy}") |
|
proxies["https"] = https_proxy |
|
|
|
if proxies == {}: |
|
proxies = None |
|
|
|
return proxies |
|
|
|
def api_picker(keys,backup_key): |
|
url = 'https://api.openai.com/v1/models' |
|
headers = {"Content-Type": "application/json"} |
|
random.shuffle(keys) |
|
for key in keys: |
|
try: |
|
headers['Authorization'] = f"Bearer {key}" |
|
response = requests.get(url, headers=headers, proxies=get_proxies()) |
|
if response.status_code == 200: |
|
return key |
|
break |
|
except: |
|
continue |
|
else: |
|
headers['Authorization'] = f"Bearer {backup_key}" |
|
return backup_key |
|
|
|
def logged_user(): |
|
return logged_in_user |
|
|
|
def ding_send(message): |
|
headers = {'Content-Type': 'application/json;charset=utf-8'} |
|
data = { |
|
"msgtype": "text", |
|
"text": { |
|
"content": message |
|
} |
|
} |
|
r = requests.post(os.environ.get("DINGTALK_WEBHOOK"), headers=headers, data=json.dumps(data)) |
|
return r.text |
|
|
|
def run(command, desc=None, errdesc=None, custom_env=None, live=False): |
|
if desc is not None: |
|
print(desc) |
|
if live: |
|
result = subprocess.run(command, shell=True, env=os.environ if custom_env is None else custom_env) |
|
if result.returncode != 0: |
|
raise RuntimeError(f"""{errdesc or 'Error running command'}. |
|
Command: {command} |
|
Error code: {result.returncode}""") |
|
|
|
return "" |
|
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, env=os.environ if custom_env is None else custom_env) |
|
if result.returncode != 0: |
|
message = f"""{errdesc or 'Error running command'}. |
|
Command: {command} |
|
Error code: {result.returncode} |
|
stdout: {result.stdout.decode(encoding="utf8", errors="ignore") if len(result.stdout)>0 else '<empty>'} |
|
stderr: {result.stderr.decode(encoding="utf8", errors="ignore") if len(result.stderr)>0 else '<empty>'} |
|
""" |
|
raise RuntimeError(message) |
|
return result.stdout.decode(encoding="utf8", errors="ignore") |
|
|
|
def versions_html(): |
|
git = os.environ.get('GIT', "git") |
|
python_version = ".".join([str(x) for x in sys.version_info[0:3]]) |
|
try: |
|
commit_hash = run(f"{git} rev-parse HEAD").strip() |
|
except Exception: |
|
commit_hash = "<none>" |
|
if commit_hash != "<none>": |
|
short_commit = commit_hash[0:7] |
|
commit_info = f"<a style=\"text-decoration:none\" href=\"https://github.com/huangyuzhang/chat/commit/{short_commit}\">{short_commit}</a>" |
|
else: |
|
commit_info = "unknown \U0001F615" |
|
return f""" |
|
Python: <span title="{sys.version}">{python_version}</span> |
|
• |
|
Gradio: {gr.__version__} |
|
""" |
|
|
|
|