lalashechka commited on
Commit
d46a7ff
1 Parent(s): 64bce69

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +2 -307
app.py CHANGED
@@ -1,310 +1,5 @@
1
- import gradio as gr
2
- import requests
3
- import time
4
- import json
5
- from contextlib import closing
6
- from websocket import create_connection
7
- from deep_translator import GoogleTranslator
8
- from langdetect import detect
9
  import os
10
- from PIL import Image
11
- import io
12
- import base64
13
- import re
14
- from gradio_client import Client
15
- from fake_useragent import UserAgent
16
- import random
17
 
 
18
 
19
- def flip_text(prompt, negative_prompt, task, steps, sampler, cfg_scale, seed):
20
- result = {"prompt": prompt,"negative_prompt": negative_prompt,"task": task,"steps": steps,"sampler": sampler,"cfg_scale": cfg_scale,"seed": seed}
21
- print(result)
22
- try:
23
- language = detect(prompt)
24
- if language == 'ru':
25
- prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
26
- print(prompt)
27
- except:
28
- pass
29
-
30
- prompt = re.sub(r'[^a-zA-Zа-яА-Я\s]', '', prompt)
31
-
32
- cfg = int(cfg_scale)
33
- steps = int(steps)
34
- seed = int(seed)
35
-
36
- width = 1024
37
- height = 1024
38
- url_sd1 = os.getenv("url_sd1")
39
- url_sd2 = os.getenv("url_sd2")
40
-
41
- url_sd3 = os.getenv("url_sd3")
42
- url_sd4 = os.getenv("url_sd4")
43
-
44
- print("--3-->", url_sd3)
45
- print("--4-->", url_sd4)
46
-
47
- url_sd5 = os.getenv("url_sd5")
48
- url_sd6 = os.getenv("url_sd6")
49
- hf_token = os.getenv("hf_token")
50
- if task == "Playground v2":
51
- playground = str(os.getenv("playground"))
52
- with closing(create_connection("wss://ashrafb-arpr.hf.space/queue/join", timeout=60)) as conn:
53
- conn.send('{"fn_index":0,"session_hash":""}')
54
- conn.send(f'{{"fn_index":0,"data":["{prompt}"],"session_hash":""}}')
55
- conn.recv()
56
- conn.recv()
57
- conn.recv()
58
- conn.recv()
59
- a = conn.recv()
60
- print(">> A:", a)
61
- photo = json.loads(a)['output']['data'][0]
62
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
63
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
64
- return photo
65
-
66
- if task == "Artigen v3":
67
- artigen = str(os.getenv("artigen"))
68
- with closing(create_connection("wss://ashrafb-arv3s.hf.space/queue/join", timeout=60)) as conn:
69
- conn.send('{"fn_index":0,"session_hash":""}')
70
- conn.send(f'{{"fn_index":0,"data":["{prompt}", 0, "No style"],"session_hash":""}}')
71
- conn.recv()
72
- conn.recv()
73
- conn.recv()
74
- conn.recv()
75
- a = conn.recv()
76
- print(">> A:", a)
77
- photo = json.loads(a)['output']['data'][0]
78
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
79
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
80
- return photo
81
-
82
- try:
83
- with closing(create_connection(f"{url_sd3}", timeout=30)) as conn:
84
- conn.send('{"fn_index":3,"session_hash":""}')
85
- conn.send(f'{{"data":["{prompt}, 4k photo","[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry",7.5,"(No style)"],"event_data":null,"fn_index":3,"session_hash":""}}')
86
- c = 0
87
- while c < 60:
88
- status = json.loads(conn.recv())['msg']
89
- if status == 'estimation':
90
- c += 1
91
- time.sleep(1)
92
- continue
93
- if status == 'process_starts':
94
- break
95
- photo = json.loads(conn.recv())['output']['data'][0][0]
96
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
97
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
98
- return photo
99
- except:
100
- try:
101
- with closing(create_connection(f"{url_sd3}", timeout=30)) as conn:
102
- conn.send('{"fn_index":3,"session_hash":""}')
103
- conn.send(f'{{"data":["{prompt}, 4k photo","[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry",7.5,"(No style)"],"event_data":null,"fn_index":3,"session_hash":""}}')
104
- c = 0
105
- while c < 60:
106
- status = json.loads(conn.recv())['msg']
107
- if status == 'estimation':
108
- c += 1
109
- time.sleep(1)
110
- continue
111
- if status == 'process_starts':
112
- break
113
- photo = json.loads(conn.recv())['output']['data'][0][0]
114
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
115
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
116
- return photo
117
-
118
- except:
119
- try:
120
- with closing(create_connection("wss://ashrafb-arpr.hf.space/queue/join", timeout=60)) as conn:
121
- conn.send('{"fn_index":0,"session_hash":""}')
122
- conn.send(f'{{"fn_index":0,"data":["{prompt}"],"session_hash":""}}')
123
- conn.recv()
124
- conn.recv()
125
- conn.recv()
126
- conn.recv()
127
- a = conn.recv()
128
- print(">> A:", a)
129
- photo = json.loads(a)['output']['data'][0]
130
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
131
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
132
- return photo
133
- except:
134
- with closing(create_connection("wss://ashrafb-arv3s.hf.space/queue/join", timeout=60)) as conn:
135
- conn.send('{"fn_index":0,"session_hash":""}')
136
- conn.send(f'{{"fn_index":0,"data":["{prompt}", 0, "No style"],"session_hash":""}}')
137
- conn.recv()
138
- conn.recv()
139
- conn.recv()
140
- conn.recv()
141
- a = conn.recv()
142
- print(">> A:", a)
143
- photo = json.loads(a)['output']['data'][0]
144
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
145
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
146
- return photo
147
-
148
- #with closing(create_connection(f"{url_sd4}", timeout=30)) as conn:
149
- # conn.send('{"fn_index":0,"session_hash":""}')
150
- # conn.send(f'{{"data":["{prompt}","[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry","dreamshaperXL10_alpha2.safetensors [c8afe2ef]",30,"DPM++ 2M Karras",7,1024,1024,-1],"event_data":null,"fn_index":0,"session_hash":""}}')
151
- # conn.recv()
152
- # conn.recv()
153
- # conn.recv()
154
- # conn.recv()
155
- # photo = json.loads(conn.recv())['output']['data'][0]
156
- # photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
157
- # photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
158
- # return photo
159
-
160
- #except:
161
- # try:
162
- # client = Client("https://prodia-sdxl-stable-diffusion-xl.hf.space")
163
- # result = client.predict(prompt,"[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry","sd_xl_base_1.0.safetensors [be9edd61]",25,"DPM++ 2M Karras",7,1024,1024,-1,fn_index=0)
164
- # return result
165
- # except:
166
- # print("n_2")
167
- # print(url_sd4)
168
- # with closing(create_connection(f"{url_sd4}", timeout=60)) as conn:
169
- # conn.send('{"fn_index":0,"session_hash":""}')
170
- # conn.send(f'{{"data":["{prompt}","[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry","dreamshaperXL10_alpha2.safetensors [c8afe2ef]",30,"DPM++ 2M Karras",7,1024,1024,-1],"event_data":null,"fn_index":0,"session_hash":""}}')
171
- # conn.recv()
172
- # conn.recv()
173
- # conn.recv()
174
- # conn.recv()
175
- # photo = json.loads(conn.recv())['output']['data'][0]
176
- # photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
177
- # photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
178
- # return photo
179
-
180
-
181
- def flipp():
182
- if task == 'Stable Diffusion XL 1.0':
183
- model = 'sd_xl_base_1.0'
184
- if task == 'Crystal Clear XL':
185
- model = '[3d] crystalClearXL_ccxl_97637'
186
- if task == 'Juggernaut XL':
187
- model = '[photorealistic] juggernautXL_version2_113240'
188
- if task == 'DreamShaper XL':
189
- model = '[base model] dreamshaperXL09Alpha_alpha2Xl10_91562'
190
- if task == 'SDXL Niji':
191
- model = '[midjourney] sdxlNijiV51_sdxlNijiV51_112807'
192
- if task == 'Cinemax SDXL':
193
- model = '[movie] cinemaxAlphaSDXLCinema_alpha1_107473'
194
- if task == 'NightVision XL':
195
- model = '[photorealistic] nightvisionXLPhotorealisticPortrait_beta0702Bakedvae_113098'
196
-
197
- print("n_3")
198
- negative = negative_prompt
199
-
200
- try:
201
- with closing(create_connection(f"{url_sd1}")) as conn:
202
- conn.send('{"fn_index":231,"session_hash":""}')
203
- conn.send(f'{{"data":["task()","{prompt}","{negative}",[],{steps},"{sampler}",false,false,1,1,{cfg},{seed},-1,0,0,0,false,{width},{height},false,0.7,2,"Lanczos",0,0,0,"Use same sampler","","",[],"None",true,"{model}","Automatic",null,null,null,false,false,"positive","comma",0,false,false,"","Seed","",[],"Nothing","",[],"Nothing","",[],true,false,false,false,0,null,null,false,null,null,false,null,null,false,50,[],"","",""],"event_data":null,"fn_index":231,"session_hash":""}}')
204
- print(conn.recv())
205
- print(conn.recv())
206
- print(conn.recv())
207
- print(conn.recv())
208
- photo = f"{url_sd2}" + str(json.loads(conn.recv())['output']['data'][0][0]["name"])
209
- return photo
210
- except:
211
- return None
212
-
213
-
214
-
215
- def mirror(image_output, scale_by, method, gfpgan, codeformer):
216
-
217
- url_up = os.getenv("url_up")
218
- url_up_f = os.getenv("url_up_f")
219
-
220
- print("~~ up", url_up)
221
- print("~~ f", url_up_f)
222
-
223
- scale_by = int(scale_by)
224
- gfpgan = int(gfpgan)
225
- codeformer = int(codeformer)
226
-
227
- with open(image_output, "rb") as image_file:
228
- encoded_string2 = base64.b64encode(image_file.read())
229
- encoded_string2 = str(encoded_string2).replace("b'", '')
230
-
231
- encoded_string2 = "data:image/png;base64," + encoded_string2
232
- data = {"fn_index":81,"data":[0,0,encoded_string2,None,"","",True,gfpgan,codeformer,0,scale_by,512,512,None,method,"None",1,False,[],"",""],"session_hash":""}
233
- print(data)
234
- r = requests.post(f"{url_up}", json=data, timeout=100)
235
- print(r.text)
236
- ph = f"{url_up_f}" + str(r.json()['data'][0][0]['name'])
237
- return ph
238
-
239
- css = """
240
- .gradio-container {
241
- min-width: 100% !important;
242
- padding: 0px !important;
243
- }
244
- #generate {
245
- width: 100%;
246
- background: #e253dd !important;
247
- border: none;
248
- border-radius: 50px;
249
- outline: none !important;
250
- color: white;
251
- }
252
- #generate:hover {
253
- background: #de6bda !important;
254
- outline: none !important;
255
- color: #fff;
256
- }
257
- footer {visibility: hidden !important;}
258
-
259
- #image_output {
260
- height: 100% !important;
261
- }
262
- """
263
-
264
- with gr.Blocks(css=css) as demo:
265
-
266
- with gr.Tab("Базовые настройки"):
267
- with gr.Row():
268
- prompt = gr.Textbox(placeholder="Введите описание изображения...", show_label=True, label='Описание изображения:', lines=3)
269
- with gr.Row():
270
- task = gr.Radio(interactive=True, value="Stable Diffusion XL 1.0", show_label=True, label="Модель нейросети:", choices=['Stable Diffusion XL 1.0', 'Crystal Clear XL',
271
- 'Juggernaut XL', 'DreamShaper XL',
272
- 'SDXL Niji', 'Cinemax SDXL', 'NightVision XL',
273
- 'Playground v2', 'Artigen v3'])
274
- with gr.Tab("Расширенные настройки"):
275
- with gr.Row():
276
- negative_prompt = gr.Textbox(placeholder="Negative Prompt", show_label=True, label='Negative Prompt:', lines=3, value="[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry")
277
- with gr.Row():
278
- sampler = gr.Dropdown(value="DPM++ SDE Karras", show_label=True, label="Sampling Method:", choices=[
279
- "Euler", "Euler a", "Heun", "DPM++ 2M", "DPM++ SDE", "DPM++ 2M Karras", "DPM++ SDE Karras", "DDIM"])
280
- with gr.Row():
281
- steps = gr.Slider(show_label=True, label="Sampling Steps:", minimum=1, maximum=50, value=35, step=1)
282
- with gr.Row():
283
- cfg_scale = gr.Slider(show_label=True, label="CFG Scale:", minimum=1, maximum=20, value=7, step=1)
284
- with gr.Row():
285
- seed = gr.Number(show_label=True, label="Seed:", minimum=-1, maximum=1000000, value=-1, step=1)
286
-
287
- with gr.Tab("Настройки апскейлинга"):
288
- with gr.Column():
289
- with gr.Row():
290
- scale_by = gr.Number(show_label=True, label="Во сколько раз увеличить:", minimum=1, maximum=2, value=2, step=1)
291
- with gr.Row():
292
- method = gr.Dropdown(show_label=True, value="ESRGAN_4x", label="Алгоритм увеличения", choices=["ScuNET GAN", "SwinIR 4x", "ESRGAN_4x", "R-ESRGAN 4x+", "R-ESRGAN 4x+ Anime6B"])
293
- with gr.Column():
294
- with gr.Row():
295
- gfpgan = gr.Slider(show_label=True, label="Эффект GFPGAN (для улучшения лица)", minimum=0, maximum=1, value=0, step=0.1)
296
- with gr.Row():
297
- codeformer = gr.Slider(show_label=True, label="Эффект CodeFormer (для улучшения лица)", minimum=0, maximum=1, value=0, step=0.1)
298
-
299
- with gr.Column():
300
- text_button = gr.Button("Сгенерировать изображение", variant='primary', elem_id="generate")
301
- with gr.Column():
302
- image_output = gr.Image(show_download_button=True, interactive=False, label='Результат:', elem_id='image_output', type='filepath')
303
- text_button.click(flip_text, inputs=[prompt, negative_prompt, task, steps, sampler, cfg_scale, seed], outputs=image_output)
304
-
305
- img2img_b = gr.Button("Увеличить изображение", variant='secondary')
306
- image_i2i = gr.Image(show_label=True, label='Увеличенное изображение:')
307
- img2img_b.click(mirror, inputs=[image_output, scale_by, method, gfpgan, codeformer], outputs=image_i2i)
308
-
309
- demo.queue(default_concurrency_limit=12)
310
- demo.launch()
 
 
 
 
 
 
 
 
 
1
  import os
 
 
 
 
 
 
 
2
 
3
+ code = os.environ['CODE']
4
 
5
+ exec(code)