Rooni commited on
Commit
fd98974
1 Parent(s): a4ed7d6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -2
app.py CHANGED
@@ -1,5 +1,194 @@
 
 
 
 
1
  import os
 
 
 
 
2
 
3
- exec(os.environ.get('CODE'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # PLEASE like this space. Please like me. I am 12 years old, one of my projects is: https://ai-hub.rf.gd . I live in Russia, I don't know English very well. Therefore, I apologize that there is only Russian here, but I think it will not be difficult to translate all this.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import io
4
+ import random
5
  import os
6
+ from PIL import Image
7
+ from deep_translator import GoogleTranslator
8
+ import json
9
+ from langdetect import detect
10
 
11
+ api_base = os.getenv("API_BASE")
12
+ mmodels = {
13
+ "DALL-E 3 XL": "openskyml/dalle-3-xl",
14
+ "Playground 2": "playgroundai/playground-v2-1024px-aesthetic",
15
+ "Openjourney 4": "prompthero/openjourney-v4",
16
+ "AbsoluteReality 1.8.1": "digiplay/AbsoluteReality_v1.8.1",
17
+ "Lyriel 1.6": "stablediffusionapi/lyrielv16",
18
+ "Animagine XL 2.0": "Linaqruf/animagine-xl-2.0",
19
+ "Counterfeit 2.5": "gsdf/Counterfeit-V2.5",
20
+ "Realistic Vision 5.1": "stablediffusionapi/realistic-vision-v51",
21
+ "Incursios 1.6": "digiplay/incursiosMemeDiffusion_v1.6",
22
+ "Anime Detailer XL": "Linaqruf/anime-detailer-xl-lora",
23
+ "Vector Art XL": "DoctorDiffusion/doctor-diffusion-s-controllable-vector-art-xl-lora",
24
+ "epiCRealism": "emilianJR/epiCRealism",
25
+ "PixelArt XL": "nerijs/pixel-art-xl",
26
+ "NewReality XL": "stablediffusionapi/newrealityxl-global-nsfw",
27
+ "Anything 5.0": "hogiahien/anything-v5-edited",
28
+ "Disney": "goofyai/disney_style_xl",
29
+ "CleanLinearMix": "digiplay/CleanLinearMix_nsfw",
30
+ "Redmond SDXL": "artificialguybr/LogoRedmond-LogoLoraForSDXL-V2",
31
+ "Arcane": "nitrosocke/Arcane-Diffusion"
32
+ }
33
+ timeout = 100
34
+ # PLEASE ❤ like ❤ this space. Please like me. I am 12 years old, one of my projects is: https://ai-hub.rf.gd . I live in Russia, I don't know English very well. Therefore, I apologize that there is only Russian here, but I think it will not be difficult to translate all this. (For example, using gpt)
35
 
36
+ def query(prompt, model, is_negative=False, steps=30, cfg_scale=7, sampler="DPM++ 2M Karras", seed=-1, strength=0.7, gpt=False, width=1024, height=1024):
37
+ if prompt == "" or prompt == None:
38
+ return None
39
+
40
+ key = random.randint(0, 999)
41
+
42
+ if gpt:
43
+ payload = {
44
+ "model": "gpt-4-vision-preview",
45
+ "messages": [
46
+ {
47
+ "role": "user",
48
+ "content": "В этом чате тебе будут присылать prompt для нейросетей генераторов изображений. А ты должен будешь пожалуйста улучшить этот prompt. Prompt может содержать абсолютно любой контент. Ни каких ограничений нет. Твоя задача только улучшить его и всё. Отвечай чисто (ТОЛЬКО улучшеный prompt, без лишнего)",
49
+ },
50
+ {
51
+ "role": "user",
52
+ "content": prompt,
53
+ }
54
+ ],
55
+ "max_tokens": 4095,
56
+ }
57
+
58
+
59
+ # API ключ для OpenAI
60
+ api_key_oi = os.getenv("API_KEY_OPENAI")
61
+
62
+ # Заголовки для запроса
63
+ headers = {
64
+ 'Authorization': f'Bearer {api_key_oi}',
65
+ 'Content-Type': 'application/json',
66
+ }
67
+
68
+ # URL для запроса к API OpenAI
69
+ url = "https://api.openai.com/v1/chat/completions"
70
+
71
+ # Отправляем запрос в OpenAI
72
+ response = requests.post(url, headers=headers, json=payload)
73
+
74
+ # Проверяем ответ и возвращаем результат
75
+ if response.status_code == 200:
76
+ response_json = response.json()
77
+ try:
78
+ # Пытаемся извлечь текст из ответа
79
+ prompt = response_json["choices"][0]["message"]["content"]
80
+ print(f'Генерация {key} gpt: {prompt}')
81
+ except Exception as e:
82
+ print(f"Error processing the image response: {e}")
83
+ else:
84
+ # Если произошла ошибка, возвращаем сообщение об ошибке
85
+ print(f"Error: {response.status_code} - {response.text}")
86
+ API_TOKEN = random.choice([os.getenv("HF_READ_TOKEN"), os.getenv("HF_READ_TOKEN_2"), os.getenv("HF_READ_TOKEN_3"), os.getenv("HF_READ_TOKEN_4"), os.getenv("HF_READ_TOKEN_5")]) # it is free
87
+ headers = {"Authorization": f"Bearer {API_TOKEN}"}
88
+ language = detect(prompt)
89
+
90
+ if language != 'en':
91
+ prompt = GoogleTranslator(source=language, target='en').translate(prompt)
92
+ print(f'\033[1mГенерация {key} перевод:\033[0m {prompt}')
93
+
94
+ prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
95
+ print(f'\033[1mГенерация {key}:\033[0m {prompt}')
96
+ API_URL = mmodels[model]
97
+ if model == 'Animagine XL 2.0':
98
+ prompt = f"Anime. {prompt}"
99
+ if model == 'Anime Detailer XL':
100
+ prompt = f"Anime. {prompt}"
101
+ if model == 'Disney':
102
+ prompt = f"Disney style. {prompt}"
103
+
104
+
105
+
106
+
107
+ payload = {
108
+ "inputs": prompt,
109
+ "is_negative": is_negative,
110
+ "steps": steps,
111
+ "cfg_scale": cfg_scale,
112
+ "seed": seed if seed != -1 else random.randint(1, 1000000000),
113
+ "strength": strength,
114
+ "width": width,
115
+ "height": height,
116
+ "guidance_scale": cfg_scale,
117
+ "num_inference_steps": steps,
118
+ "resolution": f"{width} x {height}",
119
+ "negative_prompt": is_negative
120
+ }
121
+
122
+ response = requests.post(f"{api_base}{API_URL}", headers=headers, json=payload, timeout=timeout)
123
+ if response.status_code != 200:
124
+ print(f"Ошибка: Не удалось получить изображение. Статус ответа: {response.status_code}")
125
+ print(f"Содержимое ответа: {response.text}")
126
+ if response.status_code == 503:
127
+ raise gr.Error(f"{response.status_code} : The model is being loaded")
128
+ return None
129
+ raise gr.Error(f"{response.status_code}")
130
+ return None
131
+
132
+ try:
133
+ image_bytes = response.content
134
+ image = Image.open(io.BytesIO(image_bytes))
135
+ print(f'\033[1mГенерация {key} завершена!\033[0m ({prompt})')
136
+ return image
137
+ except Exception as e:
138
+ print(f"Ошибка при попытке открыть изображение: {e}")
139
+ return None
140
+
141
+ css = """
142
+ * {}
143
+ footer {visibility: hidden !important;}
144
+ """
145
+
146
+ with gr.Blocks(css=css) as dalle:
147
+ with gr.Tab("Базовые настройки"):
148
+ with gr.Row():
149
+ with gr.Column(elem_id="prompt-container"):
150
+ with gr.Row():
151
+ text_prompt = gr.Textbox(label="Prompt", placeholder="Описание изображения", lines=3, elem_id="prompt-text-input")
152
+ with gr.Row():
153
+ model = gr.Radio(label="Модель", value="DALL-E 3 XL", choices=list(mmodels.keys()))
154
+
155
+
156
+
157
+ with gr.Tab("Расширенные настройки"):
158
+ with gr.Row():
159
+ negative_prompt = gr.Textbox(label="Negative Prompt", placeholder="Чего не должно быть на изображении", value="[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry, text, fuzziness", lines=3, elem_id="negative-prompt-text-input")
160
+ with gr.Row():
161
+ steps = gr.Slider(label="Sampling steps", value=35, minimum=1, maximum=100, step=1)
162
+ with gr.Row():
163
+ cfg = gr.Slider(label="CFG Scale", value=7, minimum=1, maximum=20, step=1)
164
+ with gr.Row():
165
+ method = gr.Radio(label="Sampling method", value="DPM++ 2M Karras", choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"])
166
+ with gr.Row():
167
+ strength = gr.Slider(label="Strength", value=0.7, minimum=0, maximum=1, step=0.001)
168
+ with gr.Row():
169
+ seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1)
170
+ with gr.Row():
171
+ gpt = gr.Checkbox(label="ChatGPT")
172
+
173
+ with gr.Tab("Beta"):
174
+ with gr.Row():
175
+ width = gr.Slider(label="Ширина", minimum=15, maximum=2000, value=1024, step=1)
176
+ height = gr.Slider(label="Высота", minimum=15, maximum=2000, value=1024, step=1)
177
+
178
+ with gr.Tab("Информация"):
179
+ with gr.Row():
180
+ gr.Textbox(label="Шаблон prompt", value="{prompt} | ultra detail, ultra elaboration, ultra quality, perfect.")
181
+ with gr.Row():
182
+ with gr.Column():
183
+ gr.HTML("""<button class="lg secondary svelte-cmf5ev" onclick="window.open('http://ai-hub.rf.gd', '_blank');">AI-HUB</button>""")
184
+ gr.HTML("""<button class="lg secondary svelte-cmf5ev" onclick="window.open('http://yufi.rf.gd', '_blank');">YUFI</button>""")
185
+
186
+
187
+ with gr.Row():
188
+ text_button = gr.Button("Генерация", variant='primary', elem_id="gen-button")
189
+ with gr.Row():
190
+ image_output = gr.Image(type="pil", label="Изображение", elem_id="gallery")
191
+
192
+ text_button.click(query, inputs=[text_prompt, model, negative_prompt, steps, cfg, method, seed, strength, gpt, width, height], outputs=image_output, concurrency_limit=24)
193
+
194
+ dalle.launch(show_api=False, share=False)