Skip to content

Commit 8a10db6

Browse files
committed
Merge branch 'master-interact'
1 parent 1fe66f0 commit 8a10db6

File tree

6 files changed

+184
-30
lines changed

6 files changed

+184
-30
lines changed

crazy_functional.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,18 @@ def get_crazy_functions():
352352
})
353353
except:
354354
print('Load function plugin failed')
355+
356+
try:
357+
from crazy_functions.交互功能函数模板 import 交互功能模板函数
358+
function_plugins.update({
359+
"交互功能模板函数": {
360+
"Color": "stop",
361+
"AsButton": False,
362+
"Function": HotReload(交互功能模板函数)
363+
}
364+
})
365+
except:
366+
print('Load function plugin failed')
355367

356368
try:
357369
from crazy_functions.Latex输出PDF结果 import Latex英文纠错加PDF对比
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from toolbox import CatchException, update_ui
2+
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
3+
4+
5+
@CatchException
6+
def 交互功能模板函数(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
7+
"""
8+
txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径
9+
llm_kwargs gpt模型参数, 如温度和top_p等, 一般原样传递下去就行
10+
plugin_kwargs 插件模型的参数, 如温度和top_p等, 一般原样传递下去就行
11+
chatbot 聊天显示框的句柄,用于显示给用户
12+
history 聊天历史,前情提要
13+
system_prompt 给gpt的静默提醒
14+
web_port 当前软件运行的端口号
15+
"""
16+
history = [] # 清空历史,以免输入溢出
17+
chatbot.append(("这是什么功能?", "交互功能函数模板。在执行完成之后, 可以将自身的状态存储到cookie中, 等待用户的再次调用。"))
18+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
19+
20+
state = chatbot._cookies.get('plugin_state_0001', None) # 初始化插件状态
21+
22+
if state is None:
23+
chatbot._cookies['lock_plugin'] = 'crazy_functions.交互功能函数模板->交互功能模板函数' # 赋予插件锁定 锁定插件回调路径,当下一次用户提交时,会直接转到该函数
24+
chatbot._cookies['plugin_state_0001'] = 'wait_user_keyword' # 赋予插件状态
25+
26+
chatbot.append(("第一次调用:", "请输入关键词, 我将为您查找相关壁纸, 建议使用英文单词, 插件锁定中,请直接提交即可。"))
27+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
28+
return
29+
30+
if state == 'wait_user_keyword':
31+
chatbot._cookies['lock_plugin'] = None # 解除插件锁定,避免遗忘导致死锁
32+
chatbot._cookies['plugin_state_0001'] = None # 解除插件状态,避免遗忘导致死锁
33+
34+
# 解除插件锁定
35+
chatbot.append((f"获取关键词:{txt}", ""))
36+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
37+
page_return = get_image_page_by_keyword(txt)
38+
inputs=inputs_show_user=f"Extract all image urls in this html page, pick the first 5 images and show them with markdown format: \n\n {page_return}"
39+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
40+
inputs=inputs, inputs_show_user=inputs_show_user,
41+
llm_kwargs=llm_kwargs, chatbot=chatbot, history=[],
42+
sys_prompt="When you want to show an image, use markdown format. e.g. ![image_description](image_url). If there are no image url provided, answer 'no image url provided'"
43+
)
44+
chatbot[-1] = [chatbot[-1][0], gpt_say]
45+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
46+
return
47+
48+
49+
50+
# ---------------------------------------------------------------------------------
51+
52+
def get_image_page_by_keyword(keyword):
53+
import requests
54+
from bs4 import BeautifulSoup
55+
response = requests.get(f'https://wallhaven.cc/search?q={keyword}', timeout=2)
56+
res = "image urls: \n"
57+
for image_element in BeautifulSoup(response.content, 'html.parser').findAll("img"):
58+
try:
59+
res += image_element["data-src"]
60+
res += "\n"
61+
except:
62+
pass
63+
return res

main.py

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,23 +45,23 @@ def main():
4545
proxy_info = check_proxy(proxies)
4646

4747
gr_L1 = lambda: gr.Row().style()
48-
gr_L2 = lambda scale: gr.Column(scale=scale)
48+
gr_L2 = lambda scale, elem_id: gr.Column(scale=scale, elem_id=elem_id)
4949
if LAYOUT == "TOP-DOWN":
5050
gr_L1 = lambda: DummyWith()
51-
gr_L2 = lambda scale: gr.Row()
51+
gr_L2 = lambda scale, elem_id: gr.Row()
5252
CHATBOT_HEIGHT /= 2
5353

5454
cancel_handles = []
5555
with gr.Blocks(title="ChatGPT 学术优化", theme=set_theme, analytics_enabled=False, css=advanced_css) as demo:
5656
gr.HTML(title_html)
5757
cookies = gr.State(load_chat_cookies())
5858
with gr_L1():
59-
with gr_L2(scale=2):
60-
chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}")
61-
chatbot.style(height=CHATBOT_HEIGHT)
59+
with gr_L2(scale=2, elem_id="gpt-chat"):
60+
chatbot = gr.Chatbot(label=f"当前模型:{LLM_MODEL}", elem_id="gpt-chatbot")
61+
if LAYOUT == "TOP-DOWN": chatbot.style(height=CHATBOT_HEIGHT)
6262
history = gr.State([])
63-
with gr_L2(scale=1):
64-
with gr.Accordion("输入区", open=True) as area_input_primary:
63+
with gr_L2(scale=1, elem_id="gpt-panel"):
64+
with gr.Accordion("输入区", open=True, elem_id="input-panel") as area_input_primary:
6565
with gr.Row():
6666
txt = gr.Textbox(show_label=False, placeholder="Input question here.").style(container=False)
6767
with gr.Row():
@@ -71,14 +71,14 @@ def main():
7171
stopBtn = gr.Button("停止", variant="secondary"); stopBtn.style(size="sm")
7272
clearBtn = gr.Button("清除", variant="secondary", visible=False); clearBtn.style(size="sm")
7373
with gr.Row():
74-
status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}")
75-
with gr.Accordion("基础功能区", open=True) as area_basic_fn:
74+
status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}", elem_id="state-panel")
75+
with gr.Accordion("基础功能区", open=True, elem_id="basic-panel") as area_basic_fn:
7676
with gr.Row():
7777
for k in functional:
7878
if ("Visible" in functional[k]) and (not functional[k]["Visible"]): continue
7979
variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
8080
functional[k]["Button"] = gr.Button(k, variant=variant)
81-
with gr.Accordion("函数插件区", open=True) as area_crazy_fn:
81+
with gr.Accordion("函数插件区", open=True, elem_id="plugin-panel") as area_crazy_fn:
8282
with gr.Row():
8383
gr.Markdown("注意:以下“红颜色”标识的函数插件需从输入区读取路径作为参数.")
8484
with gr.Row():
@@ -100,7 +100,7 @@ def main():
100100
with gr.Row():
101101
with gr.Accordion("点击展开“文件上传区”。上传本地文件可供红色函数插件调用。", open=False) as area_file_up:
102102
file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)", file_count="multiple")
103-
with gr.Accordion("更换模型 & SysPrompt & 交互界面布局", open=(LAYOUT == "TOP-DOWN")):
103+
with gr.Accordion("更换模型 & SysPrompt & 交互界面布局", open=(LAYOUT == "TOP-DOWN"), elem_id="interact-panel"):
104104
system_prompt = gr.Textbox(show_label=True, placeholder=f"System Prompt", label="System prompt", value=initial_prompt)
105105
top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01,interactive=True, label="Top-p (nucleus sampling)",)
106106
temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True, label="Temperature",)
@@ -109,7 +109,7 @@ def main():
109109
md_dropdown = gr.Dropdown(AVAIL_LLM_MODELS, value=LLM_MODEL, label="更换LLM模型/请求源").style(container=False)
110110

111111
gr.Markdown(description)
112-
with gr.Accordion("备选输入区", open=True, visible=False) as area_input_secondary:
112+
with gr.Accordion("备选输入区", open=True, visible=False, elem_id="input-panel2") as area_input_secondary:
113113
with gr.Row():
114114
txt2 = gr.Textbox(show_label=False, placeholder="Input question here.", label="输入区2").style(container=False)
115115
with gr.Row():
@@ -176,16 +176,17 @@ def on_md_dropdown_changed(k):
176176
return {chatbot: gr.update(label="当前模型:"+k)}
177177
md_dropdown.select(on_md_dropdown_changed, [md_dropdown], [chatbot] )
178178
# 随变按钮的回调函数注册
179-
def route(k, *args, **kwargs):
179+
def route(request: gr.Request, k, *args, **kwargs):
180180
if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
181-
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
181+
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(request, *args, **kwargs)
182182
click_handle = switchy_bt.click(route,[switchy_bt, *input_combo, gr.State(PORT)], output_combo)
183183
click_handle.then(on_report_generated, [cookies, file_upload, chatbot], [cookies, file_upload, chatbot])
184184
cancel_handles.append(click_handle)
185185
# 终止按钮的回调函数注册
186186
stopBtn.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
187187
stopBtn2.click(fn=None, inputs=None, outputs=None, cancels=cancel_handles)
188-
188+
demo.load(lambda: 0, inputs=None, outputs=None, _js='()=>{ChatBotHeight();}')
189+
189190
# gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
190191
def auto_opentab_delay():
191192
import threading, webbrowser, time

