dreampal / app.py
zhuguangbin86's picture
assembly all
4950385
import gradio as gr
from openai import OpenAI
import requests
import time
from PIL import Image
import os, io, json, random
import base64
import logging
# 配置日志记录器
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s:%(message)s",
handlers=[
# logging.FileHandler("debug.log"), # 将日志输出到文件
logging.StreamHandler(), # 同时在控制台输出
],
)
sd_api_base = os.environ["SD_API_BASE"]
sd_api_key = os.environ["SD_API_KEY"]
# Set your OpenAI API key here
api_key = os.environ.get("OPENAI_API_KEY")
api_base = os.environ.get("OPENAI_API_BASE")
client = OpenAI(api_key=api_key, base_url=api_base)
history = []
def predict(message, history, model, system_prompt):
history_openai_format = []
history_openai_format.append({"role": "system", "content": system_prompt})
for human, assistant in history:
history_openai_format.append({"role": "user", "content": human})
history_openai_format.append({"role": "assistant", "content": assistant})
history_openai_format.append({"role": "user", "content": message})
response = client.chat.completions.create(
model=model,
messages=history_openai_format,
response_format={"type": "json_object"},
stream=True,
)
partial_message = ""
for chunk in response:
if chunk.choices[0].delta.content and len(chunk.choices[0].delta.content) != 0:
partial_message = partial_message + chunk.choices[0].delta.content
yield partial_message
# 发送POST请求的函数
def send_post_request(input_json):
url = f"{sd_api_base}/txt2img/run/"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {sd_api_key}",
}
logging.info(f"Sending data to {url}: {json.dumps(input_json)}")
response = requests.post(url, headers=headers, json=input_json)
if response.status_code == 200:
logging.info(f"Received OK response: {json.dumps(response.json())}")
return response.json()
else:
logging.info(
f"Received ERROR response: {response.status_code}, ERROR: {response.text}"
)
raise Exception(f"Error in POST request: {response.text}")
# 轮询GET请求,直到异步操作完成
def poll_status(id):
url = f"{sd_api_base}/txt2img/status/{id}"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {sd_api_key}",
}
while True:
logging.info(f"Requesting to {url}")
response = requests.get(url, headers=headers)
if response.status_code == 200:
logging.info(f"Received OK response: {json.dumps(response.json())}")
result = response.json()
if result["status"] == "COMPLETED":
return result
elif result["status"] == "FAILED":
logging.info(
f"Received OK response, but job failed:{json.dumps(response.json())}"
)
raise Exception(f"Error in GET request: {json.dumps(response.json())}")
else:
time.sleep(1) # 等待1秒后再次尝试
else:
logging.info(
f"Received ERROR response: {response.status_code}, ERROR: {response.text}"
)
raise Exception(f"Error in GET request: {response.text}")
# 输出图片列表,输入参数,输图的信息,其中返回图片为Base64编码的图片数据,转换为可显示的图片
def display(output_json):
detail = (
output_json["output"]["detail"] if "detail" in output_json["output"] else ""
)
execution = f"id: {output_json['id']}, delayTime: {output_json['delayTime']}, executionTime: {output_json['delayTime']}, detail: {detail}"
images_data = output_json["output"]["images"]
parameters = output_json["output"]["parameters"]
info = output_json["output"]["info"]
images = []
for base64_data in images_data:
image_data = base64.b64decode(base64_data)
image = Image.open(io.BytesIO(image_data))
images.append(image)
return images, execution, parameters, info
# Gradio界面的函数
def txt2img(
prompt,
negative_prompt,
seed,
sampler_name,
batch_size,
n_iter,
steps,
cfg_scale,
width,
height,
alwayson_scripts,
):
error_message = "" # 新增一个变量来存储错误信息
try:
try:
# 尝试将输入的字符串转换为JSON对象
alwayson_scripts_json = json.loads(alwayson_scripts)
except json.JSONDecodeError as e:
logging.error(f"Not Valid JSON format: {e}, {alwayson_scripts}")
raise Exception(f"Not Valid JSON format: {e}")
input_json = {
"input": {
"prompt": prompt,
"negative_prompt": negative_prompt,
"seed": seed,
"sampler_name": sampler_name,
"batch_size": batch_size,
"n_iter": n_iter,
"steps": steps,
"cfg_scale": cfg_scale,
"width": width,
"height": height,
"alwayson_scripts": alwayson_scripts_json,
}
}
post_response = send_post_request(input_json)
status_response = poll_status(post_response["id"])
if "images" in status_response["output"]:
images, execution, parameters, info = display(status_response)
else:
error_message = (
status_response["output"]["detail"]
if "detail" in status_response["output"]
else ""
)
images, execution, parameters, info = [], "", {}, {} # 设置默认值以防异常发生
except Exception as e:
error_message = str(e) # 捕获异常并存储错误信息
logging.error(f"Exception occurred: {error_message}")
images, execution, parameters, info = [], "", {}, {} # 设置默认值以防异常发生
return images, execution, error_message, parameters, info
def sd_prompt_refine(sd_prompt_json: str, art_style: str):
sd_prompt_res = json.loads(sd_prompt_json)
emotion = sd_prompt_res["emotion"]
emotion_dominant = str(emotion["dominant"])
emotion_category = str(emotion["category"]).upper()
emotion_tags = str(emotion["tags"])
image = sd_prompt_res["image"]
action_subject = sd_prompt_res["action_subject"]
stable_diffusion_prompt = sd_prompt_res["prompt"]
emotion_to_directive = {
"anxiety": "<lora:anxiety_tones_v10:0.8>",
"hopeful": "<lora:hopeful_tonesXL_v20:0.9>",
"surprise": "<lora:Surprise_tonesXL_v20:0.5>",
"relieved": "<lora:relieved_tonesXL_v10:0.9>",
"explore": "<lora:explore_tonesXL_v10:1>",
"angry": "<lora:angry_tonesXL_v10:0.6>",
"sad": "<lora:sad_tonesXL_v10:0.55>",
"shame": "<lora:shame_tonesXL_v10:0.5>",
"fear": "<lora:fear_tonesXL_v20-000008:0.3>",
"warm": "<lora:warm_tonesXL_v10:0.6>",
}
art_style_mapping = {
"CARTOON": "Cartoon Illustration style,",
"FANTASY_ART": "ethereal fantasy concept art of,magnificent, celestial, ethereal, painterly, epic, majestic, magical, fantasy art, cover art, dreamy,",
"CUBIST_ARTWORK": "cubist artwork,geometric shapes, abstract, innovative, revolutionary,",
"VOXEL_ART": "Minecraft style,blocky, pixelated, vibrant colors, recognizable characters and objects, game assets,",
"3D_GAME": "Fortnite Art Style, 3D cartoon, colorful, Fortnite Art Style,",
}
art_style = random.choice(list(art_style_mapping.keys()))
art_style_prompt = art_style_mapping.get(art_style)
prompt_segments = stable_diffusion_prompt.split("BREAK")
lora_prompt = (
emotion_to_directive[emotion_dominant.lower()]
if emotion_dominant.lower() in emotion_to_directive
else ""
)
sd_prompt_final = f"{prompt_segments[0]}, {art_style_prompt}, {lora_prompt}, BREAK {prompt_segments[1]} BREAK {prompt_segments[2]}"
return sd_prompt_final
def update_prompt(value):
return value # 返回的值将会被设置为`prompt`文本框的值
model = ["gpt-3.5-turbo", "gpt-3.5-turbo-1106", "gpt-4", "gpt-4-1106-preview"]
dream_interpretation_prompt = """
You are now a dream interpretation expert. Please analyze the description of the dream that I input.
Title for the Dream:
Please adhere to the following principles when creating a title for the dream: If the dream description is less than 50 words, the title should be limited to a maximum of 5 words. If the dream description exceeds 50 words, the title length may range between 6-10 words.
Pay attention to the following points:
1. Core Content: For concise dreams, distill the most central or eye-catching imagery or events.
2. Feelings and Emotions: If the dream expresses strong emotions, consider naming it based on the predominant emotion.
3. Symbolic Meaning: For dreams with chaotic or fragmented content, if there are prominent symbolic elements, use these symbols to construct the title.
Please follow the steps below to interpret my dream:
1.Determine which theories to use for dream interpretation based on the following principles:
(1)Clarity of the dream:
- If the dream has rich details, clear emotions, and vivid memories, the methods of Jung or Freud might be more appropriate. If the dream contains clear personal history, emotional content, anxiety, conflicts, and involves sexual or invasive symbols, Freud's dream interpretation theory might be more applicable. If the dream involves universal symbols, mythological elements, or relates to personal growth and self-realization, considering social and cultural factors, Jung's collective unconscious theory might be closer.
- If the dream is vague, without many details or emotional expressions, then interpreting it according to the Dream Book of Zhou Gong might be more appropriate. Because the Dream Book of Zhou Gong is more about interpreting the general theme and symbolic meaning of dreams, not requiring many details.
(2)Emotional tone of the dream:
- Intense emotional tone - Freud: Freud's psychoanalytic theory focuses on subconscious conflicts that are repressed or unresolved. Strong emotional tones usually point to these subconscious issues.
- Moderate or vague emotional tone - Jung: Jung's theory not only looks at the individual's subconscious but also involves the collective unconscious and universal psychological symbols. Moderate or vague emotional tones might involve the individual's relationship with a broader psychological structure, making Jung's theory more applicable.
- Lack of clear emotional tone - Zhou Gong: If the dream is more objective and lacks strong emotional meaning, the Dream Book of Zhou Gong provides a relatively simple and traditional framework of symbolic interpretation.
(3)Content of the dream:
- Concrete: If the content of the dream is very concrete, such as specific people, places, or events, this type of dream is more suitable for interpretation according to the Dream Book of Zhou Gong. Because it usually gives clear, direct interpretations, focusing on specific elements (such as animals, objects, environments, etc.).
- Moderate abstraction: If the dream involves themes of moderate abstraction, such as family relationships, love, work, etc., this type of dream is more suitable for interpretation according to Freud. Freud's method emphasizes the connection between the subconscious and real life, especially in relation to sex, desire, and family relationships.
- High abstraction: If the dream is very abstract, containing symbols, elements, or feelings that are difficult to explain, this type of dream is more suitable for interpretation according to Jung. Jung's method focuses more on the connection between the individual and the collective subconscious, as well as deeper, universally present human themes.
2.Analysis of the dream:
(1)Analysis of key elements: Identify the key elements in the dream that are notable, recurring, or have a strong emotional tone, such as objects, characters, items, scenes, actions, etc.(focus only on the key elements that are of great value to dream interpretation, not on identifying all the key elements), and interpret these key elements in detail based on the content of the dream. Every key element is parsed into a paragraph (choose the most suitable theory for each element, avoiding the use of specific terminology of the theories)
(2)Summary: Following the above content, summarize the dream as a whole. It is not necessary to repeat the contents of the key element parsing above, but to give conclusive parsing.
Output format:
- Title for the Dream
- key elements: Please extract up to five key elements from the original dream description. These elements should be nouns or verb phrases that are significant for dream interpretation. Ensure that these elements are essential for analyzing the dream and are commonly encountered in the study of dream interpretation.
- The analysis of the dream: it should be presented in a part-whole structure, which includes the "analysis of key elements" and the "summary".
- Note:
1.The process of choosing the appropriate theoretical analysis does not need to be presented, nor is it necessary to inform the user of the final theory selected.
2.While ensuring that the language is easy to understand, avoid using specific terminology of the theories, without changing the depth and scientific nature of the interpretation.
3.Express in the first-person voice of a psychotherapist, keep your tone cordial.
4.Omit the subheadings "Analysis of Key Elements" and "Summary"
5.After each key element is parsed, wrap the line and start another paragraph
6.On the basis of not changing the depth and richness of the analysis, the number of paragraphs is controlled by not more than 5 paragraphs, and all the output content is not more than 230 words
Please output the result in json format. Here is an example:
{'title': 'xxxxx', 'tags': ['tag1', 'tag2'], 'interpretation': ['paragraph1', 'paragraph2']}
field "title" is the title for dream,
field "tags" are key elements,
field "interpretation" is the analysis of the dream.
"""
dream_sd_prompt_generation_prompt = """
I now need to guide you in generating prompts for Stable Diffusion. After some experiments and tests, we have found a set of methods that can guide the generation of correct prompts. I will now send you these prompts in a total of 5 steps. First, I will give you different dreamscapes. For each dreamscape, you need to use the following five-step guidance to output the correct result. Your output is divided into four parts: one is the core emotion of the dreamscape. The second is the core image. The third is the core action and subject (only need to output the person-shifted version). The fourth and most important is the prompt for Stable Diffusion. Our interaction should be as follows: I give a dreamscape description, and you output the corresponding four parts:
Please note that we do not want any content you generate to violate content safety. Any content you generate should not include the following topics: pornography, politics, religion, blood, drugs, geopolitics, insults, provocation, or conflict-inciting topics. If you believe a topic is not content-safe, please randomly generate a prompt for Stable Diffusion that depicts a beautiful natural landscape.
1. Now I will tell you some guidance on refining core emotions: I will give you a description of a dreamscape, please analyze the main emotional tendencies of this dreamscape, and tag the dreamscape with emotional labels according to the following tag system.
Positive emotions:
(1) surprise: includes surprise, achievement, pride, excitement, etc.
(2) warm: includes love, gratitude, forgiveness, intimacy, touching, etc.
(3) hopeful: includes optimism, positivity, longing, exhilaration, expectation, relieved, inspiration, etc.
(4) relieved: includes satisfaction, relaxation, peace, comfort, belonging, etc.
(5) explore: includes curiosity, interest, astonishment, mystery, inspiration, fantasy, bizarre, etc.
Negative emotions:
(1) anxiety: includes stress, tension, unease, uncertainty, confusion, loss of control, powerlessness, doubt, perplexity, etc.
(2) angry: includes disgust, jealousy, aversion, conflict, etc.
(3) sad: includes heartache, disappointment, loneliness, depression, loss, missing, worry, etc.
(4) shame: includes guilt, dissatisfaction, frustration, etc.
(5) fear: includes worry, fright, shock, etc. Neutral emotions: no emotional fluctuations.
Output format:
Primary label: Positive/Negative/Neutral, choose one.
Secondary label: Surprise/Warmth/Shame, etc., list all relevant secondary labels.
Dominant emotion: Determine which secondary emotion is dominant (only one allowed).
2. Now, I will give you some guidance on refining the core image of the dreamscape. (1)Your task is to extract a core image from the user-provided dreamscape description. This image should be a static image, containing a core action, rather than a series of images and actions. (2)Identify and list the key elements in the dreamscape description, such as environment, characters, objects, and actions or events related to these elements. Emphasize those elements that play a bridging role in the dreamscape narrative, and explain how they contribute to the overall dreamscape experience. (3)Pay attention to the emotional clues and atmosphere settings in the description. Point out those details that can reflect the emotional depth of the dreamscape, such as color, light, climate, or expressions, and how these elements work together to create a powerful emotional background. (4)Analyze the dreamscape description based on the following criteria: visual impact, emotional intensity, narrative keyness, symbolic meaning, originality and uniqueness, and detail richness. Determine which elements or scenes best meet these criteria and should be part of the core image. (5)Summarize the core image of the dreamscape, combining the above analysis. Describe why this image can represent the entire dreamscape and explain how it reflects the most prominent emotions and atmosphere in the user's dreamscape experience. After refining the core image, condense it to only two subjects, be sure to condense, and discard unimportant subjects. Provide a clear overview of the core image, within 100 words, no additional explanation needed.
3. Now, we need to do the next step: extract the core action and core subject from your refined core image. Please note the following points: (1)In the core image of the dreamscape, identify and describe a clear core action. This action should be a key turning point or concentrated expression of emotion in the dreamscape plot. (2)Determine the subject (initiator) performing the core action and the subject (receiver) receiving the core action, if applicable. Remember, the subject should be limited to one or a class of people with the same action or core attributes, or objects closely related in space. (3)Ensure there is only one core action and the number of subjects involved is at most two. In describing the action, keep it concise and clear, avoiding introducing additional complexity. (4)Think about the role of the core action in the dreamscape narrative and emotions. How does it define or change the plot of the dreamscape? Does it carry some symbolic meaning? (5)When extracting the core action, consider the overall context of the dreamscape. Describe how this action is closely related to the scene, atmosphere, and emotions of the dreamscape. (6)Exclude any elements from the dreamscape image that are unrelated to the core action. Focus on those details that are essential for understanding and depicting the core action of the dreamscape. (7)After determining the core action and subject, please provide a concise summary, explaining why you think these are the most important elements in the dreamscape.
4. Okay, now that we have the core image and subject, our ultimate goal is to generate prompts for Stable Diffusion, so we still have some work to do in terms of person shifting. Now, based on my instructions, further adjust our proposed core action and core subject. (1)Convert all personal pronouns and names mentioned in the dreamscape description into specific descriptive labels. For example, 'I' can be replaced with 'young person' or 'person in casual wear', 'Tom' can be replaced with 'smiling man', etc. Make guesses and conversions based on the content and context of the dreamscape. (2)Provide a concise image description for each subject. This includes age, gender, physical characteristics, clothing, emotional state, etc., striving to make the description both specific and rich enough for the image generation model to understand. (3)When describing, avoid using information that may lead to privacy issues or specific identity recognition. Instead, use broad descriptive language to express character traits. (4)Use adjectives and metaphors to enhance the vividness and imagery of the description. For example, if the original text mentions 'I feel very scared', it can be transformed into 'a person with a frightened face'. (5)After the transformation, please provide a summary, explaining how you converted personal pronouns and names into descriptive images. If you need more context for accurate conversion, do not hesitate to ask for additional information. (6)Pay attention to gender and age issues. The characters you convert should match the gender and age described in the original description.
5. Okay, now we are going to generate a set of prompts for Stable Diffusion. Please generate a set of prompts according to my instructions. These prompts are used to guide Stable Diffusion in drawing the core actions and main subjects described above. We should selectively provide appropriate details, referring to the description of the dream scenario previously mentioned. (1)We will create a set of prompts for Stable Diffusion. We have divided the scene into two parts using the regional prompt plugin, representing two subjects. Please strictly follow the specified format: general prompts + BREAK + prompts for the first subject + BREAK + prompts for the second subject. (2)General prompt settings: Start by describing how many subjects there are in total, and further explain the information of the subjects through annotations, which are a pair of parentheses immediately following, without a comma separating them. These should briefly describe the overall scene and background, including a general description of the core action. In the general prompts, it should be clearly stated the scene or background environment in which the image occurs, such as a bedroom background. (3)Description of the first subject: Provide a detailed description of the first subject, including appearance, clothing, emotional state, etc., and describe how the core action is expressed in this subject, and how its proactivity is reflected. (4)Description of the second subject: Provide a detailed description of the second subject in the same manner, ensuring that the passivity of the core action in this subject is also reflected.(5) After each subject's description, add annotations to supplement details of the image, including but not limited to clothing, appearance, and details of non-core actions. (6) Ensure that the core action is reflected in the description of both subjects, and that the action is unified and coherent in the image. (7)When generating Stable Diffusion prompts, strictly adhere to specific format requirements. Use English commas to separate all elements, and use parentheses for annotations when mentioning specific features. For actions or features that need emphasis, use the format (keyword:weight), with the weight set between 1.1 and 2.0. (8)In the subject description of each partition, mention the subject first, followed by annotations of its image description. Then, detail how the core action is expressed in that subject. Ensure that annotations follow immediately after the subject description and use parentheses for more details when needed. Please construct the prompts in the following format: 'Subject overview (annotation), core action (background:weight), facial orientation, dynamic vocabulary, general prompts BREAK partition subject 1 (annotation:detailed information), core action on subject 1 BREAK partition subject 2 (annotation:detailed information), core action on subject 2'. Each element should be separated by commas and adhere to format standards and weight emphasis. (9)Please note that each subject should only retain one core action. (10)Be sure to increase the weight for the main characters. (11)Use the correct prompts to show the differences between subjects, such as man, woman; human, animal. (12)For subjects that are absent in the scene, do not write prompts for them. Now, if you have understood what I am trying to convey, I will give a specific example, and then you can generate prompts based on the example I provide. The requirements are as simple as possible, highlighting core elements and core actions. Minimize minor details.
6. Please strictly follow the format I provided. The example I gave is:
2 people (1 boy and 1 girl), walking, (street_background:1.3), (looking at viewer), dynamic pose, dynamic angle, BREAK 1 girl (red long hair and red eye), (red shirt:1.3), BREAK 1 boy (yellow short hair and yellow eyes), (yellow suit:1.3) and hands in pocket.
Please output the final result in JSON format, for example:
{
"emotion": {
"category": "negative",
"tags": ["anxiety", "sad"],
"dominant": "anxiety"
}
"image": "A child in the different rooms of a childhood home",
"action_subject": "A child explores various familiar spaces",
"prompt": "1 person(anxious child in familiar spaces),exploring,(home setting:1.5),nostalgic mood, BREAK child(anxious expression, casual clothes), BREAK rooms mimicking childhood home(unchanging setting:1.2), constant exploration"
}
"""
system_prompts = [("dream_interpret", dream_interpretation_prompt), ("generate_sd_prompt", dream_sd_prompt_generation_prompt)]
chat = gr.ChatInterface(
predict,
additional_inputs=[
gr.Dropdown(model, label="Model", value="gpt-4-1106-preview"),
# gr.TextArea(dream_sd_prompt_generation_prompt, label="System Prompt"),
gr.Dropdown(system_prompts, label="System Prompt", choices=system_prompts ,value=system_prompts[1][1]),
],
)
with gr.Blocks() as app:
gr.Markdown("## 1. Interprete Your Dream")
chat.render()
gr.Markdown("## 2. Generate Final SD Prompt")
sd_raw_prompt = gr.Textbox(
label="Raw Prompt", placeholder="Copy your sd prompt json from above chat result here"
)
with gr.Row():
art_style = gr.Radio(
label="Art Style",
choices=[
"CARTOON",
"FANTASY_ART",
"CUBIST_ARTWORK",
"VOXEL_ART",
"3D_GAME",
],
value="CARTOON",
)
generate_button = gr.Button("Generate")
sd_final_prompt = gr.Textbox(label="Final Prompt")
generate_button.click(
fn=sd_prompt_refine,
inputs=[sd_raw_prompt, art_style],
outputs=[sd_final_prompt],
)
gr.Markdown("## 3. Paint Your Dream")
draw_button = gr.Button("Let's Paint")
with gr.Row():
with gr.Column():
prompt = gr.Textbox(
label="Prompt", placeholder="Type your prompt here...", value=""
)
negative_prompt = gr.Textbox(
label="Negative Prompt",
placeholder="Type your negative prompt here...",
value="lowres,bad anatomy,bad hand,paintings,sketches,(worst quality:2)(lowquality:2),(normal quality:2),lowres,((monochrome)), (grayscale)),skin spots,acnes,skin blemishes,age spot,glans,extrafngers,fewerfngers,((watermark:2)),(white letters:1),(multinipples),bad anatomy,badhands,text,error,missing fngers,missingarms,missing legs,extra digit,fewerdigits,cropped,worst quality,jpegartifacts,signature,watermark,username,badfeet,[Multiplepeople},blurry,poorly drawn hands,poorlydrawnface,mutation,deformed,extra limbs,extra arms,extraegs,malformedlimbs,fused fngers,too many fngers,longneck,cross-eyed,mutated hands,polarlowres,bad body,badproportrtions,gross proportrtions,wrong feet bottomrender,abdominastretch,briefs,knickers,kecks,thong,llfused fngers]},[lbadbodyll,badproportrtion body to legs,wrong toes,extra toes,missingtoes,weird toes,2 body,2pussy,2 upper,2 lower,2 head,3hand,3feet,extra long leg,super long leg,mirroredimage,mirrored noise,",
)
seed = gr.Number(label="Seed", value=-1)
sampler = gr.Textbox(label="Sampler Name", value="DPM++ 2M Karras")
batch_size = gr.Number(label="Batch Size", value=1)
n_iter = gr.Number(label="n_iter", value=1)
steps = gr.Number(label="Steps", value=17)
cfg_scale = gr.Number(label="CFG Scale", value=7)
width = gr.Number(label="Width", value=768)
height = gr.Number(label="Height", value=768)
script = gr.Textbox(
label="Alwayson Scripts",
value="""
{
"Regional Prompter": {
"args": ["True","False","Matrix","Columns","Mask","Prompt","1,1","0.2","False","True","False","Attention","","0","0","0","0","0","0"]
}
}
""",
)
with gr.Column():
images = gr.Gallery(label="Generated Images") # 使用图库来展示多个图像
execution_info = gr.Textbox(label="Execution")
error = gr.Textbox(label="Error")
param_info = gr.JSON(label="Parameters")
image_info = gr.JSON(label="Info")
draw_button.click(
fn=txt2img,
inputs=[
prompt,
negative_prompt,
seed,
sampler,
batch_size,
n_iter,
steps,
cfg_scale,
width,
height,
script,
],
outputs=[images, execution_info, error, param_info, image_info],
)
sd_final_prompt.change(update_prompt, inputs=sd_final_prompt, outputs=prompt)
# 启动Gradio应用程序
app.launch()