From 9a21e13d33b1a553065b9ba89dd0d470d4ae93ad Mon Sep 17 00:00:00 2001 From: binary-husky Date: Mon, 13 Nov 2023 13:10:15 +0800 Subject: [PATCH 01/13] =?UTF-8?q?=E6=94=AF=E6=8C=81gpt-4-vision-preview?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- request_llms/bridge_all.py | 13 + request_llms/bridge_chatgpt_vision.py | 329 ++++++++++++++++++++++++++ toolbox.py | 7 +- 3 files changed, 347 insertions(+), 2 deletions(-) create mode 100644 request_llms/bridge_chatgpt_vision.py diff --git a/request_llms/bridge_all.py b/request_llms/bridge_all.py index 89c9f76c..88848a98 100644 --- a/request_llms/bridge_all.py +++ b/request_llms/bridge_all.py @@ -16,6 +16,9 @@ from toolbox import get_conf, trimmed_format_exc from .bridge_chatgpt import predict_no_ui_long_connection as chatgpt_noui from .bridge_chatgpt import predict as chatgpt_ui +from .bridge_chatgpt_vision import predict_no_ui_long_connection as chatgpt_vision_noui +from .bridge_chatgpt_vision import predict as chatgpt_vision_ui + from .bridge_chatglm import predict_no_ui_long_connection as chatglm_noui from .bridge_chatglm import predict as chatglm_ui @@ -162,6 +165,16 @@ model_info = { "token_cnt": get_token_num_gpt4, }, + "gpt-4-vision-preview": { + "fn_with_ui": chatgpt_vision_ui, + "fn_without_ui": chatgpt_vision_noui, + "endpoint": openai_endpoint, + "max_token": 4096, + "tokenizer": tokenizer_gpt4, + "token_cnt": get_token_num_gpt4, + }, + + # azure openai "azure-gpt-3.5":{ "fn_with_ui": chatgpt_ui, diff --git a/request_llms/bridge_chatgpt_vision.py b/request_llms/bridge_chatgpt_vision.py new file mode 100644 index 00000000..112391c7 --- /dev/null +++ b/request_llms/bridge_chatgpt_vision.py @@ -0,0 +1,329 @@ +""" + 该文件中主要包含三个函数 + + 不具备多线程能力的函数: + 1. predict: 正常对话时使用,具备完备的交互功能,不可多线程 + + 具备多线程调用能力的函数 + 2. predict_no_ui_long_connection:支持多线程 +""" + +import json +import time +import logging +import requests +import base64 +import os +import glob + +from toolbox import get_conf, update_ui, is_any_api_key, select_api_key, what_keys, clip_history, trimmed_format_exc, is_the_upload_folder, update_ui_lastest_msg, get_max_token +proxies, TIMEOUT_SECONDS, MAX_RETRY, API_ORG, AZURE_CFG_ARRAY = \ + get_conf('proxies', 'TIMEOUT_SECONDS', 'MAX_RETRY', 'API_ORG', 'AZURE_CFG_ARRAY') + +timeout_bot_msg = '[Local Message] Request timeout. Network error. Please check proxy settings in config.py.' + \ + '网络错误,检查代理服务器是否可用,以及代理设置的格式是否正确,格式须是[协议]://[地址]:[端口],缺一不可。' + +def have_any_recent_upload_image_files(chatbot): + _5min = 5 * 60 + if chatbot is None: return False, None # chatbot is None + most_recent_uploaded = chatbot._cookies.get("most_recent_uploaded", None) + if not most_recent_uploaded: return False, None # most_recent_uploaded is None + if time.time() - most_recent_uploaded["time"] < _5min: + most_recent_uploaded = chatbot._cookies.get("most_recent_uploaded", None) + path = most_recent_uploaded['path'] + file_manifest = [f for f in glob.glob(f'{path}/**/*.jpg', recursive=True)] + file_manifest += [f for f in glob.glob(f'{path}/**/*.jpeg', recursive=True)] + file_manifest += [f for f in glob.glob(f'{path}/**/*.png', recursive=True)] + if len(file_manifest) == 0: return False, None + return True, file_manifest # most_recent_uploaded is new + else: + return False, None # most_recent_uploaded is too old + +def report_invalid_key(key): + if get_conf("BLOCK_INVALID_APIKEY"): + # 实验性功能,自动检测并屏蔽失效的KEY,请勿使用 + from request_llms.key_manager import ApiKeyManager + api_key = ApiKeyManager().add_key_to_blacklist(key) + +def get_full_error(chunk, stream_response): + """ + 获取完整的从Openai返回的报错 + """ + while True: + try: + chunk += next(stream_response) + except: + break + return chunk + +def decode_chunk(chunk): + # 提前读取一些信息 (用于判断异常) + chunk_decoded = chunk.decode() + chunkjson = None + has_choices = False + choice_valid = False + has_content = False + has_role = False + try: + chunkjson = json.loads(chunk_decoded[6:]) + has_choices = 'choices' in chunkjson + if has_choices: choice_valid = (len(chunkjson['choices']) > 0) + if has_choices and choice_valid: has_content = "content" in chunkjson['choices'][0]["delta"] + if has_choices and choice_valid: has_role = "role" in chunkjson['choices'][0]["delta"] + except: + pass + return chunk_decoded, chunkjson, has_choices, choice_valid, has_content, has_role + +from functools import lru_cache +@lru_cache(maxsize=32) +def verify_endpoint(endpoint): + """ + 检查endpoint是否可用 + """ + return endpoint + +def predict_no_ui_long_connection(inputs, llm_kwargs, history=[], sys_prompt="", observe_window=None, console_slience=False): + raise NotImplementedError + + +def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_prompt='', stream = True, additional_fn=None): + + have_recent_file, image_paths = have_any_recent_upload_image_files(chatbot) + + if is_any_api_key(inputs): + chatbot._cookies['api_key'] = inputs + chatbot.append(("输入已识别为openai的api_key", what_keys(inputs))) + yield from update_ui(chatbot=chatbot, history=history, msg="api_key已导入") # 刷新界面 + return + elif not is_any_api_key(chatbot._cookies['api_key']): + chatbot.append((inputs, "缺少api_key。\n\n1. 临时解决方案:直接在输入区键入api_key,然后回车提交。\n\n2. 长效解决方案:在config.py中配置。")) + yield from update_ui(chatbot=chatbot, history=history, msg="缺少api_key") # 刷新界面 + return + if not have_recent_file: + chatbot.append((inputs, "没有检测到任何近期上传的图像文件,请上传jpg格式的图片,此外,请注意拓展名需要小写")) + yield from update_ui(chatbot=chatbot, history=history, msg="等待图片") # 刷新界面 + return + if os.path.exists(inputs): + chatbot.append((inputs, "已经接收到您上传的文件,您不需要再重复强调该文件的路径了,请直接输入您的问题。")) + yield from update_ui(chatbot=chatbot, history=history, msg="等待指令") # 刷新界面 + return + + + user_input = inputs + if additional_fn is not None: + from core_functional import handle_core_functionality + inputs, history = handle_core_functionality(additional_fn, inputs, history, chatbot) + + raw_input = inputs + logging.info(f'[raw_input] {raw_input}') + def make_media_input(inputs, image_paths): + for image_path in image_paths: + inputs = inputs + f'

