hahafofo commited on
Commit
48f4d16
1 Parent(s): ceb89be
Files changed (2) hide show
  1. app.py +235 -0
  2. requirements.txt +6 -0
app.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import re
3
+
4
+ import gradio as gr
5
+ import torch
6
+ from transformers import AutoModelForCausalLM, AutoTokenizer
7
+ from transformers import pipeline, set_seed
8
+
9
+ from utils.image2text import git_image2text, w14_image2text, clip_image2text
10
+ from utils.singleton import Singleton
11
+ from utils.translate import en2zh as translate_en2zh
12
+ from utils.translate import zh2en as translate_zh2en
13
+ from utils.exif import get_image_info
14
+
15
+ device = "cuda" if torch.cuda.is_available() else "cpu"
16
+
17
+
18
+ @Singleton
19
+ class Models(object):
20
+
21
+ def __getattr__(self, item):
22
+ if item in self.__dict__:
23
+ return getattr(self, item)
24
+
25
+ if item in ('big_model', 'big_processor'):
26
+ self.big_model, self.big_processor = self.load_image2text_model()
27
+
28
+ if item in ('prompter_model', 'prompter_tokenizer'):
29
+ self.prompter_model, self.prompter_tokenizer = self.load_prompter_model()
30
+
31
+ if item in ('text_pipe',):
32
+ self.text_pipe = self.load_text_generation_pipeline()
33
+
34
+ return getattr(self, item)
35
+
36
+ @classmethod
37
+ def load_text_generation_pipeline(cls):
38
+ return pipeline('text-generation', model='succinctly/text2image-prompt-generator')
39
+
40
+ @classmethod
41
+ def load_prompter_model(cls):
42
+ prompter_model = AutoModelForCausalLM.from_pretrained("microsoft/Promptist")
43
+ tokenizer = AutoTokenizer.from_pretrained("gpt2")
44
+ tokenizer.pad_token = tokenizer.eos_token
45
+ tokenizer.padding_side = "left"
46
+ return prompter_model, tokenizer
47
+
48
+
49
+ models = Models.instance()
50
+
51
+
52
+ def generate_prompter(plain_text, max_new_tokens=75, num_beams=8, num_return_sequences=8, length_penalty=-1.0):
53
+ input_ids = models.prompter_tokenizer(plain_text.strip() + " Rephrase:", return_tensors="pt").input_ids
54
+ eos_id = models.prompter_tokenizer.eos_token_id
55
+ outputs = models.prompter_model.generate(
56
+ input_ids,
57
+ do_sample=False,
58
+ max_new_tokens=max_new_tokens,
59
+ num_beams=num_beams,
60
+ num_return_sequences=num_return_sequences,
61
+ eos_token_id=eos_id,
62
+ pad_token_id=eos_id,
63
+ length_penalty=length_penalty
64
+ )
65
+ output_texts = models.prompter_tokenizer.batch_decode(outputs, skip_special_tokens=True)
66
+ result = []
67
+ for output_text in output_texts:
68
+ result.append(output_text.replace(plain_text + " Rephrase:", "").strip())
69
+
70
+ return "\n".join(result)
71
+
72
+
73
+ def image_generate_prompter(
74
+ bclip_text,
75
+ w14_text,
76
+ max_new_tokens=75,
77
+ num_beams=8,
78
+ num_return_sequences=8,
79
+ length_penalty=-1.0
80
+ ):
81
+ result = generate_prompter(
82
+ bclip_text,
83
+ max_new_tokens,
84
+ num_beams,
85
+ num_return_sequences,
86
+ length_penalty
87
+ )
88
+ return "\n".join(["{},{}".format(line.strip(), w14_text.strip()) for line in result.split("\n") if len(line) > 0])
89
+
90
+
91
+ def text_generate(text_in_english):
92
+ seed = random.randint(100, 1000000)
93
+ set_seed(seed)
94
+
95
+ result = ""
96
+ for _ in range(6):
97
+ sequences = models.text_pipe(text_in_english, max_length=random.randint(60, 90), num_return_sequences=8)
98
+ list = []
99
+ for sequence in sequences:
100
+ line = sequence['generated_text'].strip()
101
+ if line != text_in_english and len(line) > (len(text_in_english) + 4) and line.endswith(
102
+ (':', '-', '—')) is False:
103
+ list.append(line)
104
+
105
+ result = "\n".join(list)
106
+ result = re.sub('[^ ]+\.[^ ]+', '', result)
107
+ result = result.replace('<', '').replace('>', '')
108
+ if result != '':
109
+ break
110
+ return result, "\n".join(translate_en2zh(line) for line in result.split("\n") if len(line) > 0)
111
+
112
+
113
+ with gr.Blocks(title="Prompt生成器") as block:
114
+ with gr.Column():
115
+
116
+ with gr.Tab('从图片中生成'):
117
+ with gr.Row():
118
+ input_image = gr.Image(type='pil')
119
+ exif_info = gr.HTML()
120
+ output_blip_or_clip = gr.Textbox(label='生成的 Prompt')
121
+ output_w14 = gr.Textbox(label='W14的 Prompt')
122
+
123
+ with gr.Accordion('W14', open=False):
124
+ w14_raw_output = gr.Textbox(label="Output (raw string)")
125
+ w14_booru_output = gr.Textbox(label="Output (booru string)")
126
+ w14_rating_output = gr.Label(label="Rating")
127
+ w14_characters_output = gr.Label(label="Output (characters)")
128
+ w14_tags_output = gr.Label(label="Output (tags)")
129
+ images_generate_prompter_output = gr.Textbox(lines=6, label='SD优化的 Prompt')
130
+ with gr.Row():
131
+ img_exif_btn = gr.Button('EXIF')
132
+ img_blip_btn = gr.Button('BLIP图片转描述')
133
+ img_w14_btn = gr.Button('W14图片转描述')
134
+ img_clip_btn = gr.Button('CLIP图片转描述')
135
+ img_prompter_btn = gr.Button('SD优化')
136
+
137
+ with gr.Tab('文本生成'):
138
+ with gr.Row():
139
+ input_text = gr.Textbox(lines=6, label='你的想法', placeholder='在此输入内容...')
140
+ translate_output = gr.Textbox(lines=6, label='翻译结果(Prompt输入)')
141
+
142
+ generate_prompter_output = gr.Textbox(lines=6, label='SD优化的 Prompt')
143
+
144
+ output = gr.Textbox(lines=6, label='瞎编的 Prompt')
145
+ output_zh = gr.Textbox(lines=6, label='瞎编的 Prompt(zh)')
146
+ with gr.Row():
147
+ translate_btn = gr.Button('翻译')
148
+ generate_prompter_btn = gr.Button('SD优化')
149
+ gpt_btn = gr.Button('瞎编')
150
+ with gr.Tab('参数设置'):
151
+ with gr.Accordion('SD优化参数', open=True):
152
+ max_new_tokens = gr.Slider(1, 512, 100, label='max_new_tokens', step=1)
153
+ nub_beams = gr.Slider(1, 30, 6, label='num_beams', step=1)
154
+ num_return_sequences = gr.Slider(1, 30, 6, label='num_return_sequences', step=1)
155
+ length_penalty = gr.Slider(-1.0, 1.0, -1.0, label='length_penalty')
156
+ with gr.Accordion('BLIP参数', open=True):
157
+ blip_max_length = gr.Slider(1, 512, 100, label='max_length', step=1)
158
+ with gr.Accordion('CLIP参数', open=True):
159
+ clip_mode_type = gr.Radio(['best', 'classic', 'fast', 'negative'], value='best', label='mode_type')
160
+ clip_model_name = gr.Radio(['vit_h_14', 'vit_l_14', ], value='vit_h_14', )
161
+ with gr.Accordion('WD14参数', open=True):
162
+ image2text_model = gr.Radio(
163
+ [
164
+ "SwinV2",
165
+ "ConvNext",
166
+ "ConvNextV2",
167
+ "ViT",
168
+ ],
169
+ value="ConvNextV2",
170
+ label="Model"
171
+ )
172
+ general_threshold = gr.Slider(
173
+ 0,
174
+ 1,
175
+ step=0.05,
176
+ value=0.35,
177
+ label="General Tags Threshold",
178
+ )
179
+ character_threshold = gr.Slider(
180
+ 0,
181
+ 1,
182
+ step=0.05,
183
+ value=0.85,
184
+ label="Character Tags Threshold",
185
+ )
186
+ img_prompter_btn.click(
187
+ fn=image_generate_prompter,
188
+ inputs=[output_blip_or_clip, output_w14, max_new_tokens, nub_beams, num_return_sequences, length_penalty],
189
+ outputs=images_generate_prompter_output,
190
+ )
191
+ translate_btn.click(
192
+ fn=translate_zh2en,
193
+ inputs=input_text,
194
+ outputs=translate_output
195
+ )
196
+ generate_prompter_btn.click(
197
+ fn=generate_prompter,
198
+ inputs=[translate_output, max_new_tokens, nub_beams, num_return_sequences, length_penalty],
199
+ outputs=generate_prompter_output
200
+ )
201
+ gpt_btn.click(
202
+ fn=text_generate,
203
+ inputs=translate_output,
204
+ outputs=[output, output_zh]
205
+ )
206
+ img_w14_btn.click(
207
+ fn=w14_image2text,
208
+ inputs=[input_image, image2text_model, general_threshold, character_threshold],
209
+ outputs=[
210
+ output_w14,
211
+ w14_raw_output,
212
+ w14_booru_output,
213
+ w14_rating_output,
214
+ w14_characters_output,
215
+ w14_tags_output
216
+ ]
217
+ )
218
+
219
+ img_blip_btn.click(
220
+ fn=git_image2text,
221
+ inputs=[input_image, blip_max_length],
222
+ outputs=output_blip_or_clip
223
+ )
224
+ img_clip_btn.click(
225
+ fn=clip_image2text,
226
+ inputs=[input_image, clip_mode_type, clip_model_name],
227
+ outputs=output_blip_or_clip
228
+ )
229
+
230
+ img_exif_btn.click(
231
+ fn=get_image_info,
232
+ inputs=input_image,
233
+ outputs=exif_info
234
+ )
235
+ block.queue(max_size=64).launch(show_api=False, enable_queue=True, debug=True, share=False, server_name='0.0.0.0')
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers==4.27.4
2
+ sentencepiece==0.1.97
3
+ sacremoses==0.0.53
4
+ clip-interrogator==0.6.0
5
+ torch==2.0.0
6
+ gradio==3.24.1