-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
278 lines (232 loc) · 11.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import os, io, requests, time, json
from typing import List
import google.generativeai as genai
import gradio as gr
from PIL import Image
HUGGING_FACE_API_KEY=""
GOOGLE_API_KEY = ""
MAX_PROMPT_TOKENS = 80
chat_engine = None
chat = None
config_dict = {}
latested_llm_model = None
#gemini safety settings
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_ONLY_HIGH"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_ONLY_HIGH"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_ONLY_HIGH"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_ONLY_HIGH"
},
]
generation_config = {
"temperature": 1,
"top_p": 0.95,
"top_k": 0,
"max_output_tokens": 2048
}
#chat llm models
llm_model_names = [
]
#diffusion models
diffusion_model_names = [
"stabilityai/stable-diffusion-xl-base-1.0",
"stablediffusionapi/toonyou",
"stablediffusionapi/real-cartoon-3d",
"stablediffusionapi/realcartoon3d",
"stablediffusionapi/disney-pixar-cartoon",
"stablediffusionapi/pastel-mix-stylized-anime",
"stablediffusionapi/anything-v5",
"nitrosocke/Ghibli-Diffusion",
"jinaai/flat-2d-animerge",
"Lykon/DreamShaper",
"SG161222/Realistic_Vision_V6.0_B1_noVAE",
]
def list_llm_models() -> List[str]:
if len(llm_model_names) == 0:
if GOOGLE_API_KEY:
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
llm_model_names.append(m.name.split('models/')[1])
llm_models = list(llm_model_names)
return sorted(sorted(llm_models, key=lambda t: t[1]), key=lambda t: t[0], reverse=False)
def list_diffusion_models() -> List[str]:
models = list(diffusion_model_names)
return sorted(sorted(models, key=lambda t: t[1]), key=lambda t: t[0], reverse=False)
def load_config():
global HUGGING_FACE_API_KEY, GOOGLE_API_KEY, MAX_PROMPT_TOKENS, config_dict, generation_config
if os.path.exists("./config.json"):
with open("./config.json", "r", encoding="utf8") as file:
config = file.read()
config_dict = json.loads(config)
HUGGING_FACE_API_KEY = config_dict["huggingface_api_key"]
GOOGLE_API_KEY = config_dict["google_api_key"]
MAX_PROMPT_TOKENS = config_dict["max_prompt_tokens"]
generation_config["temperature"] = config_dict["temperature"]
generation_config["top_p"] = config_dict["top_p"]
generation_config["top_k"] = config_dict["top_k"]
generation_config["max_output_tokens"] = config_dict["max_output_tokens"]
return [*config_dict.values()]
def save_config(*args):
global config_dict
values_dict = zip(config_dict.keys(), args)
config_dict_values = dict(values_dict)
google_api_key = GOOGLE_API_KEY
status=""
try:
with open('./config.json', 'w') as f:
json.dump(config_dict_values, f,indent=2)
load_config()
if not google_api_key:
initialize_chat_engine()
except:
status = "<center><h3 style='color: #E74C3C;'>There was an error saving the settings!</h3></center>"
pass
return gr.Tabs(selected=0), status, gr.Dropdown(list_llm_models())
def initialize_chat_engine():
global chat_engine
genai.configure(api_key=GOOGLE_API_KEY)
def initialize_bot(llm_model):
global chat, chat_engine, latested_llm_model
chat_engine = genai.GenerativeModel(llm_model, safety_settings=safety_settings, generation_config=generation_config)
chat = chat_engine.start_chat(history=[])
latested_llm_model = llm_model
def clean_prompt(prompt:str):
prompt = prompt.replace("\n\n*","").strip()
prompt = prompt.replace("English: ","")
prompt = prompt.replace("* ","")
return prompt
def request(model, prompt):
headers = {"Authorization": f"Bearer {HUGGING_FACE_API_KEY}"}
API_URL = f"https://api-inference.huggingface.co/models/{model}"
status=""
im = None
try:
def query(payload):
response = requests.post(API_URL, headers=headers, json=payload)
return response
data = query({"inputs": prompt,
"negative_prompt":"(lowres, low quality, worst quality:1.2), (text:1.2), watermark, (frame:1.2), deformed, ugly, deformed eyes, blur, out of focus, blurry, deformed cat, deformed, photo, anthropomorphic cat, monochrome, photo, pet collar, gun, weapon, blue, 3d, drones, drone, buildings in background, green, duplicated"})
im = Image.open(io.BytesIO(data.content))
except:
status="<center><h3 style='color: #E74C3C;'>Oops! There was an error generating your response, please try again!</h3><center>"
pass
return im, status
def predict(message, chat_history, llm_model, diffusion_model):
status=""
generated_prompt=""
if not message:
status="<center><h3 style='color: #E74C3C;'>You need to ask me something!</h3><center>"
return "", None, None, status, generated_prompt
if not HUGGING_FACE_API_KEY or not GOOGLE_API_KEY:
status="<center><h3 style='color: #E74C3C;'>You need to set the API keys in the 'Settings' tab before proceeding!</h3></center>"
return "", None, None, status, generated_prompt
if chat_engine is None or latested_llm_model != llm_model:
initialize_bot(llm_model)
image = None
if "/imagine" in message: #Generate image command
msg = message.split('/imagine')[1].strip()
text_question=f"You are creating a prompt for Stable Diffusion to generate an image. Please generate a text prompt for {msg}. Respond only with the prompt itself in the English language, but beautify it as needed, but keep it below {MAX_PROMPT_TOKENS} tokens"
try:
response = chat.send_message(f"{text_question} {msg}.")
response.resolve()
response_text = response.text.split('\n\n')
except:
status="<center><h3 style='color: #E74C3C;'>Oops! There was an error generating your response, please try again!</h3><center>"
pass
return "", None, None, status, generated_prompt
english_prompt_index = 0
if len(response_text) == 0:
status="<center><h3 style='color: #E74C3C;'>Oops! There was an error generating your response, please try again!</h3><center>"
return "", None, None, status, generated_prompt
english_prompt = clean_prompt(response_text[english_prompt_index].strip())
bot_message = f"I imagined that: '{english_prompt}'"
generated_prompt=f"<center><h3 style='color: #2E86C1;'>{english_prompt}</h3><center>"
image, status = request(diffusion_model, english_prompt)
if image:
image = [image]
else:
response = chat.send_message(message)
response.resolve()
bot_message = response.text
chat_history.append((message, bot_message))
time.sleep(2)
return "", chat_history, image, status, generated_prompt
# Initialize configuration
load_config()
if GOOGLE_API_KEY:
initialize_chat_engine()
# Description
title = r"""
<h1 align="center">Gemini-To-Diffusion: Text-to-Image Generation</h1>
"""
description = r"""
<b>Official 🤗 Gradio demo</b> for <a href='https://github.com/DEVAIEXP/gemini-to-diffusion'><b>Text-to-Image Generation</b></a>.<br>
How to use:<br>
1. Configure your <b>Google API</b> key and your <b>Huggingface API</b> key in the 'Settings' tab.
2. Ask what you want to visualize in the Question field, with the command <b>/imagine</b> before the question.
3. Click <b>Submit</b>.
"""
about = r"""
---
📝 **About this project**
<br>
This project was developed for the <b>Artificial Intelligence Immersion 2nd Edition</b> event promoted by Alura in partnership with Google. Gemini-to-Diffusion aims to make it easier to create prompts for imaging stable diffusion models. The user simply needs to ask Gemini in the chat what they want to generate in the image and Gemini will take care of generating a sophisticated prompt for stable diffusion inference. The image is generated in real time, making it possible to download it as a file. To generate the image, the application will send the prompt via REST API to a diffusion model hosted on the <a href=https://huggingface.co/>HuggingFace</a> platform.
📧 **Contact**
<br>
If you have any questions or suggestions, feel free to send your question to <b>[email protected]</b>.
"""
css = """
footer {visibility: hidden},
.gradio-container {width: 85% !important}
"""
block = gr.Blocks(theme="soft", css=css)
with block:
# description
gr.Markdown(title)
gr.Markdown(description)
with gr.Tabs() as tabs:
with gr.TabItem("Chat", id=0):
with gr.Row(equal_height=True):
with gr.Column():
chatbot = gr.Chatbot()
msg = gr.Textbox(label="Question", value="/imagine ", placeholder="You can ask me what I need to generate, example: /imagine a cat")
llm_model = gr.Dropdown(list_llm_models(), value="gemini-1.5-pro-latest", label='Chat model')
diffusion_model = gr.Dropdown(list_diffusion_models(), value="stabilityai/stable-diffusion-xl-base-1.0", label='Image model')
with gr.Column(scale=1):
gallery = gr.Gallery(label="Generated Image", columns=1, rows=1, height=640, interactive=False,format="png")
generated_prompt = gr.HTML(elem_id="generated_tatus", value="")
status = gr.HTML(elem_id="status", value="")
with gr.Row():
submit_btn = gr.Button(value="🔎Submit")
clear = gr.ClearButton([msg, chatbot, gallery, generated_prompt, status], value="🔁Clear")
msg.submit(predict, [msg, chatbot, llm_model, diffusion_model], [msg, chatbot, gallery, status, generated_prompt])
submit_btn.click(predict, [msg, chatbot, llm_model, diffusion_model], [msg, chatbot, gallery, status, generated_prompt])
with gr.TabItem("Settings", id=1) as TabConfig:
with gr.Row():
with gr.Column():
google_api_key = gr.Textbox(label="Google API Key", placeholder="Enter your API-Key here")
huggingface_api_key = gr.Textbox(label="Huggingface API Key", placeholder="Enter your API-Key here")
with gr.Column():
temperature = gr.Slider(minimum=0.0, maximum=1.0, value=0.5, step=0.1, interactive=True, label="Temperature")
top_p = gr.Slider(minimum=0.0, maximum=1.0, value=0.9, step=0.1, interactive=True, label="Top P")
top_k = gr.Slider(minimum=0.0, maximum=1.0, value=1, step=0.1, interactive=True, label="Top K")
max_prompt_tokens = gr.Slider(minimum=0, maximum=2048, value=80, step=20, interactive=True, label="Max output prompt tokens")
max_output_tokens = gr.Slider(minimum=0, maximum=8192, value=2048, step=64, interactive=True, label="Max output tokens")
save_btn = gr.Button(value="💾Save")
save_input_elements = [google_api_key, huggingface_api_key, temperature, top_p, top_k, max_prompt_tokens, max_output_tokens]
save_btn.click(save_config,inputs=[*save_input_elements], outputs=[tabs, status, llm_model])
# Set configuration inputs
TabConfig.select(load_config, outputs=[*save_input_elements])
gr.Markdown(about)
block.launch(inbrowser=True, share=True)