' + return inputs + chatbot.append((make_media_input(inputs, image_paths), "")) + yield from update_ui(chatbot=chatbot, history=history, msg="等待响应") # 刷新界面 + + # check mis-behavior + if is_the_upload_folder(user_input): + chatbot[-1] = (inputs, f"[Local Message] 检测到操作错误!当您上传文档之后,需点击“**函数插件区**”按钮进行处理,请勿点击“提交”按钮或者“基础功能区”按钮。") + yield from update_ui(chatbot=chatbot, history=history, msg="正常") # 刷新界面 + time.sleep(2) + + try: + headers, payload, api_key = generate_payload(inputs, llm_kwargs, history, system_prompt, image_paths) + except RuntimeError as e: + chatbot[-1] = (inputs, f"您提供的api-key不满足要求,不包含任何可用于{llm_kwargs['llm_model']}的api-key。您可能选择了错误的模型或请求源。") + yield from update_ui(chatbot=chatbot, history=history, msg="api-key不满足要求") # 刷新界面 + return + + # 检查endpoint是否合法 + try: + from .bridge_all import model_info + endpoint = verify_endpoint(model_info[llm_kwargs['llm_model']]['endpoint']) + except: + tb_str = '```\n' + trimmed_format_exc() + '```' + chatbot[-1] = (inputs, tb_str) + yield from update_ui(chatbot=chatbot, history=history, msg="Endpoint不满足要求") # 刷新界面 + return + + history.append(make_media_input(inputs, image_paths)) + history.append("") + + retry = 0 + while True: + try: + # make a POST request to the API endpoint, stream=True + response = requests.post(endpoint, headers=headers, proxies=proxies, + json=payload, stream=True, timeout=TIMEOUT_SECONDS);break + except: + retry += 1 + chatbot[-1] = ((chatbot[-1][0], timeout_bot_msg)) + retry_msg = f",正在重试 ({retry}/{MAX_RETRY}) ……" if MAX_RETRY > 0 else "" + yield from update_ui(chatbot=chatbot, history=history, msg="请求超时"+retry_msg) # 刷新界面 + if retry > MAX_RETRY: raise TimeoutError + + gpt_replying_buffer = "" + + is_head_of_the_stream = True + if stream: + stream_response = response.iter_lines() + while True: + try: + chunk = next(stream_response) + except StopIteration: + # 非OpenAI官方接口的出现这样的报错,OpenAI和API2D不会走这里 + chunk_decoded = chunk.decode() + error_msg = chunk_decoded + # 首先排除一个one-api没有done数据包的第三方Bug情形 + if len(gpt_replying_buffer.strip()) > 0 and len(error_msg) == 0: + yield from update_ui(chatbot=chatbot, history=history, msg="检测到有缺陷的非OpenAI官方接口,建议选择更稳定的接口。") + break + # 其他情况,直接返回报错 + chatbot, history = handle_error(inputs, llm_kwargs, chatbot, history, chunk_decoded, error_msg, api_key) + yield from update_ui(chatbot=chatbot, history=history, msg="非OpenAI官方接口返回了错误:" + chunk.decode()) # 刷新界面 + return + + # 提前读取一些信息 (用于判断异常) + chunk_decoded, chunkjson, has_choices, choice_valid, has_content, has_role = decode_chunk(chunk) + + if is_head_of_the_stream and (r'"object":"error"' not in chunk_decoded) and (r"content" not in chunk_decoded): + # 数据流的第一帧不携带content + is_head_of_the_stream = False; continue + + if chunk: + try: + if has_choices and not choice_valid: + # 一些垃圾第三方接口的出现这样的错误 + continue + # 前者是API2D的结束条件,后者是OPENAI的结束条件 + if ('data: [DONE]' in chunk_decoded) or (len(chunkjson['choices'][0]["delta"]) == 0): + # 判定为数据流的结束,gpt_replying_buffer也写完了 + lastmsg = chatbot[-1][-1] + f"

