1 Star 7 Fork 1

Richard/python-chatgpt

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
index.py 3.97 KB
一键复制 编辑 原始数据 按行查看 历史
Richard 提交于 2023-02-14 09:44 . 使用jwt认证
import time
import datetime
import jwt
from loguru import logger
from pywebio.input import *
from pywebio.output import *
from pywebio.pin import *
from pywebio.session import *
from pywebio_battery import *
from api_chatgpt import get_answer
logger.add(
f"{datetime.date.today().strftime('%Y%m%d')}.log",
encoding="utf-8",
enqueue=True,
backtrace=True,
diagnose=True,
level="INFO",
format="{time:YYYY-MM-DD HH:mm:ss} | {message}",
)
secret_key = "18038016195" # jwt的加密密钥
users = ["richard", "lihao"] # 允许的用户名
def sign_jwt(username: str) -> str:
"""生成jwt"""
payload = {
"user_id": username,
"expires": time.time() + 60 * 60 * 24,
}
return jwt.encode(payload, secret_key, algorithm="HS256")
def auth(func):
"""JWT认证装饰器"""
def wrapper(*args, **kwargs):
token = get_localstorage("token")
if not token:
return login()
try:
data = jwt.decode(token, secret_key, algorithms="HS256")
if data.get("user_id") not in users:
return login()
except jwt.ExpiredSignatureError:
return login()
except jwt.InvalidTokenError:
return login()
else:
return func(*args, **kwargs)
return wrapper
def login():
"""登录页面"""
username = input("你是谁?")
if username in users:
token = sign_jwt(username)
set_localstorage("token", token)
index()
else:
put_text("你不是我要找的人。")
@auth
@use_scope("index")
def index():
"""和润达研究院智能助手"""
put_answer()
put_textarea(name="question", placeholder="输入完成后按Ctrl+Enter可快速提交", rows=3)
put_button(
label="提 问",
onclick=lambda: put_answer(pin.question, get_answer(pin.question)),
)
put_html(
"""
<script>
$(document).ready(function() {
//监视输出变化
var targetNode = document.getElementById("pywebio-scope-output");
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
//console.log("Div content changed:", mutation.target.innerHTML);
enable_input();
});
});
var config = { childList: true, characterData: true, subtree: true };
observer.observe(targetNode, config);
//回车提交
$("textarea[name='question']").keypress(function(e) {
if(e.ctrlKey && e.which ==13 || e.which == 10){
$("textarea[name='question']").prop("disabled", true);
$("button").click().prop("disabled", true).text("ChatGPT正在思索,请耐心等待...");
}
});
//禁用输入元素状态
$("button").click(function(){
$("textarea[name='question']").prop("disabled", true);
$(this).prop("disabled", true).text("ChatGPT正在思索,请耐心等待...");
});
});
//启用输入元素
function enable_input(){
$("textarea[name='question']").prop("value", "").prop("disabled", false).focus();
$("button").prop("disabled", false).text("提 问");
}
</script>
"""
)
@use_scope("output")
def put_answer(question: str = None, answer: str = None):
if not question:
put_text("请输入您的问题。-- Richard@2023/02/09")
return
logger.info(f"{question} -> {answer}")
tpl = """
<details {{#open}}open{{/open}}>
<summary>{{title}}</summary>
{{#contents}}
{{& pywebio_output_parse}}
{{/contents}}
</details>
"""
put_widget(
tpl,
{
"open": True,
"title": question,
"contents": [
put_markdown(f"{answer}"),
],
},
)
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/qq812256/python-chatgpt.git
git@gitee.com:qq812256/python-chatgpt.git
qq812256
python-chatgpt
python-chatgpt
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385