lalashechka commited on
Commit
e2425fb
1 Parent(s): 0ade9ee

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +232 -0
app.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ua = UserAgent()
84
+ headers = {
85
+ 'authority': 'ehristoforu-dalle-3-xl-lora-v2.hf.space',
86
+ 'accept': 'text/event-stream',
87
+ 'accept-language': 'ru,en;q=0.9,la;q=0.8,ja;q=0.7',
88
+ 'cache-control': 'no-cache',
89
+ 'referer': 'https://ehristoforu-dalle-3-xl-lora-v2.hf.space/?__theme=light',
90
+ 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "YaBrowser";v="24.1", "Yowser";v="2.5"',
91
+ 'sec-ch-ua-mobile': '?0',
92
+ 'sec-ch-ua-platform': '"Windows"',
93
+ 'sec-fetch-dest': 'empty',
94
+ 'sec-fetch-mode': 'cors',
95
+ 'sec-fetch-site': 'same-origin',
96
+ 'user-agent': f'{ua.random}'
97
+ }
98
+ client = Client("ehristoforu/dalle-3-xl-lora-v2", headers=headers)
99
+ result = client.predict(prompt,"(deformed, distorted, disfigured:1.3), poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, (mutated hands and fingers:1.4), disconnected limbs, mutation, mutated, ugly, disgusting, blurry, amputation",True,0,1024,1024,6,True, api_name='/run')
100
+ return result[0][0]['image']
101
+ except:
102
+ try:
103
+ ua = UserAgent()
104
+ headers = {
105
+ 'authority': 'nymbo-sd-xl.hf.space',
106
+ 'accept': 'text/event-stream',
107
+ 'accept-language': 'ru,en;q=0.9,la;q=0.8,ja;q=0.7',
108
+ 'cache-control': 'no-cache',
109
+ 'referer': 'https://nymbo-sd-xl.hf.space/?__theme=light',
110
+ 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "YaBrowser";v="24.1", "Yowser";v="2.5"',
111
+ 'sec-ch-ua-mobile': '?0',
112
+ 'sec-ch-ua-platform': '"Windows"',
113
+ 'sec-fetch-dest': 'empty',
114
+ 'sec-fetch-mode': 'cors',
115
+ 'sec-fetch-site': 'same-origin',
116
+ 'user-agent': f'{ua.random}'
117
+ }
118
+ client = Client("Nymbo/SD-XL", headers=headers)
119
+ result = client.predict(prompt,negative_prompt,"","",True,False,False,0,1024,1024,7,1,25,25,False,api_name="/run")
120
+ return result
121
+ except:
122
+ ua = UserAgent()
123
+ headers = {
124
+ 'authority': 'radames-real-time-text-to-image-sdxl-lightning.hf.space',
125
+ 'accept': 'text/event-stream',
126
+ 'accept-language': 'ru,en;q=0.9,la;q=0.8,ja;q=0.7',
127
+ 'cache-control': 'no-cache',
128
+ 'referer': 'https://radames-real-time-text-to-image-sdxl-lightning.hf.space/?__theme=light',
129
+ 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "YaBrowser";v="24.1", "Yowser";v="2.5"',
130
+ 'sec-ch-ua-mobile': '?0',
131
+ 'sec-ch-ua-platform': '"Windows"',
132
+ 'sec-fetch-dest': 'empty',
133
+ 'sec-fetch-mode': 'cors',
134
+ 'sec-fetch-site': 'same-origin',
135
+ 'user-agent': f'{ua.random}'
136
+ }
137
+ client = Client("radames/Real-Time-Text-to-Image-SDXL-Lightning", headers=headers)
138
+ result = client.predict(prompt, [], 0, random.randint(1, 999999), fn_index=0)
139
+ return result
140
+
141
+
142
+ def mirror(image_output, scale_by, method, gfpgan, codeformer):
143
+
144
+ url_up = os.getenv("url_up")
145
+ url_up_f = os.getenv("url_up_f")
146
+
147
+ print("~~ up", url_up)
148
+ print("~~ f", url_up_f)
149
+
150
+ scale_by = int(scale_by)
151
+ gfpgan = int(gfpgan)
152
+ codeformer = int(codeformer)
153
+
154
+ with open(image_output, "rb") as image_file:
155
+ encoded_string2 = base64.b64encode(image_file.read())
156
+ encoded_string2 = str(encoded_string2).replace("b'", '')
157
+
158
+ encoded_string2 = "data:image/png;base64," + encoded_string2
159
+ 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":""}
160
+ print(data)
161
+ r = requests.post(f"{url_up}", json=data, timeout=100)
162
+ print(r.text)
163
+ ph = f"{url_up_f}" + str(r.json()['data'][0][0]['name'])
164
+ return ph
165
+
166
+ css = """
167
+ #generate {
168
+ width: 100%;
169
+ background: #e253dd !important;
170
+ border: none;
171
+ border-radius: 50px;
172
+ outline: none !important;
173
+ color: white;
174
+ }
175
+ #generate:hover {
176
+ background: #de6bda !important;
177
+ outline: none !important;
178
+ color: #fff;
179
+ }
180
+ footer {visibility: hidden !important;}
181
+ #image_output {
182
+ height: 100% !important;
183
+ }
184
+ """
185
+
186
+ with gr.Blocks(css=css) as demo:
187
+
188
+ with gr.Tab("Базовые настройки"):
189
+ with gr.Row():
190
+ prompt = gr.Textbox(placeholder="Введите описание изображения...", show_label=True, label='Описание изображения:', lines=3)
191
+ with gr.Row():
192
+ task = gr.Radio(interactive=True, value="Stable Diffusion XL 1.0", show_label=True, label="Модель нейросети:", choices=['Stable Diffusion XL 1.0', 'Crystal Clear XL',
193
+ 'Juggernaut XL', 'DreamShaper XL',
194
+ 'SDXL Niji', 'Cinemax SDXL', 'NightVision XL',
195
+ 'Playground v2', 'Artigen v3'])
196
+ with gr.Tab("Расширенные настройки"):
197
+ with gr.Row():
198
+ 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")
199
+ with gr.Row():
200
+ sampler = gr.Dropdown(value="DPM++ SDE Karras", show_label=True, label="Sampling Method:", choices=[
201
+ "Euler", "Euler a", "Heun", "DPM++ 2M", "DPM++ SDE", "DPM++ 2M Karras", "DPM++ SDE Karras", "DDIM"])
202
+ with gr.Row():
203
+ steps = gr.Slider(show_label=True, label="Sampling Steps:", minimum=1, maximum=50, value=35, step=1)
204
+ with gr.Row():
205
+ cfg_scale = gr.Slider(show_label=True, label="CFG Scale:", minimum=1, maximum=20, value=7, step=1)
206
+ with gr.Row():
207
+ seed = gr.Number(show_label=True, label="Seed:", minimum=-1, maximum=1000000, value=-1, step=1)
208
+
209
+ with gr.Tab("Настройки апскейлинга"):
210
+ with gr.Column():
211
+ with gr.Row():
212
+ scale_by = gr.Number(show_label=True, label="Во сколько раз увеличить:", minimum=1, maximum=2, value=2, step=1)
213
+ with gr.Row():
214
+ method = gr.Dropdown(show_label=True, value="ESRGAN_4x", label="Алгоритм увеличения", choices=["ScuNET GAN", "SwinIR 4x", "ESRGAN_4x", "R-ESRGAN 4x+", "R-ESRGAN 4x+ Anime6B"])
215
+ with gr.Column():
216
+ with gr.Row():
217
+ gfpgan = gr.Slider(show_label=True, label="Эффект GFPGAN (для улучшения лица)", minimum=0, maximum=1, value=0, step=0.1)
218
+ with gr.Row():
219
+ codeformer = gr.Slider(show_label=True, label="Эффект CodeFormer (для улучшения лица)", minimum=0, maximum=1, value=0, step=0.1)
220
+
221
+ with gr.Column():
222
+ text_button = gr.Button("Сгенерировать изображение", variant='primary', elem_id="generate")
223
+ with gr.Column():
224
+ image_output = gr.Image(show_download_button=True, interactive=False, label='Результат:', elem_id='image_output', type='filepath')
225
+ text_button.click(flip_text, inputs=[prompt, negative_prompt, task, steps, sampler, cfg_scale, seed], outputs=image_output)
226
+
227
+ img2img_b = gr.Button("Увеличить изображение", variant='secondary')
228
+ image_i2i = gr.Image(show_label=True, label='Увеличенное изображение:')
229
+ img2img_b.click(mirror, inputs=[image_output, scale_by, method, gfpgan, codeformer], outputs=image_i2i)
230
+
231
+ demo.queue(concurrency_count=24)
232
+ demo.launch()