优化代码! 真的最有一次优化isay的逻辑了!!!!
This commit is contained in:
50
__main__.py
50
__main__.py
@ -21,7 +21,7 @@ crazy_fns = get_crazy_functions()
|
|||||||
gr.Chatbot.postprocess = format_io
|
gr.Chatbot.postprocess = format_io
|
||||||
|
|
||||||
# 做一些外观色彩上的调整
|
# 做一些外观色彩上的调整
|
||||||
from theme import adjust_theme, advanced_css, small_and_beautiful_theme
|
from theme import adjust_theme, advanced_css, custom_css, small_and_beautiful_theme
|
||||||
|
|
||||||
set_theme = adjust_theme()
|
set_theme = adjust_theme()
|
||||||
|
|
||||||
@ -210,8 +210,7 @@ class ChatBot(ChatBotFrame):
|
|||||||
self.dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(
|
self.dropdown = gr.Dropdown(dropdown_fn_list, value=r"打开插件列表", label="").style(
|
||||||
container=False)
|
container=False)
|
||||||
self.plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False,
|
self.plugin_advanced_arg = gr.Textbox(show_label=True, label="高级参数输入区", visible=False,
|
||||||
placeholder="这里是特殊函数插件的高级参数输入区").style(
|
placeholder="这里是特殊函数插件的高级参数输入区").style(container=False)
|
||||||
container=False)
|
|
||||||
self.switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
|
self.switchy_bt = gr.Button(r"请先从插件列表中选择", variant="secondary")
|
||||||
|
|
||||||
|
|
||||||
@ -234,6 +233,32 @@ class ChatBot(ChatBotFrame):
|
|||||||
container=False)
|
container=False)
|
||||||
# temp = gr.Markdown(self.description)
|
# temp = gr.Markdown(self.description)
|
||||||
|
|
||||||
|
def draw_goals_auto(self):
|
||||||
|
with gr.Row():
|
||||||
|
self.ai_name = gr.Textbox(show_label=False, placeholder="给Ai一个名字").style(container=False)
|
||||||
|
with gr.Row():
|
||||||
|
self.ai_role = gr.Textbox(lines=5, show_label=False, placeholder="请输入你的需求").style(
|
||||||
|
container=False)
|
||||||
|
with gr.Row():
|
||||||
|
self.ai_goal_list = gr.Dataframe(headers=['Goals'], interactive=True, row_count=4,
|
||||||
|
col_count=(1, 'fixed'), type='array')
|
||||||
|
with gr.Row():
|
||||||
|
self.ai_budget = gr.Number(show_label=False, value=0.0,
|
||||||
|
info="关于本次项目的预算,超过预算自动停止,默认无限").style(container=False)
|
||||||
|
|
||||||
|
|
||||||
|
def draw_next_auto(self):
|
||||||
|
with gr.Row():
|
||||||
|
self.text_continue = gr.Textbox(visible=False, show_label=False,
|
||||||
|
placeholder="请根据提示输入执行命令").style(container=False)
|
||||||
|
with gr.Row():
|
||||||
|
self.submit_start = gr.Button("Start", variant='primary')
|
||||||
|
self.submit_next = gr.Button("Next", visible=False, variant='primary')
|
||||||
|
self.submit_stop = gr.Button("Stop", variant="stop")
|
||||||
|
self.agent_obj = gr.State({'obj': None, "start": self.submit_start,
|
||||||
|
"next": self.submit_next, "text": self.text_continue})
|
||||||
|
|
||||||
|
|
||||||
def signals_input_setting(self):
|
def signals_input_setting(self):
|
||||||
# 注册input
|
# 注册input
|
||||||
self.input_combo = [self.cookies, self.max_length_sl, self.md_dropdown,
|
self.input_combo = [self.cookies, self.max_length_sl, self.md_dropdown,
|
||||||
@ -274,12 +299,16 @@ class ChatBot(ChatBotFrame):
|
|||||||
|
|
||||||
# 函数插件-下拉菜单与随变按钮的互动
|
# 函数插件-下拉菜单与随变按钮的互动
|
||||||
def on_dropdown_changed(k):
|
def on_dropdown_changed(k):
|
||||||
# variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
|
# 按钮颜色随变
|
||||||
# return {self.switchy_bt: gr.update(value=k, variant=variant)}
|
|
||||||
variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
|
variant = crazy_fns[k]["Color"] if "Color" in crazy_fns[k] else "secondary"
|
||||||
ret = {self.switchy_bt: gr.update(value=k, variant=variant)}
|
ret = {self.switchy_bt: gr.update(value=k, variant=variant)}
|
||||||
if crazy_fns[k].get("AdvancedArgs", False): # 是否唤起高级插件参数区
|
# 参数取随变
|
||||||
ret.update({self.plugin_advanced_arg: gr.update(visible=True, interactive=True, label=f"插件[{k}]的高级参数说明:" + crazy_fns[k].get("ArgsReminder", [f"没有提供高级参数功能说明"]))})
|
fns_value = func_box.txt_converter_json(str(crazy_fns[k].get('Parameters', '')))
|
||||||
|
fns_lable = f"插件[{k}]的高级参数说明:\n" + crazy_fns[k].get("ArgsReminder", f"没有提供高级参数功能说明")
|
||||||
|
temp_dict = dict(visible=True, interactive=True, value=str(fns_value), label=fns_lable)
|
||||||
|
# 是否唤起高级插件参数区
|
||||||
|
if crazy_fns[k].get("AdvancedArgs", False):
|
||||||
|
ret.update({self.plugin_advanced_arg: gr.update(**temp_dict)})
|
||||||
else:
|
else:
|
||||||
ret.update({self.plugin_advanced_arg: gr.update(visible=False, label=f"插件[{k}]不需要高级参数。")})
|
ret.update({self.plugin_advanced_arg: gr.update(visible=False, label=f"插件[{k}]不需要高级参数。")})
|
||||||
return ret
|
return ret
|
||||||
@ -290,6 +319,7 @@ class ChatBot(ChatBotFrame):
|
|||||||
def route(k, ipaddr: gr.Request, *args, **kwargs):
|
def route(k, ipaddr: gr.Request, *args, **kwargs):
|
||||||
if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
|
if k in [r"打开插件列表", r"请先从插件列表中选择"]: return
|
||||||
append = list(args)
|
append = list(args)
|
||||||
|
append[-1] = func_box.txt_converter_json(append[-1])
|
||||||
append.insert(-1, ipaddr)
|
append.insert(-1, ipaddr)
|
||||||
args = tuple(append)
|
args = tuple(append)
|
||||||
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
|
yield from ArgsGeneralWrapper(crazy_fns[k]["Function"])(*args, **kwargs)
|
||||||
@ -305,6 +335,7 @@ class ChatBot(ChatBotFrame):
|
|||||||
|
|
||||||
self.md_dropdown.select(on_md_dropdown_changed, [self.md_dropdown], [self.chatbot])
|
self.md_dropdown.select(on_md_dropdown_changed, [self.md_dropdown], [self.chatbot])
|
||||||
|
|
||||||
|
|
||||||
# gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
|
# gradio的inbrowser触发不太稳定,回滚代码到原始的浏览器打开函数
|
||||||
def auto_opentab_delay(self, is_open=False):
|
def auto_opentab_delay(self, is_open=False):
|
||||||
import threading, webbrowser, time
|
import threading, webbrowser, time
|
||||||
@ -323,9 +354,8 @@ class ChatBot(ChatBotFrame):
|
|||||||
|
|
||||||
|
|
||||||
def main(self):
|
def main(self):
|
||||||
with open("docs/assets/custom.css", "r", encoding="utf-8") as f:
|
|
||||||
customCSS = f.read()
|
with gr.Blocks(title="Chatbot for KSO ", theme=set_theme, analytics_enabled=False, css=custom_css) as demo:
|
||||||
with gr.Blocks(title="Chatbot for KSO ", theme=set_theme, analytics_enabled=False, css=customCSS) as demo:
|
|
||||||
# 绘制页面title
|
# 绘制页面title
|
||||||
self.draw_title()
|
self.draw_title()
|
||||||
# 绘制一个ROW,row会让底下的元素自动排成一行
|
# 绘制一个ROW,row会让底下的元素自动排成一行
|
||||||
|
|||||||
@ -1,5 +0,0 @@
|
|||||||
#! .\venv\
|
|
||||||
# encoding: utf-8
|
|
||||||
# @Time : 2023/6/15
|
|
||||||
# @Author : Spike
|
|
||||||
# @Descr :
|
|
||||||
@ -1,5 +0,0 @@
|
|||||||
#! .\venv\
|
|
||||||
# encoding: utf-8
|
|
||||||
# @Time : 2023/6/14
|
|
||||||
# @Author : Spike
|
|
||||||
# @Descr :
|
|
||||||
@ -1,30 +0,0 @@
|
|||||||
#! .\venv\
|
|
||||||
# encoding: utf-8
|
|
||||||
# @Time : 2023/5/23
|
|
||||||
# @Author : Spike
|
|
||||||
# @Descr :
|
|
||||||
import json
|
|
||||||
from toolbox import CatchException, update_ui
|
|
||||||
from crazy_functions.crazy_utils import request_gpt_model_in_new_thread_with_ui_alive, input_clipping
|
|
||||||
import func_box
|
|
||||||
|
|
||||||
|
|
||||||
class ParseNoteBook:
|
|
||||||
|
|
||||||
def __init__(self, file):
|
|
||||||
self.file = file
|
|
||||||
|
|
||||||
def load_dict(self):
|
|
||||||
with open(self.file, 'r', encoding='utf-8', errors='replace') as f:
|
|
||||||
return json.load(f)
|
|
||||||
|
|
||||||
|
|
||||||
@CatchException
|
|
||||||
def 翻译理解jupyter(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
obj = ParseNoteBook('/Users/kilig/Desktop/jupy/NotarizedUpload.ipynb').load_dict()
|
|
||||||
print(obj['cells'])
|
|
||||||
|
|
||||||
35
func_box.py
35
func_box.py
@ -403,7 +403,7 @@ def prompt_save(txt, name, prompt: gr.Dataset, ipaddr: gr.Request):
|
|||||||
return txt, name, [], prompt.update(samples=result, visible=True), prompt
|
return txt, name, [], prompt.update(samples=result, visible=True), prompt
|
||||||
|
|
||||||
|
|
||||||
def prompt_input(txt, index, data: gr.Dataset):
|
def prompt_input(txt: str, index, data: gr.Dataset, tabs_index):
|
||||||
"""
|
"""
|
||||||
点击dataset的值使用Prompt
|
点击dataset的值使用Prompt
|
||||||
Args:
|
Args:
|
||||||
@ -414,11 +414,18 @@ def prompt_input(txt, index, data: gr.Dataset):
|
|||||||
返回注册函数所需的对象
|
返回注册函数所需的对象
|
||||||
"""
|
"""
|
||||||
data_str = str(data.samples[index][1])
|
data_str = str(data.samples[index][1])
|
||||||
if txt:
|
data_name = str(data.samples[index][0])
|
||||||
txt = data_str + '\n' + txt
|
rp_str = '"""{v}"""'
|
||||||
|
if data_str.find(rp_str) != -1:
|
||||||
|
new_txt = data_str.replace(rp_str, txt)
|
||||||
|
elif txt and tabs_index == 0:
|
||||||
|
new_txt = data_str + '\n' + txt
|
||||||
else:
|
else:
|
||||||
txt = data_str
|
new_txt = data_str
|
||||||
return txt
|
if tabs_index == 1:
|
||||||
|
return txt, new_txt, data_name
|
||||||
|
else:
|
||||||
|
return new_txt, '', ''
|
||||||
|
|
||||||
|
|
||||||
def copy_result(history):
|
def copy_result(history):
|
||||||
@ -484,7 +491,7 @@ prompt_path = os.path.join(base_path, 'prompt_users')
|
|||||||
def reuse_chat(result, chatbot, history, pro_numb):
|
def reuse_chat(result, chatbot, history, pro_numb):
|
||||||
"""复用对话记录"""
|
"""复用对话记录"""
|
||||||
if result is None or result == []:
|
if result is None or result == []:
|
||||||
pass
|
return chatbot, history, gr.update(), gr.update(), ''
|
||||||
else:
|
else:
|
||||||
if pro_numb:
|
if pro_numb:
|
||||||
chatbot += result
|
chatbot += result
|
||||||
@ -505,6 +512,7 @@ def num_tokens_from_string(listing: list, encoding_name: str = 'cl100k_base') ->
|
|||||||
count_tokens += len(encoding.encode(i))
|
count_tokens += len(encoding.encode(i))
|
||||||
return count_tokens
|
return count_tokens
|
||||||
|
|
||||||
|
|
||||||
def spinner_chatbot_loading(chatbot):
|
def spinner_chatbot_loading(chatbot):
|
||||||
loading = [''.join(['.' * random.randint(1, 5)])]
|
loading = [''.join(['.' * random.randint(1, 5)])]
|
||||||
# 将元组转换为列表并修改元素
|
# 将元组转换为列表并修改元素
|
||||||
@ -518,6 +526,21 @@ def spinner_chatbot_loading(chatbot):
|
|||||||
loading_msg[-1] = tuple(temp_list)
|
loading_msg[-1] = tuple(temp_list)
|
||||||
return loading_msg
|
return loading_msg
|
||||||
|
|
||||||
|
|
||||||
|
def txt_converter_json(input_string):
|
||||||
|
try:
|
||||||
|
if input_string.startswith("{") and input_string.endswith("}"):
|
||||||
|
# 尝试将字符串形式的字典转换为字典对象
|
||||||
|
dict_object = ast.literal_eval(input_string)
|
||||||
|
else:
|
||||||
|
# 尝试将字符串解析为JSON对象
|
||||||
|
dict_object = json.loads(input_string)
|
||||||
|
formatted_json_string = json.dumps(dict_object, indent=4, ensure_ascii=False)
|
||||||
|
return formatted_json_string
|
||||||
|
except (ValueError, SyntaxError):
|
||||||
|
return input_string
|
||||||
|
|
||||||
|
|
||||||
class YamlHandle:
|
class YamlHandle:
|
||||||
|
|
||||||
def __init__(self, file=os.path.join(prompt_path, 'ai_common.yaml')):
|
def __init__(self, file=os.path.join(prompt_path, 'ai_common.yaml')):
|
||||||
|
|||||||
@ -259,6 +259,7 @@ def report_execption(chatbot, history, a, b):
|
|||||||
|
|
||||||
import re
|
import re
|
||||||
|
|
||||||
|
|
||||||
def text_divide_paragraph(input_str):
|
def text_divide_paragraph(input_str):
|
||||||
if input_str:
|
if input_str:
|
||||||
# 提取所有的代码块
|
# 提取所有的代码块
|
||||||
@ -284,13 +285,13 @@ def text_divide_paragraph(input_str):
|
|||||||
else:
|
else:
|
||||||
# 对于没有反引号的字符串,针对四个空格之前的换行符进行处理
|
# 对于没有反引号的字符串,针对四个空格之前的换行符进行处理
|
||||||
lines = input_str.split('\n')
|
lines = input_str.split('\n')
|
||||||
if not any(line.startswith(' ') for line in lines):
|
|
||||||
for idx, line in enumerate(lines[:-1]):
|
for idx, line in enumerate(lines[:-1]):
|
||||||
if not line.strip():
|
if not line.strip():
|
||||||
continue
|
continue
|
||||||
if not (lines[idx + 1].startswith(' ') or lines[idx + 1].startswith('\t')):
|
if not (lines[idx + 1].startswith(' ') or lines[idx + 1].startswith('\t')):
|
||||||
lines[idx] += '\n' # 将一个换行符替换为两个换行符
|
lines[idx] += '\n' # 将一个换行符替换为两个换行符
|
||||||
input_str = '\n'.join(lines)
|
input_str = '\n'.join(lines)
|
||||||
|
|
||||||
return input_str
|
return input_str
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user