{llm_kwargs['llm_model']}调用结束,该模型不具备上下文对话能力,如需追问,请及时切换模型。" + yield from update_ui_lastest_msg(lastmsg, chatbot, history, delay=1) + logging.info(f'[response] {gpt_replying_buffer}') + break + # 处理数据流的主体 + status_text = f"finish_reason: {chunkjson['choices'][0].get('finish_reason', 'null')}" + # 如果这里抛出异常,一般是文本过长,详情见get_full_error的输出 + if has_content: + # 正常情况 + gpt_replying_buffer = gpt_replying_buffer + chunkjson['choices'][0]["delta"]["content"] + elif has_role: + # 一些第三方接口的出现这样的错误,兼容一下吧 + continue + else: + # 一些垃圾第三方接口的出现这样的错误 + gpt_replying_buffer = gpt_replying_buffer + chunkjson['choices'][0]["delta"]["content"] + + history[-1] = gpt_replying_buffer + chatbot[-1] = (history[-2], history[-1]) + yield from update_ui(chatbot=chatbot, history=history, msg=status_text) # 刷新界面 + except Exception as e: + yield from update_ui(chatbot=chatbot, history=history, msg="Json解析不合常规") # 刷新界面 + chunk = get_full_error(chunk, stream_response) + chunk_decoded = chunk.decode() + error_msg = chunk_decoded + chatbot, history = handle_error(inputs, llm_kwargs, chatbot, history, chunk_decoded, error_msg, api_key) + yield from update_ui(chatbot=chatbot, history=history, msg="Json异常" + error_msg) # 刷新界面 + print(error_msg) + return + +def handle_error(inputs, llm_kwargs, chatbot, history, chunk_decoded, error_msg, api_key=""): + from .bridge_all import model_info + openai_website = ' 请登录OpenAI查看详情 https://platform.openai.com/signup' + if "reduce the length" in error_msg: + if len(history) >= 2: history[-1] = ""; history[-2] = "" # 清除当前溢出的输入:history[-2] 是本次输入, history[-1] 是本次输出 + history = clip_history(inputs=inputs, history=history, tokenizer=model_info[llm_kwargs['llm_model']]['tokenizer'], + max_token_limit=(model_info[llm_kwargs['llm_model']]['max_token'])) # history至少释放二分之一 + chatbot[-1] = (chatbot[-1][0], "[Local Message] Reduce the length. 本次输入过长, 或历史数据过长. 历史缓存数据已部分释放, 您可以请再次尝试. (若再次失败则更可能是因为输入过长.)") + elif "does not exist" in error_msg: + chatbot[-1] = (chatbot[-1][0], f"[Local Message] Model {llm_kwargs['llm_model']} does not exist. 模型不存在, 或者您没有获得体验资格.") + elif "Incorrect API key" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] Incorrect API key. OpenAI以提供了不正确的API_KEY为由, 拒绝服务. " + openai_website); report_invalid_key(api_key) + elif "exceeded your current quota" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] You exceeded your current quota. OpenAI以账户额度不足为由, 拒绝服务." + openai_website); report_invalid_key(api_key) + elif "account is not active" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] Your account is not active. OpenAI以账户失效为由, 拒绝服务." + openai_website); report_invalid_key(api_key) + elif "associated with a deactivated account" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] You are associated with a deactivated account. OpenAI以账户失效为由, 拒绝服务." + openai_website); report_invalid_key(api_key) + elif "API key has been deactivated" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] API key has been deactivated. OpenAI以账户失效为由, 拒绝服务." + openai_website); report_invalid_key(api_key) + elif "bad forward key" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] Bad forward key. API2D账户额度不足.") + elif "Not enough point" in error_msg: + chatbot[-1] = (chatbot[-1][0], "[Local Message] Not enough point. API2D账户点数不足.") + else: + from toolbox import regular_txt_to_markdown + tb_str = '```\n' + trimmed_format_exc() + '```' + chatbot[-1] = (chatbot[-1][0], f"[Local Message] 异常 \n\n{tb_str} \n\n{regular_txt_to_markdown(chunk_decoded)}") + return chatbot, history + +# Function to encode the image +def encode_image(image_path): + with open(image_path, "rb") as image_file: + return base64.b64encode(image_file.read()).decode('utf-8') + +def generate_payload(inputs, llm_kwargs, history, system_prompt, image_paths): + """ + 整合所有信息,选择LLM模型,生成http请求,为发送请求做准备 + """ + if not is_any_api_key(llm_kwargs['api_key']): + raise AssertionError("你提供了错误的API_KEY。\n\n1. 临时解决方案:直接在输入区键入api_key,然后回车提交。\n\n2. 长效解决方案:在config.py中配置。") + + api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model']) + + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {api_key}" + } + if API_ORG.startswith('org-'): headers.update({"OpenAI-Organization": API_ORG}) + if llm_kwargs['llm_model'].startswith('azure-'): + headers.update({"api-key": api_key}) + if llm_kwargs['llm_model'] in AZURE_CFG_ARRAY.keys(): + azure_api_key_unshared = AZURE_CFG_ARRAY[llm_kwargs['llm_model']]["AZURE_API_KEY"] + headers.update({"api-key": azure_api_key_unshared}) + + base64_images = [] + for image_path in image_paths: + base64_images.append(encode_image(image_path)) + + messages = [] + what_i_ask_now = {} + what_i_ask_now["role"] = "user" + what_i_ask_now["content"] = [] + what_i_ask_now["content"].append({ + "type": "text", + "text": inputs + }) + + for image_path, base64_image in zip(image_paths, base64_images): + what_i_ask_now["content"].append({ + "type": "image_url", + "image_url": { + "url": f"data:image/jpeg;base64,{base64_image}" + } + }) + + messages.append(what_i_ask_now) + model = llm_kwargs['llm_model'] + if llm_kwargs['llm_model'].startswith('api2d-'): + model = llm_kwargs['llm_model'][len('api2d-'):] + + payload = { + "model": model, + "messages": messages, + "temperature": llm_kwargs['temperature'], # 1.0, + "top_p": llm_kwargs['top_p'], # 1.0, + "n": 1, + "stream": True, + "max_tokens": get_max_token(llm_kwargs), + "presence_penalty": 0, + "frequency_penalty": 0, + } + try: + print(f" {llm_kwargs['llm_model']} : {inputs[:100]} ..........") + except: + print('输入中可能存在乱码。') + return headers, payload, api_key + + diff --git a/toolbox.py b/toolbox.py index 30f71762..3f3c68bd 100644 --- a/toolbox.py +++ b/toolbox.py @@ -279,9 +279,12 @@ def text_divide_paragraph(text): if '```' in text: # careful input - return pre + text + suf + return text + elif '' in text: + # careful input + return text else: - # wtf input + # whatever input lines = text.split("\n") for i, line in enumerate(lines): lines[i] = lines[i].replace(" ", " ") From 682898a3bac517f5c630713607db958b885b6a6c Mon Sep 17 00:00:00 2001 From: binary-husky Date: Mon, 13 Nov 2023 13:21:33 +0800 Subject: [PATCH 02/13] =?UTF-8?q?=E6=94=AF=E6=8C=81gpt-4-v=E5=A4=84?= =?UTF-8?q?=E7=90=86=E5=A4=9A=E5=BC=A0=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- request_llms/bridge_chatgpt_vision.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/request_llms/bridge_chatgpt_vision.py b/request_llms/bridge_chatgpt_vision.py index 112391c7..e84bc0b7 100644 --- a/request_llms/bridge_chatgpt_vision.py +++ b/request_llms/bridge_chatgpt_vision.py @@ -198,7 +198,7 @@ def predict(inputs, llm_kwargs, plugin_kwargs, chatbot, history=[], system_promp # 前者是API2D的结束条件,后者是OPENAI的结束条件 if ('data: [DONE]' in chunk_decoded) or (len(chunkjson['choices'][0]["delta"]) == 0): # 判定为数据流的结束,gpt_replying_buffer也写完了 - lastmsg = chatbot[-1][-1] + f"

{llm_kwargs['llm_model']}调用结束,该模型不具备上下文对话能力,如需追问,请及时切换模型。" + lastmsg = chatbot[-1][-1] + f"\n\n\n\n「{llm_kwargs['llm_model']}调用结束,该模型不具备上下文对话能力,如需追问,请及时切换模型。」" yield from update_ui_lastest_msg(lastmsg, chatbot, history, delay=1) logging.info(f'[response] {gpt_replying_buffer}') break From 2003afe27f26f7bb7add0162a4742a838a15f1cf Mon Sep 17 00:00:00 2001 From: binary-husky Date: Tue, 14 Nov 2023 11:54:07 +0800 Subject: [PATCH 03/13] =?UTF-8?q?API=5FURL=5FREDIRECT=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- toolbox.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/toolbox.py b/toolbox.py index 3f3c68bd..b7b762d7 100644 --- a/toolbox.py +++ b/toolbox.py @@ -808,6 +808,11 @@ def read_single_conf_with_lru_cache(arg): r = getattr(importlib.import_module('config'), arg) # 在读取API_KEY时,检查一下是不是忘了改config + if arg == 'API_URL_REDIRECT': + oai_rd = r.get("https://api.openai.com/v1/chat/completions", None) # API_URL_REDIRECT填写格式是错误的,请阅读`https://github.com/binary-husky/gpt_academic/wiki/项目配置说明` + if oai_rd and not oai_rd.endswith('/completions'): + print亮红( "\n\n[API_URL_REDIRECT] API_URL_REDIRECT填错了。请阅读`https://github.com/binary-husky/gpt_academic/wiki/项目配置说明`。如果您确信自己没填错,无视此消息即可。") + time.sleep(5) if arg == 'API_KEY': print亮蓝(f"[API_KEY] 本项目现已支持OpenAI和Azure的api-key。也支持同时填写多个api-key,如API_KEY=\"openai-key1,openai-key2,azure-key3\"") print亮蓝(f"[API_KEY] 您既可以在config.py中修改api-key(s),也可以在问题输入区输入临时的api-key(s),然后回车键提交后即可生效。") From b0c34a89cd3b0feabd974a5d3c36cf8632258210 Mon Sep 17 00:00:00 2001 From: Doiiars Date: Tue, 14 Nov 2023 12:22:52 +0800 Subject: [PATCH 04/13] Update main.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加临时更换API的帮助 --- main.py | 1 + 1 file changed, 1 insertion(+) diff --git a/main.py b/main.py index 42895599..ba18f85a 100644 --- a/main.py +++ b/main.py @@ -31,6 +31,7 @@ def main(): description += "

虚空终端使用说明: 点击虚空终端, 然后根据提示输入指令, 再次点击虚空终端" description += "

如何保存对话: 点击保存当前的对话按钮" description += "

如何语音对话: 请阅读Wiki" + description += "

如何临时更换API_KEY: 需要时,在输入区输入临时的API_KEY然后回车键提交后即可生效" # 问询记录, python 版本建议3.9+(越新越好) import logging, uuid From 1fa296a3033026fc0616ec98af901ba111ab3249 Mon Sep 17 00:00:00 2001 From: binary-husky <96192199+binary-husky@users.noreply.github.com> Date: Tue, 14 Nov 2023 12:28:57 +0800 Subject: [PATCH 05/13] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=B8=AE=E5=8A=A9?= =?UTF-8?q?=E6=96=87=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index ba18f85a..b29c94fc 100644 --- a/main.py +++ b/main.py @@ -31,7 +31,7 @@ def main(): description += "

虚空终端使用说明: 点击虚空终端, 然后根据提示输入指令, 再次点击虚空终端" description += "

如何保存对话: 点击保存当前的对话按钮" description += "

如何语音对话: 请阅读Wiki" - description += "

如何临时更换API_KEY: 需要时,在输入区输入临时的API_KEY然后回车键提交后即可生效" + description += "

如何临时更换API_KEY: 在输入区输入临时API_KEY后提交(网页刷新后失效)" # 问询记录, python 版本建议3.9+(越新越好) import logging, uuid From 443915b6d6178c4f32cb11322e0d50c5c59d5952 Mon Sep 17 00:00:00 2001 From: Skyzayre <120616113+Skyzayre@users.noreply.github.com> Date: Tue, 14 Nov 2023 20:49:53 +0800 Subject: [PATCH 06/13] =?UTF-8?q?Update=20=E5=9B=BE=E7=89=87=E7=94=9F?= =?UTF-8?q?=E6=88=90.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crazy_functions/图片生成.py | 62 +++++++++++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 2 deletions(-) diff --git a/crazy_functions/图片生成.py b/crazy_functions/图片生成.py index 4968361a..8a304b4e 100644 --- a/crazy_functions/图片生成.py +++ b/crazy_functions/图片生成.py @@ -42,6 +42,47 @@ def gen_image(llm_kwargs, prompt, resolution="1024x1024", model="dall-e-2"): return image_url, file_path+file_name +def gen_image_dalle3(quality, llm_kwargs, prompt, resolution="1024x1024", model="dall-e-3"): + import requests, json, time, os + from request_llms.bridge_all import model_info + + proxies = get_conf('proxies') + # Set up OpenAI API key and model + api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model']) + chat_endpoint = model_info[llm_kwargs['llm_model']]['endpoint'] + # 'https://api.openai.com/v1/chat/completions' + img_endpoint = chat_endpoint.replace('chat/completions','images/generations') + # # Generate the image + url = img_endpoint + headers = { + 'Authorization': f"Bearer {api_key}", + 'Content-Type': 'application/json' + } + data = { + 'prompt': prompt, + 'n': 1, + 'size': resolution, + 'quality': quality, + 'model': model, + 'response_format': 'url' + } + response = requests.post(url, headers=headers, json=data, proxies=proxies) + print(response.content) + try: + image_url = json.loads(response.content.decode('utf8'))['data'][0]['url'] + except: + raise RuntimeError(response.content.decode()) + # 文件保存到本地 + r = requests.get(image_url, proxies=proxies) + file_path = f'{get_log_folder()}/image_gen/' + os.makedirs(file_path, exist_ok=True) + file_name = 'Image' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.png' + with open(file_path+file_name, 'wb+') as f: f.write(r.content) + + + return image_url, file_path+file_name + + def edit_image(llm_kwargs, prompt, image_path, resolution="1024x1024", model="dall-e-2"): import requests, json, time, os from request_llms.bridge_all import model_info @@ -109,13 +150,30 @@ def 图片生成_DALLE2(prompt, llm_kwargs, plugin_kwargs, chatbot, history, sys @CatchException -def 图片生成_DALLE3(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): +def 图片生成_DALLE3_Standard(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): history = [] # 清空历史,以免输入溢出 chatbot.append(("这是什么功能?", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文效果不理想, 请尝试英文Prompt。正在处理中 .....")) yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") resolution = plugin_kwargs.get("advanced_arg", '1024x1024') - image_url, image_path = gen_image(llm_kwargs, prompt, resolution) + image_url, image_path = gen_image_dalle3(standard, llm_kwargs, prompt, resolution) + chatbot.append([prompt, + f'图像中转网址:
`{image_url}`
'+ + f'中转网址预览:
' + f'本地文件地址:
`{image_path}`
'+ + f'本地文件预览:
' + ]) + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 + + +@CatchException +def 图片生成_DALLE3_HD(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): + history = [] # 清空历史,以免输入溢出 + chatbot.append(("这是什么功能?", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文效果不理想, 请尝试英文Prompt。正在处理中 .....")) + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 + if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") + resolution = plugin_kwargs.get("advanced_arg", '1024x1024') + image_url, image_path = gen_image_dalle3(HD, llm_kwargs, prompt, resolution) chatbot.append([prompt, f'图像中转网址:
`{image_url}`
'+ f'中转网址预览:
' From 518a1b2b75e21f790135bbe0ada5370e4bc748f0 Mon Sep 17 00:00:00 2001 From: Skyzayre <120616113+Skyzayre@users.noreply.github.com> Date: Tue, 14 Nov 2023 20:51:49 +0800 Subject: [PATCH 07/13] Update crazy_functional.py --- crazy_functional.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crazy_functional.py b/crazy_functional.py index 42b0151a..bb7aba90 100644 --- a/crazy_functional.py +++ b/crazy_functional.py @@ -354,7 +354,7 @@ def get_crazy_functions(): print('Load function plugin failed') try: - from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3 + from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3_Standard, 图片生成_DALLE3_HD function_plugins.update({ "图片生成_DALLE2 (先切换模型到openai或api2d)": { "Group": "对话", @@ -367,13 +367,24 @@ def get_crazy_functions(): }, }) function_plugins.update({ - "图片生成_DALLE3 (先切换模型到openai或api2d)": { + "图片生成_DALLE3_Standard (先切换模型到openai或api2d)": { "Group": "对话", "Color": "stop", "AsButton": False, "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792", # 高级参数输入区的显示提示 - "Info": "使用DALLE3生成图片 | 输入参数字符串,提供图像的内容", + "Info": "使用DALLE3 standard质量生成图片 | 输入参数字符串,提供图像的内容", + "Function": HotReload(图片生成_DALLE3) + }, + }) + function_plugins.update({ + "图片生成_DALLE3_HD (先切换模型到openai或api2d)": { + "Group": "对话", + "Color": "stop", + "AsButton": False, + "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) + "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792", # 高级参数输入区的显示提示 + "Info": "使用DALLE3 HD质量生成图片 | 输入参数字符串,提供图像的内容", "Function": HotReload(图片生成_DALLE3) }, }) From 1b28ae3baa21eb56b8a37617595aaf59142213b3 Mon Sep 17 00:00:00 2001 From: Skyzayre <120616113+Skyzayre@users.noreply.github.com> Date: Tue, 14 Nov 2023 21:14:41 +0800 Subject: [PATCH 08/13] Update crazy_functional.py --- crazy_functional.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crazy_functional.py b/crazy_functional.py index bb7aba90..7f3af849 100644 --- a/crazy_functional.py +++ b/crazy_functional.py @@ -354,7 +354,7 @@ def get_crazy_functions(): print('Load function plugin failed') try: - from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3_Standard, 图片生成_DALLE3_HD + from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3_Standard, 图片生成_DALLE3_HD function_plugins.update({ "图片生成_DALLE2 (先切换模型到openai或api2d)": { "Group": "对话", From 5391cb4198cd9a291f4d2991921e48711d8d3a87 Mon Sep 17 00:00:00 2001 From: Skyzayre <120616113+Skyzayre@users.noreply.github.com> Date: Tue, 14 Nov 2023 21:17:48 +0800 Subject: [PATCH 09/13] Update crazy_functional.py --- crazy_functional.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crazy_functional.py b/crazy_functional.py index 7f3af849..bdf49b7f 100644 --- a/crazy_functional.py +++ b/crazy_functional.py @@ -374,7 +374,7 @@ def get_crazy_functions(): "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792", # 高级参数输入区的显示提示 "Info": "使用DALLE3 standard质量生成图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片生成_DALLE3) + "Function": HotReload(图片生成_DALLE3_Standard) }, }) function_plugins.update({ @@ -385,7 +385,7 @@ def get_crazy_functions(): "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792", # 高级参数输入区的显示提示 "Info": "使用DALLE3 HD质量生成图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片生成_DALLE3) + "Function": HotReload(图片生成_DALLE3_HD) }, }) except: From 4d1657a53197b87827a46cf9cc57dab4d6a65086 Mon Sep 17 00:00:00 2001 From: Skyzayre <120616113+Skyzayre@users.noreply.github.com> Date: Tue, 14 Nov 2023 21:25:47 +0800 Subject: [PATCH 10/13] =?UTF-8?q?Update=20=E5=9B=BE=E7=89=87=E7=94=9F?= =?UTF-8?q?=E6=88=90.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crazy_functions/图片生成.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crazy_functions/图片生成.py b/crazy_functions/图片生成.py index 8a304b4e..e871051a 100644 --- a/crazy_functions/图片生成.py +++ b/crazy_functions/图片生成.py @@ -156,7 +156,7 @@ def 图片生成_DALLE3_Standard(prompt, llm_kwargs, plugin_kwargs, chatbot, his yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") resolution = plugin_kwargs.get("advanced_arg", '1024x1024') - image_url, image_path = gen_image_dalle3(standard, llm_kwargs, prompt, resolution) + image_url, image_path = gen_image_dalle3("standard", llm_kwargs, prompt, resolution) chatbot.append([prompt, f'图像中转网址:
`{image_url}`
'+ f'中转网址预览:
' @@ -173,7 +173,7 @@ def 图片生成_DALLE3_HD(prompt, llm_kwargs, plugin_kwargs, chatbot, history, yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") resolution = plugin_kwargs.get("advanced_arg", '1024x1024') - image_url, image_path = gen_image_dalle3(HD, llm_kwargs, prompt, resolution) + image_url, image_path = gen_image_dalle3("HD", llm_kwargs, prompt, resolution) chatbot.append([prompt, f'图像中转网址:
`{image_url}`
'+ f'中转网址预览:
' From f495bb154ecbabdfc08ea051ea699c576cc4cea6 Mon Sep 17 00:00:00 2001 From: Skyzayre <120616113+Skyzayre@users.noreply.github.com> Date: Tue, 14 Nov 2023 21:33:00 +0800 Subject: [PATCH 11/13] =?UTF-8?q?Update=20=E5=9B=BE=E7=89=87=E7=94=9F?= =?UTF-8?q?=E6=88=90.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crazy_functions/图片生成.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crazy_functions/图片生成.py b/crazy_functions/图片生成.py index e871051a..5c1f1b9a 100644 --- a/crazy_functions/图片生成.py +++ b/crazy_functions/图片生成.py @@ -173,7 +173,7 @@ def 图片生成_DALLE3_HD(prompt, llm_kwargs, plugin_kwargs, chatbot, history, yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") resolution = plugin_kwargs.get("advanced_arg", '1024x1024') - image_url, image_path = gen_image_dalle3("HD", llm_kwargs, prompt, resolution) + image_url, image_path = gen_image_dalle3("hd", llm_kwargs, prompt, resolution) chatbot.append([prompt, f'图像中转网址:
`{image_url}`
'+ f'中转网址预览:
' From 5caeb7525d11c6f10ac1950e215cf5d2ae46a582 Mon Sep 17 00:00:00 2001 From: binary-husky <96192199+binary-husky@users.noreply.github.com> Date: Tue, 14 Nov 2023 23:15:19 +0800 Subject: [PATCH 12/13] =?UTF-8?q?Update=20=E5=9B=BE=E7=89=87=E7=94=9F?= =?UTF-8?q?=E6=88=90.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- crazy_functions/图片生成.py | 109 ++++++++++-------------------------- 1 file changed, 29 insertions(+), 80 deletions(-) diff --git a/crazy_functions/图片生成.py b/crazy_functions/图片生成.py index 5c1f1b9a..642a9e22 100644 --- a/crazy_functions/图片生成.py +++ b/crazy_functions/图片生成.py @@ -2,7 +2,7 @@ from toolbox import CatchException, update_ui, get_conf, select_api_key, get_log from crazy_functions.multi_stage.multi_stage_utils import GptAcademicState -def gen_image(llm_kwargs, prompt, resolution="1024x1024", model="dall-e-2"): +def gen_image(llm_kwargs, prompt, resolution="1024x1024", model="dall-e-2", quality=None): import requests, json, time, os from request_llms.bridge_all import model_info @@ -25,47 +25,7 @@ def gen_image(llm_kwargs, prompt, resolution="1024x1024", model="dall-e-2"): 'model': model, 'response_format': 'url' } - response = requests.post(url, headers=headers, json=data, proxies=proxies) - print(response.content) - try: - image_url = json.loads(response.content.decode('utf8'))['data'][0]['url'] - except: - raise RuntimeError(response.content.decode()) - # 文件保存到本地 - r = requests.get(image_url, proxies=proxies) - file_path = f'{get_log_folder()}/image_gen/' - os.makedirs(file_path, exist_ok=True) - file_name = 'Image' + time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + '.png' - with open(file_path+file_name, 'wb+') as f: f.write(r.content) - - - return image_url, file_path+file_name - - -def gen_image_dalle3(quality, llm_kwargs, prompt, resolution="1024x1024", model="dall-e-3"): - import requests, json, time, os - from request_llms.bridge_all import model_info - - proxies = get_conf('proxies') - # Set up OpenAI API key and model - api_key = select_api_key(llm_kwargs['api_key'], llm_kwargs['llm_model']) - chat_endpoint = model_info[llm_kwargs['llm_model']]['endpoint'] - # 'https://api.openai.com/v1/chat/completions' - img_endpoint = chat_endpoint.replace('chat/completions','images/generations') - # # Generate the image - url = img_endpoint - headers = { - 'Authorization': f"Bearer {api_key}", - 'Content-Type': 'application/json' - } - data = { - 'prompt': prompt, - 'n': 1, - 'size': resolution, - 'quality': quality, - 'model': model, - 'response_format': 'url' - } + if quality is not None: data.update({'quality': quality}) response = requests.post(url, headers=headers, json=data, proxies=proxies) print(response.content) try: @@ -126,17 +86,17 @@ def edit_image(llm_kwargs, prompt, image_path, resolution="1024x1024", model="da @CatchException def 图片生成_DALLE2(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): """ - txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径 - llm_kwargs gpt模型参数,如温度和top_p等,一般原样传递下去就行 - plugin_kwargs 插件模型的参数,暂时没有用武之地 - chatbot 聊天显示框的句柄,用于显示给用户 - history 聊天历史,前情提要 + txt 输入栏用户输入的文本,例如需要翻译的一段话,再例如一个包含了待处理文件的路径 + llm_kwargs gpt模型参数,如温度和top_p等,一般原样传递下去就行 + plugin_kwargs 插件模型的参数,暂时没有用武之地 + chatbot 聊天显示框的句柄,用于显示给用户 + history 聊天历史,前情提要 system_prompt 给gpt的静默提醒 web_port 当前软件运行的端口号 """ - history = [] # 清空历史,以免输入溢出 - chatbot.append(("这是什么功能?", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文效果不理想, 请尝试英文Prompt。正在处理中 .....")) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 + history = [] # 清空历史,以免输入溢出 + chatbot.append(("您正在调用“图像生成”插件。", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文Prompt效果不理想, 请尝试英文Prompt。正在处理中 .....")) + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 由于请求gpt需要一段时间,我们先及时地做一次界面更新 if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") resolution = plugin_kwargs.get("advanced_arg", '1024x1024') image_url, image_path = gen_image(llm_kwargs, prompt, resolution) @@ -146,44 +106,32 @@ def 图片生成_DALLE2(prompt, llm_kwargs, plugin_kwargs, chatbot, history, sys f'本地文件地址:
`{image_path}`
'+ f'本地文件预览:
' ]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 界面更新 @CatchException -def 图片生成_DALLE3_Standard(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - history = [] # 清空历史,以免输入溢出 - chatbot.append(("这是什么功能?", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文效果不理想, 请尝试英文Prompt。正在处理中 .....")) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 +def 图片生成_DALLE3(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): + history = [] # 清空历史,以免输入溢出 + chatbot.append(("您正在调用“图像生成”插件。", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文Prompt效果不理想, 请尝试英文Prompt。正在处理中 .....")) + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 由于请求gpt需要一段时间,我们先及时地做一次界面更新 if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") - resolution = plugin_kwargs.get("advanced_arg", '1024x1024') - image_url, image_path = gen_image_dalle3("standard", llm_kwargs, prompt, resolution) + resolution = plugin_kwargs.get("advanced_arg", '1024x1024').lower() + if resolution.endswith('-hd'): + resolution = resolution.replace('-hd', '') + quality = 'hd' + else: + quality = 'standard' + image_url, image_path = gen_image(llm_kwargs, prompt, resolution, model="dall-e-3", quality=quality) chatbot.append([prompt, f'图像中转网址:
`{image_url}`
'+ f'中转网址预览:
' f'本地文件地址:
`{image_path}`
'+ f'本地文件预览:
' ]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 - - -@CatchException -def 图片生成_DALLE3_HD(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): - history = [] # 清空历史,以免输入溢出 - chatbot.append(("这是什么功能?", "[Local Message] 生成图像, 请先把模型切换至gpt-*或者api2d-*。如果中文效果不理想, 请尝试英文Prompt。正在处理中 .....")) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 由于请求gpt需要一段时间,我们先及时地做一次界面更新 - if ("advanced_arg" in plugin_kwargs) and (plugin_kwargs["advanced_arg"] == ""): plugin_kwargs.pop("advanced_arg") - resolution = plugin_kwargs.get("advanced_arg", '1024x1024') - image_url, image_path = gen_image_dalle3("hd", llm_kwargs, prompt, resolution) - chatbot.append([prompt, - f'图像中转网址:
`{image_url}`
'+ - f'中转网址预览:
' - f'本地文件地址:
`{image_path}`
'+ - f'本地文件预览:
' - ]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 - + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 界面更新 class ImageEditState(GptAcademicState): + # 尚未完成 def get_image_file(self, x): import os, glob if len(x) == 0: return False, None @@ -204,8 +152,8 @@ class ImageEditState(GptAcademicState): def reset(self): self.req = [ {'value':None, 'description': '请先上传图像(必须是.png格式), 然后再次点击本插件', 'verify_fn': self.get_image_file}, - {'value':None, 'description': '请输入分辨率,可选:256x256, 512x512 或 1024x1024', 'verify_fn': self.get_resolution}, - {'value':None, 'description': '请输入修改需求,建议您使用英文提示词', 'verify_fn': self.get_prompt}, + {'value':None, 'description': '请输入分辨率,可选:256x256, 512x512 或 1024x1024', 'verify_fn': self.get_resolution}, + {'value':None, 'description': '请输入修改需求,建议您使用英文提示词', 'verify_fn': self.get_prompt}, ] self.info = "" @@ -230,11 +178,12 @@ class ImageEditState(GptAcademicState): @CatchException def 图片修改_DALLE2(prompt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port): + # 尚未完成 history = [] # 清空历史 state = ImageEditState.get_state(chatbot, ImageEditState) state = state.feed(prompt, chatbot) if not state.already_obtained_all_materials(): - chatbot.append(["图片修改(先上传图片,再输入修改需求,最后输入分辨率)", state.next_req()]) + chatbot.append(["图片修改(先上传图片,再输入修改需求,最后输入分辨率)", state.next_req()]) yield from update_ui(chatbot=chatbot, history=history) return @@ -251,5 +200,5 @@ def 图片修改_DALLE2(prompt, llm_kwargs, plugin_kwargs, chatbot, history, sys f'本地文件地址:
`{image_path}`
'+ f'本地文件预览:
' ]) - yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 # 界面更新 + yield from update_ui(chatbot=chatbot, history=history) # 刷新界面 界面更新 From e7c662a5d66d58150b56fb36abc6a513e44cd27e Mon Sep 17 00:00:00 2001 From: binary-husky <96192199+binary-husky@users.noreply.github.com> Date: Tue, 14 Nov 2023 23:16:49 +0800 Subject: [PATCH 13/13] Update crazy_functional.py --- crazy_functional.py | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/crazy_functional.py b/crazy_functional.py index bdf49b7f..3d4df718 100644 --- a/crazy_functional.py +++ b/crazy_functional.py @@ -354,7 +354,7 @@ def get_crazy_functions(): print('Load function plugin failed') try: - from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3_Standard, 图片生成_DALLE3_HD + from crazy_functions.图片生成 import 图片生成_DALLE2, 图片生成_DALLE3 function_plugins.update({ "图片生成_DALLE2 (先切换模型到openai或api2d)": { "Group": "对话", @@ -367,25 +367,14 @@ def get_crazy_functions(): }, }) function_plugins.update({ - "图片生成_DALLE3_Standard (先切换模型到openai或api2d)": { + "图片生成_DALLE3 (先切换模型到openai或api2d)": { "Group": "对话", "Color": "stop", "AsButton": False, "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) - "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792", # 高级参数输入区的显示提示 - "Info": "使用DALLE3 standard质量生成图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片生成_DALLE3_Standard) - }, - }) - function_plugins.update({ - "图片生成_DALLE3_HD (先切换模型到openai或api2d)": { - "Group": "对话", - "Color": "stop", - "AsButton": False, - "AdvancedArgs": True, # 调用时,唤起高级参数输入区(默认False) - "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792", # 高级参数输入区的显示提示 - "Info": "使用DALLE3 HD质量生成图片 | 输入参数字符串,提供图像的内容", - "Function": HotReload(图片生成_DALLE3_HD) + "ArgsReminder": "在这里输入分辨率, 如1024x1024(默认),支持 1024x1024, 1792x1024, 1024x1792。如需生成高清图像,请输入 1024x1024-HD, 1792x1024-HD, 1024x1792-HD。", # 高级参数输入区的显示提示 + "Info": "使用DALLE3生成图片 | 输入参数字符串,提供图像的内容", + "Function": HotReload(图片生成_DALLE3) }, }) except: