Spaces:
Paused
Paused
File size: 10,746 Bytes
02e7b38 69bfb06 cc9c490 d1fedf7 02e7b38 4a41d50 04ad39b d1fedf7 2733832 3e81d20 2733832 3e81d20 2733832 d0410ae 0a0bb7f d0410ae be085b4 0a0bb7f 02e7b38 3e81d20 57df966 b757958 3e81d20 b757958 57df966 3e81d20 be085b4 3e81d20 57df966 02e7b38 2c6acee 4ccafa7 4dc95a1 9254c71 4dc95a1 3e81d20 9254c71 3e81d20 9254c71 8749f9d 4dc95a1 2733832 d1fedf7 4dc95a1 be085b4 6ba8188 0a0bb7f cc9c490 8acfe48 cc9c490 68ee1c7 8acfe48 be085b4 aa9cf49 3e81d20 6ba8188 3e81d20 da0ae75 cc9c490 4ccafa7 d1fedf7 3e81d20 d1fedf7 3e81d20 8acfe48 3e81d20 d1fedf7 cc9c490 d1fedf7 2733832 9254c71 d1fedf7 be3f21d d1fedf7 be3f21d 4a41d50 9254c71 4a41d50 3e81d20 4a41d50 d1fedf7 be3f21d 02e7b38 d93bc7b 02e7b38 be3f21d 57df966 02e7b38 04ad39b 3e81d20 02e7b38 04ad39b 02e7b38 2733832 04ad39b 0d22050 be3f21d 02e7b38 788a48c 02e7b38 57df966 02e7b38 57df966 02e7b38 4a41d50 3e81d20 4a41d50 2733832 57df966 02e7b38 e3fb325 02e7b38 |
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 |
import base64
import dash
from dash import dcc, html, Input, Output, State
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
import google.generativeai as genai
import requests
import logging
import threading
import time
import os
# Set up logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
# Updated STYLES list
STYLES = [
"photographic", "3d-model", "analog-film", "anime", "cinematic", "comic-book",
"digital-art", "enhance", "fantasy-art", "isometric", "line-art", "low-poly",
"modeling-compound", "neon-punk", "origami", "pixel-art", "tile-texture"
]
# Default negative prompt (hidden from UI)
DEFAULT_NEGATIVE_PROMPT = """
ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame,
extra limbs, disfigured, deformed, body out of frame, bad anatomy, watermark, signature,
cut off, low contrast, underexposed, overexposed, bad art, beginner, amateur, distorted face,
plastic, cartoonish, artificial, fake, unnatural, blurry, smooth, lack of detail, low quality
"""
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = dbc.Container([
html.H1("ImaGen", className="my-4"),
dbc.Row([
# Left column: Form entry
dbc.Col([
dbc.Card([
dbc.CardBody([
dbc.Textarea(id="prompt", placeholder="Enter your prompt", className="mb-3"),
dcc.Dropdown(
id="style",
options=[{"label": s.replace("-", " ").title(), "value": s} for s in STYLES],
value="photographic",
placeholder="Select style",
className="mb-3"
),
dbc.Button("Generate Image", id="submit-btn", color="primary", className="mb-3"),
dbc.Accordion([
dbc.AccordionItem(
[
dbc.Label("Aspect Ratio"),
dcc.Dropdown(
id="aspect-ratio",
options=[
{"label": ar, "value": ar} for ar in
["16:9", "1:1", "21:9", "2:3", "3:2", "4:5", "5:4", "9:16", "9:21"]
],
value="1:1"
),
dbc.Label("Steps"),
dcc.Slider(id="steps", min=4, max=50, step=1, value=30, marks={4: '4', 25: '25', 50: '50'}),
],
title="Advanced Settings",
),
], start_collapsed=True, className="mb-3"),
])
], className="mb-4"),
], width=6),
# Right column: Image preview
dbc.Col([
dbc.Card([
dbc.CardBody([
dcc.Loading(
id="loading",
type="circle",
children=[
html.Div(id="status-message", className="mb-3"),
html.Img(id="image-output", className="img-fluid mb-3"),
html.Div(id="enhanced-prompt-output", className="mb-3"),
dbc.Button("Download Image", id="download-btn", color="secondary", className="mb-3", disabled=True),
dcc.Download(id="download-image")
]
),
])
]),
], width=6),
]),
], fluid=True)
def enhance_prompt(google_api_key, prompt, style):
genai.configure(api_key=google_api_key)
model = genai.GenerativeModel("gemini-2.0-flash-lite")
enhanced_prompt_request = f"""
Task: Enhance the following prompt with details to match the specified style
Style: {style}
Original prompt: '{prompt}'
Instructions:
1. Expand the prompt to be more detailed, vivid, and realistic with camera used and the setting for that camera like ISO etc.
2. Incorporate elements of the specified style.
3. Add details that enhance the scene to the specified style
4. Emphasize natural lighting and enhance the realism of textures and colors based on the specified style.
5. Avoid terms that might result in artificial or cartoonish appearance unless specified by user.
6. Maintain the original intent of the prompt while significantly improving its descriptive quality with details.
7. Provide ONLY the enhanced prompt, without any explanations or options.
8. Keep the enhanced prompt concise, ideally under 100 words.
Enhanced prompt:
"""
try:
response = model.generate_content(enhanced_prompt_request)
enhanced_prompt = response.text.strip()
prefixes_to_remove = ["Enhanced prompt:", "Here's the enhanced prompt:", "The enhanced prompt is:"]
for prefix in prefixes_to_remove:
if enhanced_prompt.lower().startswith(prefix.lower()):
enhanced_prompt = enhanced_prompt[len(prefix):].strip()
logging.info(f"Enhanced prompt: {enhanced_prompt}")
return enhanced_prompt
except Exception as e:
logging.error(f"Error in enhance_prompt: {str(e)}")
raise
def generate_image(stability_api_key, enhanced_prompt, style, negative_prompt, steps, aspect_ratio):
url = "https://api.stability.ai/v2beta/stable-image/generate/sd3"
headers = {
"Accept": "image/*",
"Authorization": f"Bearer {stability_api_key}"
}
data = {
"prompt": f"{enhanced_prompt}, Style: {style}, highly detailed, high quality, descriptive, sharp focus, intricate details",
"negative_prompt": negative_prompt,
"model": "sd3.5-large-turbo",
"output_format": "jpeg",
"num_images": 1,
"steps": steps,
"style_preset": style,
"aspect_ratio": aspect_ratio,
}
try:
response = requests.post(url, headers=headers, files={"none": ''}, data=data, timeout=60)
response.raise_for_status()
logging.debug(f"Response headers: {response.headers}")
logging.debug(f"Response content type: {response.headers.get('content-type')}")
if response.headers.get('content-type').startswith('image/'):
image_data = response.content
if len(image_data) < 1000:
raise Exception("Received incomplete image data")
return image_data
else:
error_message = response.text
logging.error(f"Unexpected content type: {response.headers.get('content-type')}. Response: {error_message}")
raise Exception(f"Unexpected content type: {response.headers.get('content-type')}. Response: {error_message}")
except requests.exceptions.RequestException as e:
logging.error(f"Request failed: {str(e)}")
raise Exception(f"Request failed: {str(e)}")
def process_and_generate(google_api_key, stability_api_key, prompt, style, steps, aspect_ratio, set_status):
try:
set_status("Enhancing prompt...")
enhanced_prompt = enhance_prompt(google_api_key, prompt, style)
set_status("Generating image...")
max_attempts = 3
for attempt in range(max_attempts):
try:
image_bytes = generate_image(stability_api_key, enhanced_prompt, style, DEFAULT_NEGATIVE_PROMPT, steps, aspect_ratio)
set_status("Image generated successfully!")
return image_bytes, enhanced_prompt
except Exception as e:
if attempt < max_attempts - 1:
set_status(f"Attempt {attempt + 1} failed. Retrying...")
time.sleep(2)
else:
raise e
except Exception as e:
logging.error(f"Error in process_and_generate: {str(e)}")
set_status(f"Error: {str(e)}")
return None, str(e)
@app.callback(
[Output("image-output", "src"),
Output("enhanced-prompt-output", "children"),
Output("status-message", "children"),
Output("download-btn", "disabled")],
[Input("submit-btn", "n_clicks")],
[State("prompt", "value"),
State("style", "value"),
State("steps", "value"),
State("aspect-ratio", "value")],
prevent_initial_call=True
)
def update_output(n_clicks, prompt, style, steps, aspect_ratio):
if n_clicks is None:
raise PreventUpdate
google_api_key = os.getenv('GOOGLE_API_KEY')
stability_api_key = os.getenv('STABILITY_API_KEY')
if not google_api_key or not stability_api_key:
return "", "Error: API keys not found in environment variables", "API keys missing", True
logging.debug(f"Stability API Key (first 4 chars): {stability_api_key[:4]}...")
status = {"message": "Starting process..."}
def set_status(message):
status["message"] = message
def run_process():
image_bytes, enhanced_prompt = process_and_generate(google_api_key, stability_api_key, prompt, style, steps, aspect_ratio, set_status)
if image_bytes:
encoded_image = base64.b64encode(image_bytes).decode('ascii')
return f"data:image/jpeg;base64,{encoded_image}", f"Enhanced Prompt: {enhanced_prompt}", status["message"], False
else:
return "", f"Error: {enhanced_prompt}", status["message"], True
try:
thread = threading.Thread(target=run_process)
thread.start()
thread.join(timeout=90)
if thread.is_alive():
return "", "Error: Image generation timed out", "Process timed out", True
return run_process()
except Exception as e:
logging.error(f"Unexpected error in update_output: {str(e)}")
return "", f"Unexpected error: {str(e)}", "An unexpected error occurred", True
@app.callback(
Output("download-image", "data"),
Input("download-btn", "n_clicks"),
State("image-output", "src"),
prevent_initial_call=True
)
def download_image(n_clicks, image_src):
if n_clicks is None:
raise PreventUpdate
image_data = image_src.split(",")[1]
image_bytes = base64.b64decode(image_data)
return dcc.send_bytes(image_bytes, "generated_image.jpeg")
if __name__ == '__main__':
print("Starting the Dash application...")
app.run(debug=False, host='0.0.0.0', port=7860)
print("Dash application has finished running.") |