代码拉取完成,页面将自动刷新
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}"),
],
},
)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。