Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,195 @@
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
if model != 'DALL-E 3 XL':
|
92 |
+
prompt = GoogleTranslator(source=language, target='en').translate(prompt)
|
93 |
+
print(f'\033[1mГенерация {key} перевод:\033[0m {prompt}')
|
94 |
+
|
95 |
+
prompt = f"{prompt} | ultra detail, ultra elaboration, ultra quality, perfect."
|
96 |
+
print(f'\033[1mГенерация {key}:\033[0m {prompt}')
|
97 |
+
API_URL = mmodels[model]
|
98 |
+
if model == 'Animagine XL 2.0':
|
99 |
+
prompt = f"Anime. {prompt}"
|
100 |
+
if model == 'Anime Detailer XL':
|
101 |
+
prompt = f"Anime. {prompt}"
|
102 |
+
if model == 'Disney':
|
103 |
+
prompt = f"Disney style. {prompt}"
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
|
108 |
+
payload = {
|
109 |
+
"inputs": prompt,
|
110 |
+
"is_negative": is_negative,
|
111 |
+
"steps": steps,
|
112 |
+
"cfg_scale": cfg_scale,
|
113 |
+
"seed": seed if seed != -1 else random.randint(1, 1000000000),
|
114 |
+
"strength": strength,
|
115 |
+
"width": width,
|
116 |
+
"height": height,
|
117 |
+
"guidance_scale": cfg_scale,
|
118 |
+
"num_inference_steps": steps,
|
119 |
+
"resolution": f"{width} x {height}",
|
120 |
+
"negative_prompt": is_negative
|
121 |
+
}
|
122 |
+
|
123 |
+
response = requests.post(f"{api_base}{API_URL}", headers=headers, json=payload, timeout=timeout)
|
124 |
+
if response.status_code != 200:
|
125 |
+
print(f"Ошибка: Не удалось получить изображение. Статус ответа: {response.status_code}")
|
126 |
+
print(f"Содержимое ответа: {response.text}")
|
127 |
+
if response.status_code == 503:
|
128 |
+
raise gr.Error(f"{response.status_code} : The model is being loaded")
|
129 |
+
return None
|
130 |
+
raise gr.Error(f"{response.status_code}")
|
131 |
+
return None
|
132 |
+
|
133 |
+
try:
|
134 |
+
image_bytes = response.content
|
135 |
+
image = Image.open(io.BytesIO(image_bytes))
|
136 |
+
print(f'\033[1mГенерация {key} завершена!\033[0m ({prompt})')
|
137 |
+
return image
|
138 |
+
except Exception as e:
|
139 |
+
print(f"Ошибка при попытке открыть изображение: {e}")
|
140 |
+
return None
|
141 |
+
|
142 |
+
css = """
|
143 |
+
* {}
|
144 |
+
footer {visibility: hidden !important;}
|
145 |
+
"""
|
146 |
+
|
147 |
+
with gr.Blocks(css=css) as dalle:
|
148 |
+
with gr.Tab("Базовые настройки"):
|
149 |
+
with gr.Row():
|
150 |
+
with gr.Column(elem_id="prompt-container"):
|
151 |
+
with gr.Row():
|
152 |
+
text_prompt = gr.Textbox(label="Prompt", placeholder="Описание изображения", lines=3, elem_id="prompt-text-input")
|
153 |
+
with gr.Row():
|
154 |
+
model = gr.Radio(label="Модель", value="DALL-E 3 XL", choices=list(mmodels.keys()))
|
155 |
+
|
156 |
+
|
157 |
+
|
158 |
+
with gr.Tab("Расширенные настройки"):
|
159 |
+
with gr.Row():
|
160 |
+
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")
|
161 |
+
with gr.Row():
|
162 |
+
steps = gr.Slider(label="Sampling steps", value=35, minimum=1, maximum=100, step=1)
|
163 |
+
with gr.Row():
|
164 |
+
cfg = gr.Slider(label="CFG Scale", value=7, minimum=1, maximum=20, step=1)
|
165 |
+
with gr.Row():
|
166 |
+
method = gr.Radio(label="Sampling method", value="DPM++ 2M Karras", choices=["DPM++ 2M Karras", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "DDIM"])
|
167 |
+
with gr.Row():
|
168 |
+
strength = gr.Slider(label="Strength", value=0.7, minimum=0, maximum=1, step=0.001)
|
169 |
+
with gr.Row():
|
170 |
+
seed = gr.Slider(label="Seed", value=-1, minimum=-1, maximum=1000000000, step=1)
|
171 |
+
with gr.Row():
|
172 |
+
gpt = gr.Checkbox(label="ChatGPT")
|
173 |
+
|
174 |
+
with gr.Tab("Beta"):
|
175 |
+
with gr.Row():
|
176 |
+
width = gr.Slider(label="Ширина", minimum=15, maximum=2000, value=1024, step=1)
|
177 |
+
height = gr.Slider(label="Высота", minimum=15, maximum=2000, value=1024, step=1)
|
178 |
+
|
179 |
+
with gr.Tab("Информация"):
|
180 |
+
with gr.Row():
|
181 |
+
gr.Textbox(label="Шаблон prompt", value="{prompt} | ultra detail, ultra elaboration, ultra quality, perfect.")
|
182 |
+
with gr.Row():
|
183 |
+
with gr.Column():
|
184 |
+
gr.HTML("""<button class="lg secondary svelte-cmf5ev" onclick="window.open('http://ai-hub.rf.gd', '_blank');">AI-HUB</button>""")
|
185 |
+
gr.HTML("""<button class="lg secondary svelte-cmf5ev" onclick="window.open('http://yufi.rf.gd', '_blank');">YUFI</button>""")
|
186 |
+
|
187 |
+
|
188 |
+
with gr.Row():
|
189 |
+
text_button = gr.Button("Генерация", variant='primary', elem_id="gen-button")
|
190 |
+
with gr.Row():
|
191 |
+
image_output = gr.Image(type="pil", label="Изображение", elem_id="gallery")
|
192 |
+
|
193 |
+
text_button.click(query, inputs=[text_prompt, model, negative_prompt, steps, cfg, method, seed, strength, gpt, width, height], outputs=image_output)
|
194 |
+
|
195 |
+
dalle.launch(show_api=False, share=False)
|