DigiP-AI commited on
Commit
8487701
·
verified ·
1 Parent(s): 5fed634

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -316
app.py CHANGED
@@ -1,322 +1,63 @@
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
- from io import BytesIO
13
- import base64
14
- import re
15
- from mistralai import Mistral
16
- from gradio_client import Client
17
- from fake_useragent import UserAgent
18
- import random
19
- from theme import theme
20
- from fastapi import FastAPI
21
 
22
- app = FastAPI()
23
-
24
- api_key = os.getenv("MISTRAL_API_KEY")
25
- Mistralclient = Mistral(api_key=api_key)
26
-
27
- def encode_image(image_path):
28
- """Encode the image to base64."""
29
- try:
30
- # Open the image file
31
- image = Image.open(image_path).convert("RGB")
32
-
33
- # Resize the image to a height of 512 while maintaining the aspect ratio
34
- base_height = 512
35
- h_percent = (base_height / float(image.size[1]))
36
- w_size = int((float(image.size[0]) * float(h_percent)))
37
- image = image.resize((w_size, base_height), Image.LANCZOS)
38
-
39
- # Convert the image to a byte stream
40
- buffered = BytesIO()
41
- image.save(buffered, format="JPEG")
42
- img_str = base64.b64encode(buffered.getvalue()).decode("utf-8")
43
-
44
- return img_str
45
- except FileNotFoundError:
46
- print(f"Error: The file {image_path} was not found.")
47
- return None
48
- except Exception as e: # Add generic exception handling
49
- print(f"Error: {e}")
50
- return None
51
-
52
- def feifeichat(image):
53
- try:
54
- model = "pixtral-large-2411"
55
- # Define the messages for the chat
56
- base64_image = encode_image(image)
57
- messages = [{
58
- "role":
59
- "user",
60
- "content": [
61
- {
62
- "type": "text",
63
- "text": "Please provide a detailed description of this photo"
64
- },
65
- {
66
- "type": "image_url",
67
- "image_url": f"data:image/jpeg;base64,{base64_image}"
68
- },
69
- ],
70
- "stream": False,
71
- }]
72
 
73
- partial_message = ""
74
- for chunk in Mistralclient.chat.stream(model=model, messages=messages):
75
- if chunk.data.choices[0].delta.content is not None:
76
- partial_message = partial_message + chunk.data.choices[
77
- 0].delta.content
78
- yield partial_message
79
- except Exception as e: # 添加通用异常处理
80
- print(f"Error: {e}")
81
- return "Please upload a photo"
82
 
83
-
84
- def query(prompt, negative_prompt, task, steps, sampler, cfg_scale, seed, width, height):
85
- result = {"prompt": prompt,"negative_prompt": negative_prompt,"task": task,"steps": steps,"sampler": sampler,"cfg_scale": cfg_scale,"seed": seed, "width": width, "height": height}
86
- print(result)
87
- try:
88
- language = detect(prompt)
89
- if language == 'ru':
90
- prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
91
- print(prompt)
92
- except:
93
- pass
94
-
95
- prompt = re.sub(r'[^a-zA-Zа-яА-Я\s]', '', prompt)
96
 