theme.py

Lines changed: 65 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import gradio as gr
22
from toolbox import get_conf
3-
CODE_HIGHLIGHT, ADD_WAIFU = get_conf('CODE_HIGHLIGHT', 'ADD_WAIFU')
3+
CODE_HIGHLIGHT, ADD_WAIFU, LAYOUT = get_conf('CODE_HIGHLIGHT', 'ADD_WAIFU', 'LAYOUT')
44
# gradio可用颜色列表
55
# gr.themes.utils.colors.slate (石板色)
66
# gr.themes.utils.colors.gray (灰色)
@@ -82,20 +82,76 @@ def adjust_theme():
8282
button_cancel_text_color_dark="white",
8383
)
8484

85+
# Layout = "LEFT-RIGHT"
86+
js = """
87+
<script>
88+
function ChatBotHeight() {
89+
function update_height(){
90+
var { panel_height_target, chatbot_height, chatbot } = get_elements();
91+
if (panel_height_target!=chatbot_height)
92+
{
93+
var pixelString = panel_height_target.toString() + 'px';
94+
chatbot.style.maxHeight = pixelString; chatbot.style.height = pixelString;
95+
}
96+
}
97+
98+
function update_height_slow(){
99+
var { panel_height_target, chatbot_height, chatbot } = get_elements();
100+
if (panel_height_target!=chatbot_height)
101+
{
102+
new_panel_height = (panel_height_target - chatbot_height)*0.5 + chatbot_height;
103+
if (Math.abs(new_panel_height - panel_height_target) < 10){
104+
new_panel_height = panel_height_target;
105+
}
106+
// console.log(chatbot_height, panel_height_target, new_panel_height);
107+
var pixelString = new_panel_height.toString() + 'px';
108+
chatbot.style.maxHeight = pixelString; chatbot.style.height = pixelString;
109+
}
110+
}
111+
112+
update_height();
113+
setInterval(function() {
114+
update_height_slow()
115+
}, 50); // 每100毫秒执行一次
116+
}
117+
118+
function get_elements() {
119+
var chatbot = document.querySelector('#gpt-chatbot > div.wrap.svelte-18telvq');
120+
if (!chatbot) {
121+
chatbot = document.querySelector('#gpt-chatbot');
122+
}
123+
const panel1 = document.querySelector('#input-panel');
124+
const panel2 = document.querySelector('#basic-panel');
125+
const panel3 = document.querySelector('#plugin-panel');
126+
const panel4 = document.querySelector('#interact-panel');
127+
const panel5 = document.querySelector('#input-panel2');
128+
const panel_active = document.querySelector('#state-panel');
129+
var panel_height_target = (20-panel_active.offsetHeight) + panel1.offsetHeight + panel2.offsetHeight + panel3.offsetHeight + panel4.offsetHeight + panel5.offsetHeight + 21;
130+
var panel_height_target = parseInt(panel_height_target);
131+
var chatbot_height = chatbot.style.height;
132+
var chatbot_height = parseInt(chatbot_height);
133+
return { panel_height_target, chatbot_height, chatbot };
134+
}
135+
</script>
136+
"""
137+
138+
if LAYOUT=="TOP-DOWN":
139+
js = ""
140+
85141
# 添加一个萌萌的看板娘
86142
if ADD_WAIFU:
87-
js = """
143+
js += """
88144
<script src="file=docs/waifu_plugin/jquery.min.js"></script>
89145
<script src="file=docs/waifu_plugin/jquery-ui.min.js"></script>
90146
<script src="file=docs/waifu_plugin/autoload.js"></script>
91147
"""
92-
gradio_original_template_fn = gr.routes.templates.TemplateResponse
93-
def gradio_new_template_fn(*args, **kwargs):
94-
res = gradio_original_template_fn(*args, **kwargs)
95-
res.body = res.body.replace(b'</html>', f'{js}</html>'.encode("utf8"))
96-
res.init_headers()
97-
return res
98-
gr.routes.templates.TemplateResponse = gradio_new_template_fn # override gradio template
148+
gradio_original_template_fn = gr.routes.templates.TemplateResponse
149+
def gradio_new_template_fn(*args, **kwargs):
150+
res = gradio_original_template_fn(*args, **kwargs)
151+
res.body = res.body.replace(b'</html>', f'{js}</html>'.encode("utf8"))
152+
res.init_headers()
153+
return res
154+
gr.routes.templates.TemplateResponse = gradio_new_template_fn # override gradio template
99155
except:
100156
set_theme = None
101157
print('gradio版本较旧, 不能自定义字体和颜色')

toolbox.py

Lines changed: 26 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import inspect
55
import re
66
import os
7+
import gradio
78
from latex2mathml.converter import convert as tex2mathml
89
from functools import wraps, lru_cache
910
pj = os.path.join
@@ -40,7 +41,7 @@ def ArgsGeneralWrapper(f):
4041
"""
4142
装饰器函数,用于重组输入参数,改变输入参数的顺序与结构。
4243
"""
43-
def decorated(cookies, max_length, llm_model, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg, *args):
44+
def decorated(request: gradio.Request, cookies, max_length, llm_model, txt, txt2, top_p, temperature, chatbot, history, system_prompt, plugin_advanced_arg, *args):
4445
txt_passon = txt
4546
if txt == "" and txt2 != "": txt_passon = txt2
4647
# 引入一个有cookie的chatbot
@@ -54,22 +55,43 @@ def decorated(cookies, max_length, llm_model, txt, txt2, top_p, temperature, cha
5455
'top_p':top_p,
5556
'max_length': max_length,
5657
'temperature':temperature,
58+
'client_ip': request.client.host,
5759
}
5860
plugin_kwargs = {
5961
"advanced_arg": plugin_advanced_arg,
6062
}
6163
chatbot_with_cookie = ChatBotWithCookies(cookies)
6264
chatbot_with_cookie.write_list(chatbot)
63-
yield from f(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, *args)
65+
if cookies.get('lock_plugin', None) is None:
66+
# 正常状态
67+
yield from f(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, *args)
68+
else:
69+
# 处理个别特殊插件的锁定状态
70+
module, fn_name = cookies['lock_plugin'].split('->')
71+
f_hot_reload = getattr(importlib.import_module(module, fn_name), fn_name)
72+
yield from f_hot_reload(txt_passon, llm_kwargs, plugin_kwargs, chatbot_with_cookie, history, system_prompt, *args)
6473
return decorated
6574

6675

6776
def update_ui(chatbot, history, msg='正常', **kwargs): # 刷新界面
6877
"""
6978
刷新用户界面
7079
"""
71-
assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时,可用clear将其清空,然后用for+append循环重新赋值。"
72-
yield chatbot.get_cookies(), chatbot, history, msg
80+
assert isinstance(chatbot, ChatBotWithCookies), "在传递chatbot的过程中不要将其丢弃。必要时, 可用clear将其清空, 然后用for+append循环重新赋值。"
81+
cookies = chatbot.get_cookies()
82+
83+
# 解决插件锁定时的界面显示问题
84+
if cookies.get('lock_plugin', None):
85+
label = cookies.get('llm_model', "") + " | " + "正在锁定插件" + cookies.get('lock_plugin', None)
86+
chatbot_gr = gradio.update(value=chatbot, label=label)
87+
if cookies.get('label', "") != label: cookies['label'] = label # 记住当前的label
88+
elif cookies.get('label', None):
89+
chatbot_gr = gradio.update(value=chatbot, label=cookies.get('llm_model', ""))
90+
cookies['label'] = None # 清空label
91+
else:
92+
chatbot_gr = chatbot
93+
94+
yield cookies, chatbot_gr, history, msg
7395

7496
def update_ui_lastest_msg(lastmsg, chatbot, history, delay=1): # 刷新界面
7597
"""

version

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"version": 3.43,
2+
"version": 3.44,
33
"show_feature": true,
4-
"new_feature": "修复Azure接口的BUG <-> 完善多语言模块 <-> 完善本地Latex矫错和翻译功能 <-> 增加gpt-3.5-16k的支持 <-> 新增最强Arxiv论文翻译插件 <-> 修复gradio复制按钮BUG <-> 修复PDF翻译的BUG, 新增HTML中英双栏对照 <-> 添加了OpenAI图片生成插件"
4+
"new_feature": "改善UI <-> 修复Azure接口的BUG <-> 完善多语言模块 <-> 完善本地Latex矫错和翻译功能 <-> 增加gpt-3.5-16k的支持 <-> 新增最强Arxiv论文翻译插件 <-> 修复gradio复制按钮BUG <-> 修复PDF翻译的BUG, 新增HTML中英双栏对照 <-> 添加了OpenAI图片生成插件"
55
}

0 commit comments

Comments
 (0)