Skip to content

Commit

Permalink
重新编译Gradio优化使用体验
Browse files Browse the repository at this point in the history
  • Loading branch information
binary-husky committed Oct 6, 2023
1 parent 93c76e1 commit 6310b65
Show file tree
Hide file tree
Showing 15 changed files with 122 additions and 67 deletions.
12 changes: 11 additions & 1 deletion config.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
THEME = "Default"
AVAIL_THEMES = ["Default", "Chuanhu-Small-and-Beautiful", "High-Contrast", "Gstaff/Xkcd", "NoCrypt/Miku"]


# 对话窗的高度 (仅在LAYOUT="TOP-DOWN"时生效)
CHATBOT_HEIGHT = 1115

Expand All @@ -58,7 +59,10 @@

# 窗口布局
LAYOUT = "LEFT-RIGHT" # "LEFT-RIGHT"(左右布局) # "TOP-DOWN"(上下布局)
DARK_MODE = True # 暗色模式 / 亮色模式


# 暗色模式 / 亮色模式
DARK_MODE = True


# 发送请求到OpenAI后,等待多久判定为超时
Expand Down Expand Up @@ -179,10 +183,16 @@

# 是否允许通过自然语言描述修改本页的配置,该功能具有一定的危险性,默认关闭
ALLOW_RESET_CONFIG = False


# 临时的上传文件夹位置,请勿修改
PATH_PRIVATE_UPLOAD = "private_upload"


# 日志文件夹的位置,请勿修改
PATH_LOGGING = "gpt_log"


# 除了连接OpenAI之外,还有哪些场合允许使用代理,请勿修改
WHEN_TO_USE_PROXY = ["Download_LLM", "Download_Gradio_Theme", "Connect_Grobid", "Warmup_Modules"]

Expand Down
Binary file modified docs/gradio-3.32.6-py3-none-any.whl
Binary file not shown.
2 changes: 1 addition & 1 deletion docs/translate_english.json
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,7 @@
"任何文件": "Any file",
"但推荐上传压缩文件": "But it is recommended to upload compressed files",
"更换模型 & SysPrompt & 交互界面布局": "Change model & SysPrompt & interactive interface layout",
"底部输入区": "Bottom input area",
"浮动输入区": "Floating input area",
"输入清除键": "Input clear key",
"插件参数区": "Plugin parameter area",
"显示/隐藏功能区": "Show/hide function area",
Expand Down
1 change: 0 additions & 1 deletion docs/translate_japanese.json
Original file line number Diff line number Diff line change
Expand Up @@ -1007,7 +1007,6 @@
"第一部分": "第1部分",
"的分析如下": "の分析は以下の通りです",
"解决一个mdx_math的bug": "mdx_mathのバグを解決する",
"底部输入区": "下部の入力エリア",
"函数插件输入输出接驳区": "関数プラグインの入出力接続エリア",
"打开浏览器": "ブラウザを開く",
"免费用户填3": "無料ユーザーは3を入力してください",
Expand Down
1 change: 0 additions & 1 deletion docs/translate_traditionalchinese.json
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,6 @@
"情况会好转": "情況會好轉",
"超过512个": "超過512個",
"多线": "多線",
"底部输入区": "底部輸入區",
"合并小写字母开头的段落块并替换为空格": "合併小寫字母開頭的段落塊並替換為空格",
"暗色主题": "暗色主題",
"提高限制请查询": "提高限制請查詢",
Expand Down
77 changes: 52 additions & 25 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,16 @@ def main():

initial_prompt = "Serve me as a writing and programming assistant."
title_html = f"<h1 align=\"center\">GPT 学术优化 {get_current_version()}</h1>{theme_declaration}"
description = "代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic),"
description += "感谢热情的[开发者们❤️](https://github.com/binary-husky/gpt_academic/graphs/contributors)"
description = "Github源代码开源和更新[地址🚀](https://github.com/binary-husky/gpt_academic), "
description += "感谢热情的[开发者们❤️](https://github.com/binary-husky/gpt_academic/graphs/contributors)."
description += "</br></br>常见问题请查阅[项目Wiki](https://github.com/binary-husky/gpt_academic/wiki), "
description += "如遇到Bug请前往[Bug反馈](https://github.com/binary-husky/gpt_academic/issues)."
description += "</br></br>普通对话使用说明: 1. 输入问题; 2. 点击提交"
description += "</br></br>基础功能区使用说明: 1. 输入文本; 2. 点击任意基础功能区按钮"
description += "</br></br>函数插件区使用说明: 1. 输入路径/问题, 或者上传文件; 2. 点击任意函数插件区按钮"
description += "</br></br>虚空终端使用说明: 点击虚空终端, 然后根据提示输入指令, 再次点击虚空终端"
description += "</br></br>如何保存对话: 点击保存当前的对话按钮"
description += "</br></br>如何语音对话: 请阅读Wiki"

