增加段落markdown 样式

This commit is contained in:
w_xiaolizu
2023-06-20 15:20:10 +08:00
parent f2ee6c3d95
commit 8bcb8dee18
6 changed files with 160 additions and 437 deletions

View File

@ -21,7 +21,7 @@ crazy_fns = get_crazy_functions()
gr.Chatbot.postprocess = format_io
# 做一些外观色彩上的调整
from theme import adjust_theme, advanced_css, custom_css
from theme import adjust_theme, advanced_css, custom_css, small_and_beautiful_theme
set_theme = adjust_theme()
@ -75,56 +75,16 @@ class ChatBot(ChatBotFrame):
self.chatbot = gr.Chatbot(elem_id='main_chatbot', label=f"当前模型:{LLM_MODEL}")
self.chatbot.style()
self.history = gr.State([])
temp_draw = [gr.HTML() for i in range(7)]
with gr.Box(elem_id='chat_box'):
with gr.Row():
gr.Button(elem_classes='sm_btn').style(size='sm', full_width=False)
gr.HTML(func_box.get_html("appearance_switcher.html").format(label=""), elem_id='user_input_tb', elem_classes="insert_block")
with gr.Row():
self.txt = gr.Textbox(show_label=False, placeholder="Input question here.", elem_classes='chat_input').style(container=False)
self.input_copy = gr.State('')
self.submitBtn = gr.Button("", variant="primary", elem_classes='submit_btn').style(full_width=False)
temp_draw = [gr.HTML() for i in range(4)]
with gr.Row():
self.status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行\n {proxy_info}", elem_id='debug_mes')
def draw_examples(self):
with gr.Column(elem_id='examples_col') as self.examples_column:
gr.Markdown('# Get Started Quickly')
with gr.Row():
hide_components = gr.Textbox(visible=False)
gr.Button.update = func_box.update_btn
self.example = [['今天伦敦天气怎么样?', '对2021年以后的世界和事件了解有限', self.submitBtn.update(elem_id='highlight_update')],
['今夕何夕,明月何月?', '偶尔会产生不正确的信息', self.submitBtn.update(elem_id='highlight_update')],
['怎么才能把学校给炸了?', '经过训练,会拒绝不适当的请求', self.submitBtn.update(elem_id='highlight_update')]]
self.example_inputs = [self.txt, hide_components, self.submitBtn]
self.guidance_example = gr.Examples(examples=self.example, inputs=self.example_inputs, label='基础对话')
self.guidance_plugins = gr.Dataset(components=[gr.HTML(visible=False)], samples=[['...'] for i in range(4)], label='高级功能', type='index')
self.guidance_plugins_state = gr.State()
self.guidance_news = gr.Examples(examples=func_box.git_log_list(), inputs=[hide_components, hide_components], label='News')
def plug_update(index, date_set):
variant = crazy_fns[date_set[index]]["Color"] if "Color" in crazy_fns[date_set[index]] else "secondary"
ret = {self.switchy_bt: self.switchy_bt.update(value=date_set[index], variant=variant, elem_id='highlight_update'),
self.tabs_inputs: gr.Tabs.update(selected='plug_tab'),
self.area_crazy_fn: self.area_crazy_fn.update(open=True)}
fns_value = func_box.txt_converter_json(str(crazy_fns[date_set[index]].get('Parameters', '')))
fns_lable = f"插件[{date_set[index]}]的高级参数说明:\n" + crazy_fns[date_set[index]].get("ArgsReminder", f"没有提供高级参数功能说明")
temp_dict = dict(visible=True, interactive=True, value=str(fns_value), label=fns_lable)
# 是否唤起高级插件参数区
if crazy_fns[date_set[index]].get("AdvancedArgs", False):
ret.update({self.plugin_advanced_arg: gr.update(**temp_dict)})
ret.update({self.area_crazy_fn: self.area_crazy_fn.update(open=False)})
else:
ret.update({self.plugin_advanced_arg: gr.update(visible=False, label=f"插件[{date_set[index]}]不需要高级参数。")})
return ret
self.guidance_plugins.select(fn=plug_update, inputs=[self.guidance_plugins, self.guidance_plugins_state],
outputs=[self.switchy_bt, self.plugin_advanced_arg, self.tabs_inputs,
self.area_crazy_fn])
self.txt = gr.Textbox(show_label=False, placeholder="Input question here.", elem_id='chat_txt').style(container=False)
self.input_copy = gr.State('')
self.submitBtn = gr.Button("提交", variant="primary", visible=False).style(full_width=False)
with gr.Row(elem_id='debug_mes'):
self.status = gr.Markdown(f"Tip: 按Enter提交, 按Shift+Enter换行。当前模型: {LLM_MODEL} \n {proxy_info}")
def __clear_input(self, inputs):
return '', inputs, self.examples_column.update(visible=False)
return '', inputs
def draw_prompt(self):
with gr.Row():
@ -132,18 +92,17 @@ class ChatBot(ChatBotFrame):
container=False)
self.pro_entry_btn = gr.Button("搜索", variant="primary").style(full_width=False, size="sm")
with gr.Row():
with gr.Accordion(label='Prompt usage frequency'):
self.pro_prompt_list = gr.Dataset(components=[gr.HTML(visible=False)], samples_per_page=10,
label='Results',
samples=[[". . ."] for i in range(20)], type='index')
self.pro_prompt_state = gr.State(self.pro_prompt_list)
self.pro_prompt_list = gr.Dataset(components=[gr.HTML(visible=False)], samples_per_page=10,
label="Prompt usage frequency",
samples=[[". . ."] for i in range(20)], type='index')
self.pro_prompt_state = gr.State(self.pro_prompt_list)
def draw_temp_edit(self):
with gr.Box():
with gr.Row():
with gr.Column(scale=100):
self.pro_results = gr.Chatbot(label='Prompt and result', elem_id='prompt_result').style()
with gr.Column(scale=16):
with gr.Column(scale=11):
Tips = "用 BORF 分析法设计chat GPT prompt:\n" \
"1、阐述背景 B(Background): 说明背景为chatGPT提供充足的信息\n" \
"2、定义目标 O(Objectives):“我们希望实现什么”\n" \
@ -187,14 +146,18 @@ class ChatBot(ChatBotFrame):
self.pro_func_prompt, self.pro_fp_state])
self.pro_reuse_btn.click(
fn=func_box.reuse_chat,
inputs=[self.pro_results, self.chatbot, self.history, self.pro_name_txt, self.txt],
outputs=[self.chatbot, self.history, self.txt, self.tabs_chatbot, self.pro_name_txt, self.examples_column]
inputs=[self.pro_results, self.chatbot, self.history, self.pro_name_txt],
outputs=[self.chatbot, self.history, self.txt, self.tabs_chatbot, self.pro_name_txt]
)
def draw_function_chat(self):
prompt_list, devs_document = get_conf('prompt_list', 'devs_document')
with gr.TabItem('Function', id='func_tab'):
with gr.Accordion("基础功能区", open=False) as self.area_basic_fn:
with gr.Row():
# self.cpopyBtn = gr.Button("复制回答", variant="secondary").style(size="sm")
self.resetBtn = gr.Button("新建对话", variant="secondary", elem_id='empty_btn').style(size="sm")
self.stopBtn = gr.Button("中止对话", variant="stop").style(size="sm")
with gr.Tab('Function'):
with gr.Accordion("基础功能区", open=True) as self.area_basic_fn:
with gr.Row():
for k in functional:
variant = functional[k]["Color"] if "Color" in functional[k] else "secondary"
@ -206,7 +169,7 @@ class ChatBot(ChatBotFrame):
label=f'上传你的Prompt文件, 编写格式请遵循上述开发者文档', )
self.pro_private_check = gr.CheckboxGroup(choices=prompt_list['key'], value=prompt_list['value'],
label='选择展示Prompt')
self.pro_func_prompt = gr.Dataset(components=[gr.HTML()], label="Prompt List", visible=False,
self.pro_func_prompt = gr.Dataset(components=[gr.HTML()], label="All Prompt", visible=False,
samples=[['...', ""] for i in range(20)], type='index',
samples_per_page=10)
self.pro_fp_state = gr.State(self.pro_func_prompt)
@ -226,7 +189,7 @@ class ChatBot(ChatBotFrame):
self.prompt_tab.select(fn=lambda: 1, inputs=None, outputs=self.tabs_code)
def draw_public_chat(self):
with gr.TabItem('Plugins', id='plug_tab'):
with gr.Tab('Plugins'):
with gr.Accordion("上传本地文件可供高亮函数插件调用", open=False) as self.area_file_up:
self.file_upload = gr.Files(label="任何文件, 但推荐上传压缩文件(zip, tar)",
file_count="multiple")
@ -241,23 +204,23 @@ class ChatBot(ChatBotFrame):
self.variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
crazy_fns[k]["Button"] = gr.Button(k, variant=self.variant)
crazy_fns[k]["Button"].style(size="sm")
with gr.Accordion("更多函数插件/高级用法", open=True):
dropdown_fn_list = []
for k in crazy_fns.keys():
if not crazy_fns[k].get("AsButton", True):
dropdown_fn_list.append(k)
elif crazy_fns[k].get('AdvancedArgs', False):
dropdown_fn_list.append(k)
self.dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(
container=False)
self.plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False,
placeholder="这里是特殊函数插件的高级参数输入区").style(container=False)
self.switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
with gr.Accordion("更多函数插件/高级用法", open=True):
dropdown_fn_list = []
for k in crazy_fns.keys():
if not crazy_fns[k].get("AsButton", True):
dropdown_fn_list.append(k)
elif crazy_fns[k].get('AdvancedArgs', False):
dropdown_fn_list.append(k)
self.dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(
container=False)
self.plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False,
placeholder="这里是特殊函数插件的高级参数输入区").style(container=False)
self.switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
def draw_setting_chat(self):
switch_model = get_conf('switch_model')[0]
with gr.TabItem('Settings', id='sett_tab'):
with gr.Tab('Settings'):
self.top_p = gr.Slider(minimum=-0, maximum=1.0, value=1.0, step=0.01, interactive=True,
label="Top-p (nucleus sampling)", ).style(container=False)
self.temperature = gr.Slider(minimum=-0, maximum=2.0, value=1.0, step=0.01, interactive=True,
@ -307,13 +270,12 @@ class ChatBot(ChatBotFrame):
self.system_prompt, self.models_box, self.plugin_advanced_arg]
self.output_combo = [self.cookies, self.chatbot, self.history, self.status]
self.predict_args = dict(fn=ArgsGeneralWrapper(predict), inputs=self.input_combo, outputs=self.output_combo)
self.clear_agrs = dict(fn=self.__clear_input, inputs=[self.txt], outputs=[self.txt, self.input_copy,
self.examples_column])
self.clear_agrs = dict(fn=self.__clear_input, inputs=[self.txt], outputs=[self.txt, self.input_copy])
# 提交按钮、重置按钮
self.cancel_handles.append(self.txt.submit(**self.clear_agrs).then(**self.predict_args))
self.cancel_handles.append(self.submitBtn.click(**self.clear_agrs).then(**self.predict_args))
# self.cpopyBtn.click(fn=func_box.copy_result, inputs=[self.history], outputs=[self.status])
self.resetBtn.click(lambda: ([], [], "已重置"), None, [self.chatbot, self.history, self.status], _js='()=>{clearHistoryHtml();}')
self.resetBtn.click(lambda: ([], [], "已重置"), None, [self.chatbot, self.history, self.status])
def signals_function(self):
# 基础功能区的回调函数注册
@ -334,8 +296,8 @@ class ChatBot(ChatBotFrame):
if not crazy_fns[k].get("AsButton", True): continue
self.click_handle = crazy_fns[k]["Button"].click(**self.clear_agrs).then(
ArgsGeneralWrapper(crazy_fns[k]["Function"]), [*self.input_combo, gr.State(PORT)], self.output_combo)
self.click_handle.then(on_report_generated, [self.cookies, self.file_upload, self.chatbot],
[self.cookies, self.file_upload, self.chatbot])
self.click_handle.then(on_report_generated, [self.file_upload, self.chatbot],
[self.file_upload, self.chatbot])
# self.click_handle.then(fn=lambda x: '', inputs=[], outputs=self.txt)
self.cancel_handles.append(self.click_handle)
@ -343,7 +305,7 @@ class ChatBot(ChatBotFrame):
def on_dropdown_changed(k):
# 按钮颜色随变
variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
ret = {self.switchy_bt: self.switchy_bt.update(value=k, variant=variant)}
ret = {self.switchy_bt: gr.update(value=k, variant=variant)}
# 参数取随变
fns_value = func_box.txt_converter_json(str(crazy_fns[k].get('Parameters', '')))
fns_lable = f"插件[{k}]的高级参数说明:\n" + crazy_fns[k].get("ArgsReminder", f"没有提供高级参数功能说明")
@ -354,20 +316,16 @@ class ChatBot(ChatBotFrame):
else:
ret.update({self.plugin_advanced_arg: gr.update(visible=False, label=f"插件[{k}]不需要高级参数。")})
return ret
self.dropdown.select(on_dropdown_changed, [self.dropdown], [self.switchy_bt, self.plugin_advanced_arg])
# 随变按钮的回调函数注册
def route(k, ipaddr: gr.Request, *args, **kwargs):
if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
append = list(args)
append[-2] = func_box.txt_converter_json(append[-2])
append.insert(-1, ipaddr)
args = tuple(append)
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
self.click_handle = self.switchy_bt.click(**self.clear_agrs).then(route, [self.switchy_bt, *self.input_combo, gr.State(PORT)], self.output_combo)
self.click_handle.then(on_report_generated, [self.cookies, self.file_upload, self.chatbot], [self.cookies, self.file_upload, self.chatbot])
self.click_handle.then(on_report_generated, [self.file_upload, self.chatbot], [self.file_upload, self.chatbot])
self.cancel_handles.append(self.click_handle)
# 终止按钮的回调函数注册
self.stopBtn.click(fn=None, inputs=None, outputs=None, cancels=self.cancel_handles)
@ -378,12 +336,13 @@ class ChatBot(ChatBotFrame):
self.md_dropdown.select(on_md_dropdown_changed, [self.md_dropdown], [self.chatbot])
def signals_auto_input(self):
from autogpt.cli import agent_main
self.auto_input_combo = [self.ai_name, self.ai_role, self.ai_goal_list, self.ai_budget,
self.cookies, self.chatbot, self.history,
self.agent_obj]
self.auto_output_combo = [self.cookies, self.chatbot, self.history, self.status,
self.agent_obj, self.submit_start, self.submit_next, self.text_continue]
self.submit_start.click(fn=agent_main, inputs=self.auto_input_combo, outputs=self.auto_output_combo)
# gradio的inbrowser触发不太稳定回滚代码到原始的浏览器打开函数
def auto_opentab_delay(self, is_open=False):
@ -410,19 +369,13 @@ class ChatBot(ChatBotFrame):
# 绘制一个ROWrow会让底下的元素自动排成一行
with gr.Row().style(justify='between'):
# 绘制列1
with gr.Column(scale=44):
with gr.Column(scale=46):
with gr.Tabs() as self.tabs_copilot:
# 绘制对话模组
with gr.TabItem('Chat-Copilot'):
with gr.Row():
# self.cpopyBtn = gr.Button("复制回答", variant="secondary").style(size="sm")
self.resetBtn = gr.Button("新建对话", variant="primary", elem_id='empty_btn').style(
size="sm")
self.stopBtn = gr.Button("中止对话", variant="stop").style(size="sm")
with gr.Tabs() as self.tabs_inputs:
self.draw_function_chat()
self.draw_public_chat()
self.draw_setting_chat()
self.draw_function_chat()
self.draw_public_chat()
self.draw_setting_chat()
# 绘制autogpt模组
with gr.TabItem('Auto-GPT'):
@ -439,7 +392,6 @@ class ChatBot(ChatBotFrame):
with self.chat_tab: # 使用 gr.State()对组件进行拷贝时如果之前绘制了Markdown格式会导致启动崩溃,所以将 markdown相关绘制放在最后
self.draw_chatbot()
self.draw_examples()
with self.prompt_tab:
self.draw_temp_edit()
# 函数注册需要在Blocks下进行
@ -449,10 +401,7 @@ class ChatBot(ChatBotFrame):
self.signals_public()
self.signals_prompt_edit()
# self.signals_auto_input()
adv_plugins = gr.State([i for i in crazy_fns])
self.demo.load(fn=func_box.refresh_load_data, postprocess=False,
inputs=[self.chatbot, self.history, self.pro_fp_state, adv_plugins],
outputs=[self.pro_func_prompt, self.pro_fp_state, self.chatbot, self.history, self.guidance_plugins, self.guidance_plugins_state])
self.demo.load(fn=func_box.refresh_load_data, postprocess=False, inputs=[self.chatbot, self.history, self.pro_fp_state], outputs=[self.pro_func_prompt, self.pro_fp_state, self.chatbot, self.history, ])
# Start
self.auto_opentab_delay()