File size: 10,520 Bytes
3c7025e 2401ce9 3c7025e de87bdc a5515e4 de87bdc a5515e4 ecbcd62 a5515e4 de87bdc a5515e4 ecbcd62 a5515e4 ecbcd62 e692727 3c7025e ecbcd62 2401ce9 ecbcd62 2401ce9 ecbcd62 2401ce9 ecbcd62 2401ce9 3c7025e 1367e6b 3c7025e e692727 de87bdc e692727 7f1bd15 a5515e4 3c7025e ecbcd62 297482a 7f1bd15 a5515e4 3c7025e de87bdc 3c7025e 7f1bd15 a5515e4 297482a de87bdc 7f1bd15 2401ce9 a5515e4 7f1bd15 3c7025e 1367e6b 297482a 3c7025e 3691b33 3c7025e e692727 3c7025e 2401ce9 ecbcd62 297482a 1367e6b 297482a 3c7025e 297482a 3c7025e 297482a 1367e6b 297482a 1367e6b 297482a e692727 3c7025e 2401ce9 3c7025e 297482a 3c7025e e692727 3c7025e 2401ce9 3c7025e 297482a 3c7025e e692727 297482a e692727 297482a 3c7025e e692727 297482a e692727 297482a 3c7025e e692727 3c7025e d808b5b 297482a 1367e6b d808b5b 3c7025e 39d4ddb 3c7025e e692727 3c7025e 39d4ddb 297482a 39d4ddb 3c7025e 297482a 3c7025e e692727 39d4ddb 297482a 39d4ddb 3c7025e 2401ce9 a5515e4 7f1bd15 297482a 3c7025e 2401ce9 3c7025e |
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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 |
import os
from datetime import datetime
import streamlit as st
from lib import config, preset, txt2img_generate
# The token name is the service in lower_snake_case
SERVICE_SESSION = {
"Black Forest Labs": "api_key_black_forest_labs",
"Fal": "api_key_fal",
"Hugging Face": "api_key_hugging_face",
"Together": "api_key_together",
}
SESSION_TOKEN = {
"api_key_black_forest_labs": os.environ.get("BFL_API_KEY") or None,
"api_key_fal": os.environ.get("FAL_KEY") or None,
"api_key_hugging_face": os.environ.get("HF_TOKEN") or None,
"api_key_together": os.environ.get("TOGETHER_API_KEY") or None,
}
# TODO: group by service so we can have models with the same name
# Model IDs in lib/config.py
PRESET_MODEL = {
# bfl
"flux-pro-1.1": preset.txt2img.flux_1_1_pro_bfl,
"flux-pro": preset.txt2img.flux_pro_bfl,
"flux-dev": preset.txt2img.flux_dev_bfl,
# fal
"fal-ai/aura-flow": preset.txt2img.aura_flow,
"fal-ai/flux/dev": preset.txt2img.flux_dev_fal,
"fal-ai/flux/schnell": preset.txt2img.flux_schnell_fal,
"fal-ai/flux-pro": preset.txt2img.flux_pro_fal,
"fal-ai/flux-pro/v1.1": preset.txt2img.flux_1_1_pro_fal,
"fal-ai/fooocus": preset.txt2img.fooocus,
"fal-ai/kolors": preset.txt2img.kolors,
"fal-ai/stable-diffusion-v3-medium": preset.txt2img.stable_diffusion_3,
# hf
"black-forest-labs/flux.1-dev": preset.txt2img.flux_dev_hf,
"black-forest-labs/flux.1-schnell": preset.txt2img.flux_schnell_hf,
"stabilityai/stable-diffusion-xl-base-1.0": preset.txt2img.stable_diffusion_xl,
# together
"black-forest-labs/FLUX.1-schnell-Free": preset.txt2img.flux_schnell_free_together,
}
st.set_page_config(
page_title=f"{config.title} | Text to Image",
page_icon=config.icon,
layout=config.layout,
)
# Initialize Streamlit session state
if "api_key_black_forest_labs" not in st.session_state:
st.session_state.api_key_black_forest_labs = ""
if "api_key_fal" not in st.session_state:
st.session_state.api_key_fal = ""
if "api_key_hugging_face" not in st.session_state:
st.session_state.api_key_hugging_face = ""
if "api_key_together" not in st.session_state:
st.session_state.api_key_together = ""
if "running" not in st.session_state:
st.session_state.running = False
if "txt2img_messages" not in st.session_state:
st.session_state.txt2img_messages = []
if "txt2img_seed" not in st.session_state:
st.session_state.txt2img_seed = 0
st.logo("logo.png")
st.sidebar.header("Settings")
service = st.sidebar.selectbox(
"Service",
options=list(SERVICE_SESSION.keys()),
disabled=st.session_state.running,
index=2, # Hugging Face
)
# Show the API key input for the selected service.
# Disable and hide value if set by environment variable; handle empty string value later.
for display_name, session_key in SERVICE_SESSION.items():
if service == display_name:
st.session_state[session_key] = st.sidebar.text_input(
"API Key",
type="password",
value="" if SESSION_TOKEN[session_key] else st.session_state[session_key],
disabled=bool(SESSION_TOKEN[session_key]) or st.session_state.running,
help="Set by environment variable" if SESSION_TOKEN[session_key] else "Cleared on page refresh",
)
model = st.sidebar.selectbox(
"Model",
options=config.txt2img.models[service],
index=config.txt2img.default_model[service],
disabled=st.session_state.running,
)
# heading
st.html("""
<h1>Text to Image</h1>
<p>Generate an image from a text prompt.</p>
""")
# Build parameters from preset by rendering the appropriate input widgets
parameters = {}
preset = PRESET_MODEL[model]
for param in preset.parameters:
if param == "model":
parameters[param] = model
if param == "seed":
parameters[param] = st.sidebar.number_input(
"Seed",
min_value=-1,
max_value=(1 << 53) - 1,
value=-1,
disabled=st.session_state.running,
)
if param == "negative_prompt":
parameters[param] = st.sidebar.text_area(
"Negative Prompt",
value=config.txt2img.negative_prompt,
disabled=st.session_state.running,
)
if param == "width":
parameters[param] = st.sidebar.slider(
"Width",
step=64,
value=1024,
min_value=512,
max_value=2048,
disabled=st.session_state.running,
)
if param == "height":
parameters[param] = st.sidebar.slider(
"Height",
step=64,
value=1024,
min_value=512,
max_value=2048,
disabled=st.session_state.running,
)
if param == "image_size":
parameters[param] = st.sidebar.select_slider(
"Image Size",
options=config.txt2img.image_sizes,
value=config.txt2img.default_image_size,
disabled=st.session_state.running,
)
if param == "aspect_ratio":
parameters[param] = st.sidebar.select_slider(
"Aspect Ratio",
options=config.txt2img.aspect_ratios,
value=config.txt2img.default_aspect_ratio,
disabled=st.session_state.running,
)
if param in ["guidance_scale", "guidance"]:
parameters[param] = st.sidebar.slider(
"Guidance Scale",
preset.guidance_scale_min,
preset.guidance_scale_max,
preset.guidance_scale,
0.1,
disabled=st.session_state.running,
)
if param in ["num_inference_steps", "steps"]:
parameters[param] = st.sidebar.slider(
"Inference Steps",
preset.num_inference_steps_min,
preset.num_inference_steps_max,
preset.num_inference_steps,
1,
disabled=st.session_state.running,
)
if param in ["expand_prompt", "prompt_expansion"]:
parameters[param] = st.sidebar.checkbox(
"Prompt Expansion",
value=False,
disabled=st.session_state.running,
)
if param == "prompt_upsampling":
parameters[param] = st.sidebar.checkbox(
"Prompt Upsampling",
value=False,
disabled=st.session_state.running,
)
# Wrap the prompt in an accordion to display additional parameters
for message in st.session_state.txt2img_messages:
role = message["role"]
with st.chat_message(role):
image_container = st.empty()
with image_container.container():
if role == "user":
with st.expander(message["content"]):
# build a markdown string for additional parameters
st.html("""
<style>
div[data-testid="stMarkdownContainer"] p:not(:last-of-type) { margin-bottom: 0 }
</style>
""")
filtered_parameters = [
f"`{k}`: {v}"
for k, v in message["parameters"].items()
if k not in config.txt2img.hidden_parameters
]
st.markdown(f"`model`: {message['model']}\n\n" + "\n\n".join(filtered_parameters))
if role == "assistant":
# image is full width when _not_ in full-screen mode
st.html("""
<style>
div[data-testid="stImage"]:has(img[style*="max-width: 100%"]) {
height: auto;
max-width: 512px;
}
div[data-testid="stImage"] img[style*="max-width: 100%"] {
border-radius: 8px;
}
</style>
""")
st.write(message["content"]) # success will be image, error will be text
# Buttons for deleting last generation or clearing all generations
if st.session_state.txt2img_messages:
button_container = st.empty()
with button_container.container():
# https://discuss.streamlit.io/t/st-button-in-one-line/25966/6
st.html("""
<style>
div[data-testid="column"] {
width: fit-content;
min-width: 0;
flex: none;
}
</style>
""")
col1, col2 = st.columns(2)
with col1:
if (
st.button("β", help="Delete last generation", disabled=st.session_state.running)
and len(st.session_state.txt2img_messages) >= 2
):
st.session_state.txt2img_messages.pop()
st.session_state.txt2img_messages.pop()
st.rerun()
with col2:
if st.button("ποΈ", help="Clear all generations", disabled=st.session_state.running):
st.session_state.txt2img_messages = []
st.session_state.txt2img_seed = 0
st.rerun()
else:
button_container = None
# Set running state to True and show spinner while loading.
# Update state and refresh on response; errors will be displayed as chat messages.
if prompt := st.chat_input(
"What do you want to see?",
on_submit=lambda: setattr(st.session_state, "running", True),
):
if "seed" in parameters and parameters["seed"] >= 0:
st.session_state.txt2img_seed = parameters["seed"]
else:
st.session_state.txt2img_seed = int(datetime.now().timestamp() * 1e6) % (1 << 53)
if "seed" in parameters:
parameters["seed"] = st.session_state.txt2img_seed
if button_container:
button_container.empty()
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
with st.spinner("Running..."):
if preset.kwargs:
parameters.update(preset.kwargs)
session_key = f"api_key_{service.lower().replace(' ', '_')}"
api_key = st.session_state[session_key] or SESSION_TOKEN[session_key]
image = txt2img_generate(api_key, service, model, prompt, parameters)
st.session_state.running = False
st.session_state.txt2img_messages.append(
{"role": "user", "content": prompt, "parameters": parameters, "model": PRESET_MODEL[model].name}
)
st.session_state.txt2img_messages.append({"role": "assistant", "content": image})
st.rerun()
|