# 问询记录, python 版本建议3.9+(越新越好)
import logging, uuid
Expand Down Expand Up @@ -73,11 +81,11 @@ def main():
with gr.Row():
txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
with gr.Row():
submitBtn = gr.Button("提交", variant="primary")
submitBtn = gr.Button("提交", elem_id="elem_submit", variant="primary")
with gr.Row():
resetBtn = gr.Button("重置", variant="secondary"); resetBtn.style(size="sm")
stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
clearBtn = gr.Button("清除", variant="secondary", visible=False); clearBtn.style(size="sm")
resetBtn = gr.Button("重置", elem_id="elem_reset", variant="secondary"); resetBtn.style(size="sm")
stopBtn = gr.Button("停止", elem_id="elem_stop", variant="secondary"); stopBtn.style(size="sm")
clearBtn = gr.Button("清除", elem_id="elem_clear", variant="secondary", visible=False); clearBtn.style(size="sm")
if ENABLE_AUDIO:
with gr.Row():
audio_mic = gr.Audio(source="microphone", type="numpy", streaming=True, show_label=False).style(container=False)
Expand All @@ -88,7 +96,7 @@ def main():
for k in functional:
if ("Visible" in functional[k]) and (not functional[k]["Visible"]): continue
variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
functional[k]["Button"] = gr.Button(k, variant=variant)
functional[k]["Button"] = gr.Button(k, variant=variant, info_str=f'基础功能区: {k}')
functional[k]["Button"].style(size="sm")
with gr.Accordion("函数插件区", open=True, elem_id="plugin-panel") as area_crazy_fn:
with gr.Row():
Expand All @@ -101,7 +109,9 @@ def main():
if not plugin.get("AsButton", True): continue
visible = True if match_group(plugin['Group'], DEFAULT_FN_GROUPS) else False
variant = plugins[k]["Color"] if "Color" in plugin else "secondary"
plugin['Button'] = plugins[k]['Button'] = gr.Button(k, variant=variant, visible=visible).style(size="sm")
info = plugins[k].get("Info", k)
plugin['Button'] = plugins[k]['Button'] = gr.Button(k, variant=variant,
visible=visible, info_str=f'函数插件区: {info}').style(size="sm")
with gr.Row():
with gr.Accordion("更多函数插件", open=True):
dropdown_fn_list = []
Expand All @@ -118,15 +128,26 @@ def main():
switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary").style(size="sm")
with gr.Row():
with gr.Accordion("点击展开“文件上传区”。上传本地文件/压缩包供函数插件调用。", open=False) as area_file_up:
file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
with gr.Accordion("更换模型 & SysPrompt & 交互界面布局", open=(LAYOUT == "TOP-DOWN"), elem_id="interact-panel"):
system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
file_upload = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple", elem_id="elem_upload")


with gr.Floating(init_x="0%", init_y="0%", visible=True, width=None, drag="forbidden"):
with gr.Row():
with gr.Tab("上传文件", elem_id="interact-panel"):
gr.Markdown("请上传本地文件/压缩包供“函数插件区”功能调用。请注意: 上传文件后会自动把输入区修改为相应路径。")
file_upload_2 = gr.Files(label="任何文件, 推荐上传压缩文件(zip, tar)", file_count="multiple")

with gr.Tab("更换模型 & Prompt", elem_id="interact-panel"):
md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False)
top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
max_length_sl = gr.Slider(minimum=256, maximum=8192, value=4096, step=1, interactive=True, label="Local LLM MaxLength",)
checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "底部输入区", "输入清除键", "插件参数区"], value=["基础功能区", "函数插件区"], label="显示/隐藏功能区")
md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False)
max_length_sl = gr.Slider(minimum=256, maximum=1024*32, value=4096, step=128, interactive=True, label="Local LLM MaxLength",)
system_prompt = gr.Textbox(show_label=True, lines=2, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)

with gr.Tab("界面外观", elem_id="interact-panel"):
theme_dropdown = gr.Dropdown(AVAIL_THEMES, value=THEME, label="更换UI主题").style(container=False)
checkboxes = gr.CheckboxGroup(["基础功能区", "函数插件区", "浮动输入区", "输入清除键", "插件参数区"],
value=["基础功能区", "函数插件区"], label="显示/隐藏功能区", elem_id='cbs').style(container=False)
dark_mode_btn = gr.Button("切换界面明暗 ☀", variant="secondary").style(size="sm")
dark_mode_btn.click(None, None, None, _js="""() => {
if (document.querySelectorAll('.dark').length) {
Expand All @@ -136,13 +157,17 @@ def main():
}
}""",
)
with gr.Tab("帮助", elem_id="interact-panel"):
gr.Markdown(description)
with gr.Accordion("备选输入区", open=True, visible=False, elem_id="input-panel2") as area_input_secondary:
with gr.Row():
txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False)
with gr.Row():
submitBtn2 = gr.Button("提交", variant="primary")
with gr.Row():

with gr.Floating(init_x="20%", init_y="50%", visible=False, width="40%", drag="top") as area_input_secondary:
with gr.Accordion("浮动输入区", open=True, elem_id="input-panel2"):
with gr.Row() as row:
row.style(equal_height=True)
with gr.Column(scale=10):
txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", lines=8, label="输入区2").style(container=False)
with gr.Column(scale=1, min_width=40):
submitBtn2 = gr.Button("提交", variant="primary"); submitBtn2.style(size="sm")
resetBtn2 = gr.Button("重置", variant="secondary"); resetBtn2.style(size="sm")
stopBtn2 = gr.Button("停止", variant="secondary"); stopBtn2.style(size="sm")
clearBtn2 = gr.Button("清除", variant="secondary", visible=False); clearBtn2.style(size="sm")
Expand All @@ -152,12 +177,12 @@ def fn_area_visibility(a):
ret = {}
ret.update({area_basic_fn: gr.update(visible=("基础功能区" in a))})
ret.update({area_crazy_fn: gr.update(visible=("函数插件区" in a))})
ret.update({area_input_primary: gr.update(visible=("底部输入区" not in a))})
ret.update({area_input_secondary: gr.update(visible=("底部输入区" in a))})
ret.update({area_input_primary: gr.update(visible=("浮动输入区" not in a))})
ret.update({area_input_secondary: gr.update(visible=("浮动输入区" in a))})
ret.update({clearBtn: gr.update(visible=("输入清除键" in a))})
ret.update({clearBtn2: gr.update(visible=("输入清除键" in a))})
ret.update({plugin_advanced_arg: gr.update(visible=("插件参数区" in a))})
if "底部输入区" in a: ret.update({txt: gr.update(value="")})
if "浮动输入区" in a: ret.update({txt: gr.update(value="")})
return ret
checkboxes.select(fn_area_visibility, [checkboxes], [area_basic_fn, area_crazy_fn, area_input_primary, area_input_secondary, txt, txt2, clearBtn, clearBtn2, plugin_advanced_arg] )
# 整理反复出现的控件句柄组合
Expand Down Expand Up @@ -185,6 +210,7 @@ def fn_area_visibility(a):
cancel_handles.append(click_handle)
# 文件上传区,接收文件后与chatbot的互动
file_upload.upload(on_file_uploaded, [file_upload, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies])
file_upload_2.upload(on_file_uploaded, [file_upload_2, chatbot, txt, txt2, checkboxes, cookies], [chatbot, txt, txt2, cookies])
# 函数插件-固定按钮区
for k in plugins:
if not plugins[k].get("AsButton", True): continue
Expand All @@ -194,7 +220,8 @@ def fn_area_visibility(a):
# 函数插件-下拉菜单与随变按钮的互动
def on_dropdown_changed(k):
variant = plugins[k]["Color"] if "Color" in plugins[k] else "secondary"
ret = {switchy_bt: gr.update(value=k, variant=variant)}
info = plugins[k].get("Info", k)
ret = {switchy_bt: gr.update(value=k, variant=variant, info_str=f'函数插件区: {info}')}
if plugins[k].get("AdvancedArgs", False): # 是否唤起高级插件参数区
ret.update({plugin_advanced_arg: gr.update(visible=True, label=f"插件[{k}]的高级参数说明:" + plugins[k].get("ArgsReminder", [f"没有提供高级参数功能说明"]))})
else:
Expand Down Expand Up @@ -267,7 +294,7 @@ def init_cookie(cookies, chatbot):
cookies.update({'uuid': uuid.uuid4()})
return cookies
demo.load(init_cookie, inputs=[cookies, chatbot], outputs=[cookies])
demo.load(lambda: 0, inputs=None, outputs=None, _js='()=>{GptAcademicJavaScriptInit();}')
demo.load(None, inputs=[gr.Textbox(LAYOUT, visible=False)], outputs=None, _js='(LAYOUT)=>{GptAcademicJavaScriptInit(LAYOUT);}')

# gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
def auto_opentab_delay():
Expand Down
29 changes: 29 additions & 0 deletions themes/common.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@
box-shadow: none;
}

#input-plugin-group .secondary-wrap.svelte-aqlk7e.svelte-aqlk7e.svelte-aqlk7e {
border: none;
min-width: 0;
}

/* hide selector label */
#input-plugin-group .svelte-1gfkn6j {
visibility: hidden;
Expand Down Expand Up @@ -82,4 +87,28 @@
/* input btns: clear, reset, stop */
#input-panel2 button {
min-width: min(80px, 100%);
}


#cbs {
background-color: var(--block-background-fill) !important;
}

#interact-panel .form {
border: hidden
}

.drag-area {
border: solid;
border-width: thin;
user-select: none;
padding-left: 2%;
}

.floating-component #input-panel2 {
border-top-left-radius: 0px;
border-top-right-radius: 0px;
border: solid;
border-width: thin;
border-top-width: 0;
}
22 changes: 13 additions & 9 deletions themes/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,8 @@ function chatbotContentChanged(attempt = 1, force = false) {
}
}

function GptAcademicJavaScriptInit() {
chatbotIndicator = gradioApp().querySelector('#gpt-chatbot > div.wrap');
var chatbotObserver = new MutationObserver(() => {
chatbotContentChanged(1);
});
chatbotObserver.observe(chatbotIndicator, { attributes: true, childList: true, subtree: true });

function chatbotAutoHeight(){
// 自动调整高度
function update_height(){
var { panel_height_target, chatbot_height, chatbot } = get_elements(true);
if (panel_height_target!=chatbot_height)
Expand Down Expand Up @@ -110,6 +105,15 @@ function GptAcademicJavaScriptInit() {
}, 50); // 每100毫秒执行一次
}

function GptAcademicJavaScriptInit(LAYOUT = "LEFT-RIGHT") {
chatbotIndicator = gradioApp().querySelector('#gpt-chatbot > div.wrap');
var chatbotObserver = new MutationObserver(() => {
chatbotContentChanged(1);
});
chatbotObserver.observe(chatbotIndicator, { attributes: true, childList: true, subtree: true });
if (LAYOUT === "LEFT-RIGHT") {chatbotAutoHeight();}
}

function get_elements(consider_state_panel=false) {
var chatbot = document.querySelector('#gpt-chatbot > div.wrap.svelte-18telvq');
if (!chatbot) {
Expand All @@ -118,14 +122,14 @@ function get_elements(consider_state_panel=false) {
const panel1 = document.querySelector('#input-panel').getBoundingClientRect();
const panel2 = document.querySelector('#basic-panel').getBoundingClientRect()
const panel3 = document.querySelector('#plugin-panel').getBoundingClientRect();
const panel4 = document.querySelector('#interact-panel').getBoundingClientRect();
// const panel4 = document.querySelector('#interact-panel').getBoundingClientRect();
const panel5 = document.querySelector('#input-panel2').getBoundingClientRect();
const panel_active = document.querySelector('#state-panel').getBoundingClientRect();
if (consider_state_panel || panel_active.height < 25){
document.state_panel_height = panel_active.height;
}
// 25 是chatbot的label高度, 16 是右侧的gap
var panel_height_target = panel1.height + panel2.height + panel3.height + panel4.height + panel5.height - 25 + 16*3;
var panel_height_target = panel1.height + panel2.height + panel3.height + 0 + 0 - 25 + 16*2;
// 禁止动态的state-panel高度影响
panel_height_target = panel_height_target + (document.state_panel_height-panel_active.height)
var panel_height_target = parseInt(panel_height_target);
Expand Down
9 changes: 3 additions & 6 deletions themes/contrast.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,9 @@ def adjust_theme():
button_cancel_text_color_dark="white",
)

if LAYOUT=="TOP-DOWN":
js = ""
else:
with open('themes/common.js', 'r', encoding='utf8') as f:
js = f"<script>{f.read()}</script>"

with open('themes/common.js', 'r', encoding='utf8') as f:
js = f"<script>{f.read()}</script>"

# 添加一个萌萌的看板娘
if ADD_WAIFU:
js += """
Expand Down
4 changes: 2 additions & 2 deletions themes/default.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
border-radius: 4px;
}

#plugin-panel .dropdown-arrow.svelte-p5edak {
width: 50px;
#plugin-panel .dropdown-arrow {
width: 25px;
}
#plugin-panel input.svelte-aqlk7e.svelte-aqlk7e.svelte-aqlk7e {
padding-left: 5px;
Expand Down
7 changes: 2 additions & 5 deletions themes/default.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,8 @@ def adjust_theme():
button_cancel_text_color_dark="white",
)

if LAYOUT=="TOP-DOWN":
js = ""
else:
with open('themes/common.js', 'r', encoding='utf8') as f:
js = f"<script>{f.read()}</script>"
with open('themes/common.js', 'r', encoding='utf8') as f:
js = f"<script>{f.read()}</script>"

# 添加一个萌萌的看板娘
if ADD_WAIFU:
Expand Down
Loading

0 comments on commit 6310b65

Please sign in to comment.