DiffusionGPT commited on
Commit
caf2830
·
1 Parent(s): 4560dce
Files changed (1) hide show
  1. app.py +701 -0
app.py ADDED
@@ -0,0 +1,701 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding: utf-8
2
+ import os
3
+ import gradio as gr
4
+ import random
5
+ import torch
6
+ import cv2
7
+ import re
8
+ import uuid
9
+ import json
10
+ import pickle
11
+ from PIL import Image, ImageDraw, ImageOps, ImageFont
12
+ import math
13
+ import numpy as np
14
+ import argparse
15
+ import inspect
16
+ import tempfile
17
+ # import subprocess
18
+
19
+ from diffusers import StableDiffusionPipeline, StableDiffusionInpaintPipeline, StableDiffusionInstructPix2PixPipeline
20
+ from diffusers import EulerAncestralDiscreteScheduler, PNDMScheduler
21
+ from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, DiffusionPipeline, UniPCMultistepScheduler
22
+
23
+ from langchain.agents.initialize import initialize_agent
24
+ from langchain.agents.tools import Tool
25
+ from langchain.chains.conversation.memory import ConversationBufferMemory
26
+ from langchain.llms.openai import OpenAI
27
+ from langchain.llms import AzureOpenAI
28
+ from langchain_llm_api import LLMAPI
29
+
30
+
31
+ from sentence_transformers import SentenceTransformer
32
+ from compel import Compel
33
+
34
+
35
+ PREFIX = """DiffusionGPT is designed to be able to assist users in generating high-quality images.
36
+
37
+ Human may provide some text prompts to DiffusionGPT. The input prompts will be analyzed by DiffusionGPT to select the most suitable generative model for generating images.
38
+
39
+ Overall, DiffusionGPT is a powerful image generation system that can assist in processing various forms of textual input and match them with the most suitable generative model to accomplish the generation task.
40
+
41
+ TOOLS:
42
+ ------
43
+
44
+ DiffusionGPT has access to the following tools:"""
45
+
46
+ FORMAT_INSTRUCTIONS = """To use a tool, please use the following format:
47
+
48
+ ```
49
+ Thought: Do I need to use a tool? Yes
50
+ Action: the action to take, should be one of [{tool_names}]
51
+ Action Input: the input to the action
52
+ Observation: the result of the action
53
+ ```
54
+
55
+ When you have a response to say to the Human, or if you do not need to use a tool, you MUST use the format:
56
+
57
+ ```
58
+ Thought: Do I need to use a tool? No
59
+ {ai_prefix}: [your response here]
60
+ ```
61
+ """
62
+
63
+ SUFFIX = """You are very strict to the filename correctness and will never fake a file name if it does not exist.
64
+ You will remember to provide the image file name loyally if it's provided in the last tool observation.
65
+
66
+ Begin!
67
+
68
+ Previous conversation history:
69
+ {chat_history}
70
+
71
+ New input: {input}
72
+ DiffusionGPT must use tools to observe images rather than imagination.
73
+ The thoughts and observations are only visible for DiffusionGPT, DiffusionGPT should remember to repeat important information in the final response for Human.
74
+ Thought: Do I need to use a tool? {agent_scratchpad} Let's think step by step.
75
+ """
76
+
77
+
78
+ TOT_PROMPTS = """Identify and behave as five different experts that are appropriate to select one element from the input list that best matches the input prompt.
79
+ All experts will write down the selection result, then share it with the group.
80
+
81
+ You then analyze all 5 analyses and output the consensus selected element or your best guess matched element.
82
+ The final selection output MUST be the same as the TEMPLATE:
83
+ TEMPLATE:
84
+ ```
85
+ Selected: [the selected word]
86
+ ```
87
+
88
+ Input list: {search_list}
89
+
90
+ Input prompt: {input}
91
+ """
92
+
93
+
94
+ PROMPT_PARSE_PROMPTS = """Given the user input text.
95
+ Please judge the paradigm of the input text, and then recognize the main string of text prompts according to the corresponding form.
96
+ The output must be same as the TEMPlATE:
97
+
98
+ TEMPLATE:
99
+ ```
100
+ Prompts: [the output prompts]
101
+ ```
102
+
103
+ For instance:
104
+ 1. Input: A dog
105
+ Prompts: A dog
106
+ 2. Input: generate an image of a dog
107
+ Prompts: an image of a dog
108
+ 3. Input: I want to see a beach
109
+ Prompts: a beach
110
+ 4. Input: If you give me a toy, I will laugh very happily
111
+ Prompts: a toy and a laugh face
112
+
113
+ Input: {inputs}
114
+
115
+ """
116
+
117
+
118
+ TREE_OF_MODEL_PROMPT_SUBJECT = """ You are an information analyst who can analyze and abstract a set of words to abstract some representation categories.
119
+ Below is a template that can represent the abstracted categories in Subject Dimension belonging to concrete noun:
120
+
121
+ TEMPLATE:
122
+ ```
123
+ Categories:
124
+ - [Subject]
125
+ - [Subject]
126
+ - ...
127
+ ```
128
+
129
+ You MUST abstract the categories in a highly abstract manner only from Subject Dimension and ensure the whole number of categories are fewer than 5.
130
+ Then, You MUST remove the Style-related categories.
131
+
132
+ Please output the categories following the format of TEMPLATE.
133
+
134
+ Input: {input}
135
+
136
+ """
137
+
138
+ TREE_OF_MODEL_PROMPT_STYLE = """ You are an information analyst who can analyze and summarize a set of words to abstract some representation categories.
139
+ Below is a template that can represent the the abstracted categories in Style Dimension:
140
+
141
+ TEMPLATE:
142
+ ```
143
+ Categories:
144
+ - [Style]
145
+ - [Style]
146
+ - ...
147
+ ```
148
+
149
+ You MUST abstract the categories in a highly abstract manner from only Style dimension and ensure the whole number of categories are fewer than 8.
150
+
151
+ Please output the Categories following the format of TEMPLATE.
152
+
153
+ Input: {input}
154
+
155
+ """
156
+
157
+ TREE_OF_MODEL_PROMPT_ = """ You are an information analyst who can create a Knowledge Tree according to the input categories.
158
+ Below is a knowledge tree template:
159
+
160
+ TEMPLATE:
161
+ ```
162
+ Knowledge Tree:
163
+ - [Subject]
164
+ - [Style]
165
+ - ...
166
+ - [Subject]
167
+ - ...
168
+ ```
169
+
170
+ You MUST place the each Style category as subcategory under the Subject categories based on whether it can be well matched with a specific subject category to form a reasonable scene.
171
+
172
+ Please output the categories following the format of TEMPLATE.
173
+
174
+ Subject Input: {subject}
175
+
176
+ Style Input: {style}
177
+
178
+ """
179
+
180
+
181
+ TREE_OF_MODEL_PROMPT_ADD_MODELS = """ You are an information analyst who can add some input models to an input knowledge tree according to the similarity of the model tags and the categories of the knowledge tree.
182
+
183
+ You need to place each input model into the appropriate subcategory on the tree, one by one.
184
+ You MUST keep the original content of the knowledge tree.
185
+
186
+
187
+ Please output the final knowledge tree.
188
+
189
+ Knowledge Tree Input: {tree}
190
+
191
+ Models Input: {models}
192
+
193
+ Model Tags Input: {model_tags}
194
+
195
+ """
196
+
197
+
198
+ os.makedirs('image', exist_ok=True)
199
+
200
+
201
+ from langchain.llms.base import LLM
202
+
203
+ from langchain import PromptTemplate, HuggingFaceHub
204
+ from langchain.llms import HuggingFacePipeline
205
+
206
+ from transformers import AutoTokenizer, AutoModelForCausalLM
207
+
208
+
209
+ def seed_everything(seed):
210
+ random.seed(seed)
211
+ np.random.seed(seed)
212
+ torch.manual_seed(seed)
213
+ torch.cuda.manual_seed_all(seed)
214
+ return seed
215
+
216
+
217
+ def prompts(name, description):
218
+ def decorator(func):
219
+ func.name = name
220
+ func.description = description
221
+ return func
222
+
223
+ return decorator
224
+
225
+
226
+ def cut_dialogue_history(history_memory, keep_last_n_words=500):
227
+ if history_memory is None or len(history_memory) == 0:
228
+ return history_memory
229
+ tokens = history_memory.split()
230
+ n_tokens = len(tokens)
231
+
232
+ if n_tokens < keep_last_n_words:
233
+ return history_memory
234
+ paragraphs = history_memory.split('\n')
235
+ last_n_tokens = n_tokens
236
+ while last_n_tokens >= keep_last_n_words:
237
+ last_n_tokens -= len(paragraphs[0].split(' '))
238
+ paragraphs = paragraphs[1:]
239
+ return '\n' + '\n'.join(paragraphs)
240
+
241
+
242
+ class Text2Image:
243
+ def __init__(self, device):
244
+ print(f"Initializing Text2Image to {device}")
245
+ self.device = device
246
+ self.torch_dtype = torch.float16 if 'cuda' in device else torch.float32
247
+
248
+ self.llm = OpenAI(temperature=0)
249
+
250
+ if not os.path.exists('model_tree_tot_sd15.json'):
251
+ with open('model_data_sd15.json', 'r') as f:
252
+ self.model_data_all = json.load(f)
253
+
254
+ model_tags = {model["model_name"]: model["tag"] for model in self.model_data_all}
255
+
256
+ model_tree = self.build_tree(model_tags)
257
+
258
+ model_all_data = {model["model_name"].split(".")[0]: model for model in self.model_data_all}
259
+
260
+ save_model_tree = {}
261
+ for cate_name, sub_category in model_tree.items():
262
+ cate_name = cate_name.lower()
263
+ temp_category = {}
264
+
265
+ if "Universal" not in sub_category:
266
+ temp_category["universal"] = [model_all_data["majicmixRealistic_v6"], model_all_data["FilmVelvia2"]]
267
+
268
+ for sec_cate_name, sub_sub_cates in sub_category.items():
269
+ sec_cate_name = sec_cate_name.lower()
270
+ temp_model_list = []
271
+
272
+ for model_name in sub_sub_cates:
273
+ model_name = model_name.strip()
274
+ lower_name = model_name[0].lower() + model_name[1:]
275
+ if model_name in model_all_data:
276
+ temp_model_list.append(model_all_data[model_name])
277
+ elif lower_name in model_all_data:
278
+ temp_model_list.append(model_all_data[lower_name])
279
+
280
+
281
+ temp_category[sec_cate_name] = temp_model_list
282
+
283
+ save_model_tree[cate_name] = temp_category
284
+
285
+ # write in json
286
+ json_data = json.dumps(save_model_tree, indent=2)
287
+ with open('model_tree_tot_sd15.json', 'w') as f:
288
+ f.write(json_data)
289
+ f.close()
290
+
291
+
292
+ with open('model_tree_tot_sd15.json', 'r') as f:
293
+ self.model_data = json.load(f)
294
+
295
+ with open('model_data_sd15.json', 'r') as f:
296
+ self.model_all_data = json.load(f)
297
+ self.model_all_data = {model["model_name"]:model for model in self.model_all_data}
298
+
299
+ # Advantage databases with human feedback
300
+ with open('./VectorDB_HF/prompt_embed_st.pickle', 'rb') as f:
301
+ self.pt_pairs = pickle.load(f)
302
+
303
+ with open('./VectorDB_HF/prompt2scores.json', 'r') as f:
304
+ self.prompt2scores = json.load(f)
305
+
306
+ self.st_model = SentenceTransformer('sentence-transformers/all-MiniLM-L6-v2')
307
+
308
+
309
+ def build_tree(self, model_tags):
310
+ tags_only = list(model_tags.values())
311
+ model_names = list(model_tags.keys())
312
+
313
+ prompts = TREE_OF_MODEL_PROMPT.format(input=tags_only)
314
+
315
+ prompt1 = TREE_OF_MODEL_PROMPT_SUBJECT.format(input=tags_only)
316
+ response1 = self.llm(prompt1)
317
+
318
+ prompt2 = TREE_OF_MODEL_PROMPT_STYLE.format(input=tags_only)
319
+ response2 = self.llm(prompt2)
320
+
321
+ prompt_tree = TREE_OF_MODEL_PROMPT_.format(style=response2, subject=response1)
322
+ response = self.llm(prompt_tree)
323
+
324
+ tree = response.split("Knowledge Tree:")[1]
325
+
326
+ model_names = [name.split(".")[0] for name in list(model_tags.keys())]
327
+
328
+ prompts = TREE_OF_MODEL_PROMPT_ADD_MODELS.format(model_tags=model_tags, tree=tree, models=model_names)
329
+
330
+ tree = self.llm(prompts)
331
+
332
+ output = {}
333
+ tree_list = tree.split("\n")
334
+ for category in tree_list:
335
+ if category == '':
336
+ continue
337
+
338
+ if category.startswith("- "):
339
+ current_key = category[2:]
340
+ output[current_key] = {}
341
+ elif category.startswith(" - "):
342
+ next_key = category[4:]
343
+ output[current_key][next_key] = []
344
+ elif category.startswith(" - "):
345
+ output[current_key][next_key].append(category[6:])
346
+
347
+ return output
348
+
349
+ def prompt_parse(self, inputs):
350
+
351
+ prompts = PROMPT_PARSE_PROMPTS.format(inputs=inputs)
352
+ output = self.llm(prompts)
353
+ output = output.split("Prompts:")[1]
354
+
355
+ return output.strip()
356
+
357
+ def get_property(self, model_data):
358
+ properties = []
359
+ for model in model_data:
360
+ name = "model_name:" + model["model_name"] + ", "
361
+ tag = "tag:" + ",".join(model["tag"])
362
+
363
+ prop = name + tag + "\n\n"
364
+ properties.append(prop)
365
+ return properties
366
+
367
+ def search_one_matched(self, inputs, search_list):
368
+
369
+ tot_prompts = TOT_PROMPTS.format(search_list=search_list, input=inputs)
370
+
371
+ model_name = self.llm(tot_prompts)
372
+ print(model_name)
373
+
374
+ if "Selected:" in model_name:
375
+ model_name = model_name.split("Selected:")[-1]
376
+
377
+ for ch in [",", ";", "."]:
378
+ if ch in model_name:
379
+ model_name = model_name.split(ch)[0]
380
+ model_name = model_name.strip().lower()
381
+
382
+ return model_name
383
+
384
+
385
+ def select_best_model_with_HF(self, inputs, model_space):
386
+
387
+ text_embed = torch.Tensor(self.st_model.encode([inputs]) )
388
+ text_embed /= text_embed.norm(dim=1, keepdim=True)
389
+
390
+ similarity = text_embed @ self.pt_pairs['text_embeds'].T
391
+
392
+ topk_idxs = similarity.topk(5).indices[0,:]
393
+
394
+ topk_model_list = []
395
+ model_names_of_tree = [model["model_name"].split(".")[0] for model in model_space]
396
+
397
+ for idx, p in enumerate(topk_idxs):
398
+
399
+ save_prompt_name = self.pt_pairs['prompts'][int(p)][:100].replace('\n','')
400
+
401
+ model_scores = self.prompt2scores[save_prompt_name]
402
+
403
+ model_names = list(model_scores.keys())
404
+ reward_scores = []
405
+ for name, values in model_scores.items():
406
+ reward_scores.append(values['image_reward'])
407
+
408
+ reward_scores = torch.Tensor(reward_scores)
409
+ topk_model_idx = reward_scores.topk(5).indices.tolist()
410
+ topk_models = [model_names[i] for i in topk_model_idx]
411
+
412
+ topk_model_list.append(topk_models)
413
+
414
+ prompt1 = f"Please judge whether each name in this list {model_names_of_tree} has highly similar name in the list {topk_model_list}, if yes, output the similar model name, the output MUST be Template: Model: [model name, ...]"
415
+ intersection_model = self.llm(prompt1)
416
+
417
+ prompts = f"Please select one model name from the following model list {intersection_model} that has the highest frequency and top ranking according to the list {topk_model_list}.\n\n The output MUST be Template: Model: [model name]"
418
+ selected_model = self.llm(prompts)
419
+ selected_model = selected_model.split("Model:")[1]
420
+
421
+ return selected_model.strip()
422
+
423
+ def search_model_tree(self, inputs):
424
+ search_space = self.model_data
425
+ search_path = []
426
+
427
+ while not isinstance(search_space, list):
428
+ search_list = list(search_space.keys())
429
+ name = self.search_one_matched(inputs, search_list)
430
+ search_path.append(name)
431
+ search_space = search_space[name]
432
+
433
+ candidate_model_data = {}
434
+ for model in search_space:
435
+ candidate_model_data[model["model_name"]] = model
436
+
437
+ model_properties = self.get_property(search_space)
438
+
439
+ model_name_pre = self.select_best_model_with_HF(inputs, search_space)
440
+ all_names = list(self.model_all_data.keys())
441
+ all_names = [name + "\n" for name in all_names]
442
+
443
+ prompts = f"Please according to the name of {model_name_pre} and select one element from the list bellow, and ensure the selected element MUST be the same as one of the list {all_names}."
444
+ model_name = self.llm(prompts).strip('\n')
445
+
446
+
447
+ if model_name not in self.model_all_data:
448
+ model_name = model_name[0].lower() + model_name[1:]
449
+ selected_model = self.model_all_data[model_name]
450
+
451
+ search_path.append(model_name)
452
+
453
+ return search_path, selected_model
454
+
455
+
456
+ def prompt_entension(self, inputs, model):
457
+ example_prompt = model["example_prompts"][0]
458
+ example_n_prompt = model["negtive_prompts"][0]
459
+
460
+ prompts = f"Here is a paragraph describing an image. " \
461
+ f"{inputs}. " \
462
+ f"Please follow the sentence pattern of the example to expand the description of the input paragraph. The output MUST preserve the contents of the input paragraph. Example: {example_prompt}."
463
+
464
+ extended_prompt = self.llm(prompts)
465
+
466
+ return extended_prompt, example_n_prompt
467
+
468
+ def match_id(self, model):
469
+
470
+ model_names = list(self.model_all_data.keys())
471
+
472
+ prompts = f"Here is a model. " \
473
+ f"{model}. " \
474
+ f"Please select the model name that best matches the given model from the model name list {model_names}. " \
475
+ f"The output must be the same as the word in the list. "
476
+
477
+ matched_name = self.llm(prompts)
478
+ matched_name = matched_name[2:]
479
+
480
+ return matched_name
481
+
482
+
483
+ @prompts(name="Generate Image From User Input Text",
484
+ description="always useful to generate an image from a user input text and save it to a file. "
485
+ "The input to this tool MUST be the whole user input text.")
486
+
487
+
488
+ def inference(self, inputs):
489
+ # Prompt Parse
490
+ original_input = inputs
491
+ inputs = self.prompt_parse(inputs)
492
+
493
+ # search model tree
494
+ model_select_path, selected_model_data = self.search_model_tree(inputs)
495
+ print("Selected model path:", model_select_path)
496
+ print("Selected model name:", selected_model_data["model_name"])
497
+
498
+ model_name = selected_model_data["model_name"]
499
+ model_type = selected_model_data["model_type"]
500
+
501
+
502
+ # load model ckpt
503
+ self.pipe_prior = None
504
+ if "checkpoint" in model_type:
505
+
506
+ if model_name in list(self.model_all_data.keys()):
507
+ model_id = "./checkpoints/" + model_name
508
+ self.pipe = StableDiffusionPipeline.from_single_file(model_id, torch_dtype=self.torch_dtype)
509
+
510
+ self.pipe.to(self.device)
511
+
512
+ # load model lora
513
+ elif model_type == "lora":
514
+
515
+ base_model = selected_model_data["resources_used"][0]
516
+ base_model_name = self.match_id(base_model)
517
+ base_model_name = "./checkpoints/" + base_model_name
518
+ print(base_model_name)
519
+ self.pipe = StableDiffusionPipeline.from_single_file(base_model_name, torch_dtype=self.torch_dtype)
520
+
521
+ self.pipe.to(self.device)
522
+ self.pipe.load_lora_weights("./checkpoints", weight_name=model_name)
523
+
524
+ # Prompt Extension
525
+ if selected_model_data["example_prompts"][0] != "None":
526
+ prompt, n_prompt = self.prompt_entension(inputs, selected_model_data)
527
+ else:
528
+ prompt = inputs
529
+ n_prompt = selected_model_data["negtive_prompts"][0]
530
+
531
+ if n_prompt == "None":
532
+ n_prompt = ""
533
+
534
+ prompt_embeds = None
535
+
536
+
537
+ ## compel for long text
538
+ compel = Compel(tokenizer=self.pipe.tokenizer, text_encoder=self.pipe.text_encoder, truncate_long_prompts=False)
539
+
540
+ prompt_list = list(prompt.strip().split("."))
541
+ n_prompt_list = list(n_prompt.strip().split("."))
542
+ prompt = f'{prompt_list}.and()'
543
+ n_prompt = f'{n_prompt_list}.and()'
544
+
545
+ prompt_embeds = compel.build_conditioning_tensor(prompt)
546
+ negative_conditioning = compel.build_conditioning_tensor(n_prompt)
547
+ [prompt_embeds, negative_conditioning] = compel.pad_conditioning_tensors_to_same_length([prompt_embeds, negative_conditioning])
548
+ negative_prompt_embeds = negative_conditioning
549
+
550
+
551
+ if prompt_embeds is not None:
552
+
553
+ output_latents = self.pipe(prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, num_images_per_prompt=1, output_type='latent').images
554
+ with torch.no_grad():
555
+ images = self.pipe.decode_latents(output_latents)
556
+ images = self.pipe.numpy_to_pil(images)
557
+ else:
558
+ output_latents = self.pipe(prompt, negative_prompt=n_prompt, height=512, width=512, num_images_per_prompt=1, output_type='latent').images
559
+ with torch.no_grad():
560
+ images = self.pipe.decode_latents(output_latents)
561
+ images = self.pipe.numpy_to_pil(images)
562
+
563
+ image_filename = os.path.join('image', f"{str(uuid.uuid4())[:8]}.png")
564
+
565
+ output = images[0]
566
+ output.save(image_filename)
567
+
568
+ print(
569
+ f"\nProcessed Text2Image, Input Text: {inputs}, Output Image: {image_filename}")
570
+ return image_filename
571
+
572
+
573
+
574
+ class ConversationBot:
575
+ def __init__(self, load_dict):
576
+ print(f"Initializing DiffusionGPT, load_dict={load_dict}")
577
+
578
+ self.models = {}
579
+ # Load Basic Foundation Models
580
+ for class_name, device in load_dict.items():
581
+ self.models[class_name] = globals()[class_name](device=device)
582
+
583
+ # Load Template Foundation Models
584
+ for class_name, module in globals().items():
585
+ if getattr(module, 'template_model', False):
586
+ template_required_names = {k for k in inspect.signature(module.__init__).parameters.keys() if k!='self'}
587
+ loaded_names = set([type(e).__name__ for e in self.models.values()])
588
+ if template_required_names.issubset(loaded_names):
589
+ self.models[class_name] = globals()[class_name](
590
+ **{name: self.models[name] for name in template_required_names})
591
+
592
+ print(f"All the Available Functions: {self.models}")
593
+
594
+ self.tools = []
595
+ for instance in self.models.values():
596
+ for e in dir(instance):
597
+ if e.startswith('inference'):
598
+ func = getattr(instance, e)
599
+ self.tools.append(Tool(name=func.name, description=func.description, func=func))
600
+ self.llm = OpenAI(temperature=0)
601
+
602
+ self.memory = ConversationBufferMemory(memory_key="chat_history", output_key='output')
603
+
604
+ def init_agent(self, lang):
605
+ self.memory.clear() #clear previous history
606
+
607
+ place = "Enter text and press enter, or upload an image"
608
+ label_clear = "Clear"
609
+
610
+ self.agent = initialize_agent(
611
+ self.tools,
612
+ self.llm,
613
+ agent="conversational-react-description",
614
+ verbose=True,
615
+ memory=self.memory,
616
+ return_intermediate_steps=True,
617
+ agent_kwargs={'prefix': PREFIX, 'format_instructions': FORMAT_INSTRUCTIONS,
618
+ 'suffix': SUFFIX},
619
+ handle_parsing_errors="Check your output and make sure it conforms!" )
620
+ return gr.update(visible = True), gr.update(visible = False), gr.update(placeholder=place), gr.update(value=label_clear)
621
+
622
+ def run_text(self, text, state):
623
+
624
+ self.agent.memory.buffer = cut_dialogue_history(self.agent.memory.buffer, keep_last_n_words=500)
625
+ res = self.agent({"input": text.strip()})
626
+ res['output'] = res['output'].replace("\\", "/")
627
+ response = re.sub('(image/[-\w]*.png)', lambda m: f'![](file={m.group(0)})*{m.group(0)}*', res['output'])
628
+ state = state + [(text, response)]
629
+ print(f"\nProcessed run_text, Input text: {text}\n")
630
+ return state, state
631
+
632
+
633
+ if __name__ == '__main__':
634
+
635
+ parser = argparse.ArgumentParser()
636
+ parser.add_argument('--load', type=str, default="Text2Image_cuda:0")
637
+ args = parser.parse_args()
638
+ load_dict = {e.split('_')[0].strip(): e.split('_')[1].strip() for e in args.load.split(',')}
639
+
640
+ def init_api(apikey):
641
+ os.environ['OPENAI_API_KEY'] = apikey
642
+ global bot
643
+ bot = ConversationBot(load_dict=load_dict)
644
+ print('set new api key:', apikey)
645
+ return None
646
+
647
+ init_api(apikey="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")
648
+ def inference_warp(prompt):
649
+ prompt = prompt.strip()
650
+ global bot
651
+ state = []
652
+ _, state = bot.run_text(prompt, state)
653
+
654
+ print('========>', str(state))
655
+
656
+ pattern = r"\(file=(.*?)\)"
657
+ matches = re.findall(pattern, str(state))
658
+
659
+
660
+ if matches:
661
+ file_path = matches[0]
662
+ print(file_path)
663
+
664
+
665
+ image = Image.open(file_path)
666
+ return image
667
+
668
+ with gr.Blocks(css="#chatbot .overflow-y-auto{height:1000px}") as demo:
669
+ state = gr.State([])
670
+ with gr.Row():
671
+ with gr.Column():
672
+ apikey = gr.Textbox(label='apikey', value="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")
673
+ prompt = gr.Textbox(label='Prompt')
674
+ run_button = gr.Button('Generate Image')
675
+
676
+ result = gr.Image(label="Generated Image")
677
+ bot.init_agent("English")
678
+ run_button.click(fn=inference_warp,
679
+ inputs=prompt,
680
+ outputs=result,)
681
+
682
+ apikey.change(fn=init_api, inputs=[apikey])
683
+
684
+
685
+ examples = [
686
+ ["a girl with dress and red hat."],
687
+ ["generate an image of a laughing woman, fashion magazine cover."],
688
+ ["a cat on the grass."],
689
+ ["create an illustration of a romantic couple sharing a tender moment under a starry sky."],
690
+ ["a robot cooking in the kitchen."]
691
+
692
+ ]
693
+ gr.Examples(examples=examples,
694
+ inputs=prompt,
695
+ outputs=result,
696
+ fn=inference_warp,
697
+ cache_examples=True,
698
+ run_on_click=True
699
+ )
700
+
701
+ demo.launch(server_name="0.0.0.0", server_port=7862)