97
- cfg = int(cfg_scale)
98
- steps = int(steps)
99
- seed = int(seed)
100
-
101
- width = 896
102
- height = 1152
103
-
104
- if task == "Playground v2":
105
- ua = UserAgent()
106
- headers = {
107
- 'user-agent': f'{ua.random}'
108
- }
109
- client = Client("https://ashrafb-arpr.hf.space/", headers=headers)
110
- result = client.predict(prompt, fn_index=0)
111
- return result
112
-
113
- if task == "Artigen v3":
114
- ua = UserAgent()
115
- headers = {
116
- 'user-agent': f'{ua.random}'
117
- }
118
- client = Client("https://ashrafb-arv3s.hf.space/", headers=headers)
119
- result = client.predict(prompt,0,"Cinematic", fn_index=0)
120
- return result
121
- try:
122
- with closing(create_connection("wss://google-sdxl.hf.space/queue/join")) as conn:
123
- conn.send('{"fn_index":3,"session_hash":""}')
124
- 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":""}}')
125
- c = 0
126
- while c < 60:
127
- status = json.loads(conn.recv())['msg']
128
- if status == 'estimation':
129
- c += 1
130
- time.sleep(1)
131
- continue
132
- if status == 'process_starts':
133
- break
134
- photo = json.loads(conn.recv())['output']['data'][0][0]
135
- photo = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
136
- photo = Image.open(io.BytesIO(base64.decodebytes(bytes(photo, "utf-8"))))
137
- return photo
138
- except:
139
- try:
140
- ua = UserAgent()
141
- headers = {
142
- 'authority': 'ehristoforu-dalle-3-xl-lora-v2.hf.space',
143
- 'accept': 'text/event-stream',
144
- 'accept-language': 'ru,en;q=0.9,la;q=0.8,ja;q=0.7',
145
- 'cache-control': 'no-cache',
146
- 'referer': 'https://ehristoforu-dalle-3-xl-lora-v2.hf.space/?__theme=light',
147
- 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "YaBrowser";v="24.1", "Yowser";v="2.5"',
148
- 'sec-ch-ua-mobile': '?0',
149
- 'sec-ch-ua-platform': '"Windows"',
150
- 'sec-fetch-dest': 'empty',
151
- 'sec-fetch-mode': 'cors',
152
- 'sec-fetch-site': 'same-origin',
153
- 'user-agent': f'{ua.random}'
154
- }
155
- client = Client("ehristoforu/dalle-3-xl-lora-v2", headers=headers)
156
- 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')
157
- return result[0][0]['image']
158
- except:
159
- try:
160
- ua = UserAgent()
161
- headers = {
162
- 'authority': 'nymbo-sd-xl.hf.space',
163
- 'accept': 'text/event-stream',
164
- 'accept-language': 'ru,en;q=0.9,la;q=0.8,ja;q=0.7',
165
- 'cache-control': 'no-cache',
166
- 'referer': 'https://nymbo-sd-xl.hf.space/?__theme=light',
167
- 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "YaBrowser";v="24.1", "Yowser";v="2.5"',
168
- 'sec-ch-ua-mobile': '?0',
169
- 'sec-ch-ua-platform': '"Windows"',
170
- 'sec-fetch-dest': 'empty',
171
- 'sec-fetch-mode': 'cors',
172
- 'sec-fetch-site': 'same-origin',
173
- 'user-agent': f'{ua.random}'
174
- }
175
- client = Client("Nymbo/SD-XL", headers=headers)
176
- result = client.predict(prompt,negative_prompt,"","",True,False,False,0,896,1152,7,1,25,25,False,api_name="/run")
177
- return result
178
- except:
179
- try:
180
- ua = UserAgent()
181
- headers = {
182
- 'authority': 'radames-real-time-text-to-image-sdxl-lightning.hf.space',
183
- 'accept': 'text/event-stream',
184
- 'accept-language': 'ru,en;q=0.9,la;q=0.8,ja;q=0.7',
185
- 'cache-control': 'no-cache',
186
- 'referer': 'https://radames-real-time-text-to-image-sdxl-lightning.hf.space/?__theme=light',
187
- 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "YaBrowser";v="24.1", "Yowser";v="2.5"',
188
- 'sec-ch-ua-mobile': '?0',
189
- 'sec-ch-ua-platform': '"Windows"',
190
- 'sec-fetch-dest': 'empty',
191
- 'sec-fetch-mode': 'cors',
192
- 'sec-fetch-site': 'same-origin',
193
- 'user-agent': f'{ua.random}'
194
- }
195
- client = Client("radames/Real-Time-Text-to-Image-SDXL-Lightning", headers=headers)
196
- result = client.predict(prompt, [], 0, random.randint(1, 999999), fn_index=0)
197
- return result
198
- except:
199
- try:
200
- ua = UserAgent()
201
- headers = {
202
- 'user-agent': f'{ua.random}'
203
- }
204
- client = Client("https://ashrafb-arpr.hf.space/", headers=headers)
205
- result = client.predict(prompt, fn_index=0)
206
- return result
207
- except:
208
- ua = UserAgent()
209
- headers = {
210
- 'user-agent': f'{ua.random}'
211
- }
212
- client = Client("https://ashrafb-arv3s.hf.space/", headers=headers)
213
- result = client.predict(prompt,0,"Cinematic", fn_index=0)
214
- return result
215
-
216
-
217
-
218
- def mirror(image_output, scale_by, method, gfpgan, codeformer):
219
-
220
- url_up = "https://darkstorm2150-protogen-web-ui.hf.space/run/predict/"
221
- url_up_f = "https://darkstorm2150-protogen-web-ui.hf.space/file="
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,896,1152,None,method,"None",1,False,[],"",""],"session_hash":""}
233
- r = requests.post(url_up, json=data, timeout=100)
234
- print(r.text)
235
- print(r.json()['data'][0][0]['name'])
236
- ph = "https://darkstorm2150-protogen-web-ui.hf.space/file=" + str(r.json()['data'][0][0]['name'])
237
- print(ph)
238
- response2 = requests.get(ph)
239
- img = Image.open(BytesIO(response2.content))
240
- return img
241
-
242
- css = """
243
- .gradio-container {background-color: MediumAquaMarine}
244
- footer{display:none !important}
245
- #generate {
246
- width: 100%;
247
- }
248
- #image_output {
249
- height: 100% !important;
250
- }
251
- """
252
-
253
- with gr.Blocks(css=css, theme=theme) as app:
254
- with gr.Tab(label="Image To Prompt"):
255
- with gr.Row():
256
- with gr.Column(scale=4, min_width=300):
257
- input_img = gr.Image(label="Input Picture", type="filepath")
258
- with gr.Column(scale=3):
259
- output_text = gr.Textbox(label="Prompt", lines=2, scale=6, show_copy_button = True)
260
- submit_btn = gr.Button(value="Generate Pompt", scale=4, variant='primary')
261
- clear_prompt =gr.Button("Clear 🗑️",variant="primary", elem_id="clear_button")
262
- clear_prompt.click(lambda: (None, None), None, [input_img, output_text], queue=False, show_api=False)
263
-
264
- submit_btn.click(feifeichat, [input_img], [output_text])
265
-
266
- with gr.Tab("Basic Settings"):
267
- with gr.Column(scale=3):
268
- with gr.Row():
269
- prompt = gr.Textbox(placeholder="Enter the image description...", show_label=True, label='Image Prompt ✍️', lines=3, show_copy_button = True)
270
- with gr.Row():
271
- task = gr.Radio(interactive=True, value="Stable Diffusion XL 1.0", show_label=True, label="Model of neural network ❄️ ", choices=['Stable Diffusion XL 1.0', 'Crystal Clear XL',
272
- 'Juggernaut XL', 'DreamShaper XL',
273
- 'SDXL Niji', 'Cinemax SDXL', 'NightVision XL'])
274
- with gr.Accordion("Advanced Options", open=True):
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++ 2M Karras", show_label=True, label="Sampling Method:", choices=[
279
- "DPM++ 2M Karras", "DPM++ 2S a Karras", "DPM2 a Karras", "DPM2 Karras", "DPM++ SDE Karras", "DEIS", "LMS", "DPM Adaptive", "DPM++ 2M", "DPM2 Ancestral", "DPM++ S", "DPM++ SDE", "DDPM", "DPM Fast", "dpmpp_2s_ancestral", "Euler", "Euler CFG PP", "Euler a", "Euler Ancestral", "Euler+beta", "Heun", "Heun PP2", "DDIM", "LMS Karras", "PLMS", "UniPC", "UniPC BH2"])
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
- with gr.Row():
287
- width = gr.Slider(label="Width", minimum=512, maximum=2048, step=8, value=896, interactive=True,)
288
- with gr.Row():
289
- height = gr.Slider(label="Height", minimum=512, maximum=2048, step=8, value=1152,interactive=True,)
290
- with gr.Column():
291
- with gr.Row():
292
- image_output = gr.Image(show_download_button=True, interactive=False, label='Generated Image 🌄', show_share_button=False, format="png", type="filepath", elem_id="gallery")
293
- text_button = gr.Button("Generate image", variant="primary", interactive=True, elem_id="generate")
294
-
295
- with gr.Tab("Upscaling Settings"):
296
- with gr.Column():
297
- with gr.Row():
298
- scale_by = gr.Number(show_label=True, label="How many times to increase:", minimum=1, maximum=2, value=2, step=1)
299
- with gr.Row():
300
- method = gr.Dropdown(show_label=True, value="ESRGAN_4x", label="Increasing algorithm", choices=["ScuNET GAN", "SwinIR 4x", "ESRGAN_4x", "R-ESRGAN 4x+", "R-ESRGAN 4x+ Anime6B"])
301
- with gr.Column():
302
- with gr.Row():
303
- gfpgan = gr.Slider(show_label=True, label="Effect GFPGAN (For facial improvement)", minimum=0, maximum=1, value=0, step=0.1)
304
- with gr.Row():
305
- codeformer = gr.Slider(show_label=True, label="Effect CodeFormer (Improve the face)", minimum=0, maximum=1, value=0, step=0.1)
306
 
