Files
k3GPT/main/utils.py

120 lines
3.1 KiB
Python
Raw Normal View History

2025-11-19 19:43:16 +08:00
import secrets
import hashlib
import time
import os
def generate_hashed_session_id():
"""
生成一个基于 SHA-256 的安全 session_id
:return: 安全的 session_id
"""
random_bytes = secrets.token_bytes(32) # 生成 32 字节随机数
hashed = hashlib.sha256(random_bytes).hexdigest() # 计算 SHA-256 哈希值
#保存session_id
timestamp = int(time.time())
with open(f"/tmp/k3gpt/session_id_{hashed}","w+") as f:
f.write(str(timestamp))
return hashed
def valid_session_id(session_id):
"""
检查会话id是否有效
"""
try:
with open(f"/tmp/k3gpt/session_id_{session_id}","r") as f:
s_timestamp = f.read()
if int(time.time())-int(s_timestamp) < 3600*12:
return True
else:
return False
except Exception as e:
print(e)
return False
def delete_session_id(session_id):
"""
删除session
"""
try:
os.remove(f"/tmp/k3gpt/session_id_{session_id}")
except:
pass
def hashed_password(password):
"""
生成一个基于 SHA-256 的安全 session_id
:return: 安全的 session_id
"""
pswd=f"k3gpt_{password}".encode("utf8")
hashed = hashlib.sha256(pswd).hexdigest() # 计算 SHA-256 哈希值
return hashed
def hashed_tel(password):
"""
生成一个基于 SHA-256 的安全 session_id
:return: 安全的 session_id
"""
pswd=f"tel_{password}".encode("utf8")
hashed = hashlib.sha256(pswd).hexdigest() # 计算 SHA-256 哈希值
return hashed
import re
def regular_filename(filename):
"""
去除字符串中的中文符号英文符号空格换行制表符等所有特殊符号
仅保留中文字符英文字母数字
"""
# \u4e00-\u9fa5常用中文字符范围简体+繁体基本覆盖)
# a-zA-Z0-9英文字母和数字
cleaned = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9.]', '_', filename)
return cleaned
#处理思考大模型的信息
def found_llm_think_data(data):
think=""
if data.find("<think>")>=0 and data.find("</think>")==-1:
#还未思考结束
think = data[8:]
data = ""
elif data.find("<think>")>=0 and data.find("</think>")>0:
#思考结束
end = data.find("</think>")
think = data[8:end]
data = data[end+8:]
begin = data.find("{")
end = data.rfind("}")
if data.find("```json") >=0:
#找到json数据只返回json数据
data = data[begin:end+1]
elif begin>0 and end >0:
#含有json数据
data = data[begin:end+1]
return think,data
from cryptography.fernet import Fernet
key = b'aDSK382C_Ep5hAvMkW0UPttdicyog-JoxaV_-CStutE='
def encrypt_tel(tel):
f = Fernet(key)
token = f.encrypt(tel.encode("utf-8"))
return token.decode("utf-8")
def decrypt_tel(token):
f = Fernet(key)
try:
tel = f.decrypt(token.encode("utf-8"))
except:
return "***********"
return tel.decode("utf-8")
if __name__=="__main__":
h = hashed_password("12345678")
print(h)