307
-
308
- with gr.Column():
309
- #image_output = gr.Image(show_download_button=True, interactive=False, label='Generated Image 🌄', show_share_button=False, format="png", type="filepath", elem_id="gallery")
310
-
311
- text_button.click(query, inputs=[prompt, negative_prompt, task, steps, sampler, cfg_scale, seed, width, height], outputs=image_output, concurrency_limit=48)
312
- clear_prompt =gr.Button("Clear 🗑️",variant="primary", elem_id="clear_button")
313
- clear_prompt.click(lambda: (None, None), None, [prompt, image_output], queue=False, show_api=False)
314
-
315
- img2img_b = gr.Button("Increase the image", variant='secondary')
316
- image_i2i = gr.Image(show_label=True, label='Increased image:')
317
- img2img_b.click(mirror, inputs=[image_output, scale_by, method, gfpgan, codeformer], outputs=image_i2i, concurrency_limit=48)
318
-
319
-
320
- app.queue(default_concurrency_limit=200, max_size=200) # <-- Sets up a queue with default parameters
321
- if __name__ == "__main__":
322
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ #----------Start of theme----------
4
+ theme = gr.themes.Ocean(
5
+ primary_hue="zinc",
6
+ secondary_hue="slate",
7
+ neutral_hue="neutral",
8
+ font=[gr.themes.GoogleFont('Kavivanar'), gr.themes.GoogleFont('Kavivanar'), 'system-ui', 'sans-serif'],
9
+ font_mono=[gr.themes.GoogleFont('Source Code Pro'), gr.themes.GoogleFont('Inconsolata'), gr.themes.GoogleFont('Inconsolata'), 'monospace'],
10
+ ).set(
11
+ #Body Settings
12
+ body_background_fill='linear-gradient(10deg, *primary_200, *secondary_50)',
13
+ body_text_color='secondary_600',
14
+ body_text_color_subdued='*primary_500',
15
+ body_text_weight='500',
16
+
17
+ #Background Settings
18
+ background_fill_primary='*primary_100',
19
+ background_fill_secondary='*secondary_200',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ color_accent='*primary_300',
 
 
 
 
 
 
 
 
22
 
23
+ #Border Settings
24
+ border_color_accent_subdued='*primary_400',
25
+ border_color_primary='*primary_400',
 
 
 
 
 
 
 
 
 
 
26
 
27
+ #Block Settings
28
+ block_radius='*radius_md',
29
+ block_background_fill='*primary_200',
30
+ block_border_color='*primary_500',
31
+ block_border_width='*panel_border_width',
32
+ block_info_text_color='*primary_700',
33
+ block_info_text_size='*text_md',
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
+ container_radius='*radius_xl',
36
+ panel_background_fill='*primary_200',
37
+ accordion_text_color='*primary_600',
38
+ checkbox_border_radius='*radius_xl',
39
+ #slider_color='*primary_600',
40
+ table_text_color='*primary_600',
41
+ input_background_fill='*primary_50',
42
+ input_background_fill_focus='*primary_100',
43
+
44
+ #Button Settings
45
+ button_border_width='1px',
46
+ button_transform_hover='scale(1.01)',
47
+ button_transition='all 0.1s ease-in-out',
48
+ button_transform_active='Scale(0.9)',
49
+ button_large_radius='*radius_xl',
50
+ button_small_radius='*radius_xl',
51
+ button_primary_border_color='*primary_500',
52
+ button_secondary_border_color='*primary_400',
53
+ button_primary_background_fill_hover='linear-gradient(90deg, *primary_400, *secondary_200, *primary_400)',
54
+ button_primary_background_fill='linear-gradient(90deg,*secondary_300 , *primary_500, *secondary_300)',
55
+ button_primary_text_color='*primary_100',
56
+ button_primary_text_color_hover='*primary_700',
57
+ button_cancel_background_fill='*primary_500',
58
+ button_cancel_background_fill_hover='*primary_400',
59
+
60
+ loader_color="#800000",
61
+ slider_color="#708090"
62
+ )
63
+ #----------End of theme----------