File size: 14,588 Bytes
97cce6b fe58d40 |
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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 |
import gradio as gr
import requests
import os
import time
from PIL import Image
import io
import base64
import json
# Configuration
MIRAGIC_API_URL = os.getenv("MIRAGIC_API_URL")
COMPANY_NAME = "Miragic"
COMPANY_URL = "https://www.miragic.ai"
CONTACT_EMAIL = "info@miragic.ai"
def generate_image_via_api(prompt, model, width, height, seed, image_url, enhance, safe):
"""
Call the Flask API to generate an image
"""
try:
# Prepare the request data
data = {
"prompt": prompt,
"model": model,
"width": width,
"height": height,
"enhance": enhance,
"safe": safe
}
if seed and seed != -1:
data["seed"] = seed
if image_url:
data["image_url"] = image_url
# Validate kontext model requirements
if model.lower() == "kontext" and not image_url:
raise gr.Error("Image URL is required for kontext model (image-to-image generation)")
# Make the API request
response = requests.post(
f"{MIRAGIC_API_URL}/generate_image",
json=data,
timeout=300 # Increased timeout for image generation
)
if response.status_code == 200:
result = response.json()
if result["status"] == "success":
# Download the image from Dropbox link
image_url = result["link"]
image_response = requests.get(image_url, timeout=30)
if image_response.status_code == 200:
# Convert to PIL Image
image = Image.open(io.BytesIO(image_response.content))
return image, gr.update(visible=True)
else:
return None, gr.update(visible=False)
else:
raise gr.Error(f"API Error: {result.get('error', 'Unknown error')}")
else:
raise gr.Error(f"HTTP Error: {response.status_code} - {response.text}")
except requests.exceptions.RequestException as e:
raise gr.Error(f"Request Error: {str(e)}")
except Exception as e:
raise gr.Error(f"Unexpected Error: {str(e)}")
def get_available_models():
"""
Get available models from the Flask API
"""
try:
response = requests.get(f"{MIRAGIC_API_URL}/available_models", timeout=10)
if response.status_code == 200:
result = response.json()
if result["status"] == "success":
return result["models"]
return ["flux", "kontext", "dreamshaper", "realistic", "anime"]
except:
return ["flux", "kontext", "dreamshaper", "realistic", "anime"]
def handle_like_action():
"""Handle like button click"""
return gr.update(
value="β€οΈ Thanks for liking! Please star our repo!",
interactive=False,
variant="secondary"
)
def create_footer_html():
"""Create footer HTML"""
return f"""
<div style="text-align: center; margin-top: 30px; padding: 15px; border-radius: 8px;">
<p style="margin: 5px 0;">Β© 2025 {COMPANY_NAME}. All rights reserved.</p>
<p style="margin: 5px 0;">
<a href="{COMPANY_URL}" target="_blank" style="color: #0984e3; text-decoration: none;">Website</a> |
<a href="mailto:{CONTACT_EMAIL}" style="color: #0984e3; text-decoration: none;">Contact Us</a> |
<a href="{COMPANY_URL}/privacy-policy" target="_blank" style="color: #0984e3; text-decoration: none;">Privacy Policy</a>
</p>
</div>
"""
def create_instructions_html():
"""Create instructions HTML"""
return """
<div style="padding: 15px; border-radius: 8px; margin-bottom: 20px;">
<h2 style="margin-top: 0;">How to use:</h2>
<ol style="color: #636e72;">
<li>Enter a detailed description of the image you want to generate</li>
<li>Select a model (different models have different styles)</li>
<li>For 'kontext' model, provide an image URL for image-to-image generation</li>
<li>Adjust the image dimensions and other parameters</li>
<li>Click "Generate Image" to create your AI artwork</li>
</ol>
<p style="margin-bottom: 0;"><strong>Tip:</strong> Be specific in your prompts for better results!</p>
</div>
"""
def get_css_styles():
"""Get CSS styles for the interface"""
return """
footer {visibility: hidden}
.banner {
background-color: #f8f9fa;
padding: 10px;
border-radius: 5px;
margin-bottom: 20px;
text-align: center;
}
.button-gradient {
background: linear-gradient(45deg, #ff416c, #ff4b2b, #ff9b00, #ff416c);
background-size: 400% 400%;
border: none;
padding: 14px 28px;
font-size: 16px;
font-weight: bold;
color: white;
border-radius: 10px;
cursor: pointer;
transition: 0.3s ease-in-out;
animation: gradientAnimation 2s infinite linear;
box-shadow: 0 4px 10px rgba(255, 65, 108, 0.6);
}
@keyframes gradientAnimation {
0% { background-position: 0% 50%; }
100% { background-position: 100% 50%; }
}
.button-gradient:hover {
transform: scale(1.05);
box-shadow: 0 6px 15px rgba(255, 75, 43, 0.8);
}
.signup-container {
text-align: center;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
margin-top: 10px;
color: white;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.signup-container h3 {
margin-bottom: 10px;
color: white;
}
.signup-container p {
margin-bottom: 15px;
color: #f0f0f0;
}
.signup-button {
background: linear-gradient(45deg, #ff416c, #ff4b2b);
border: none;
padding: 12px 25px;
font-size: 16px;
font-weight: bold;
color: white;
border-radius: 8px;
text-decoration: none;
display: inline-block;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.signup-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
}
#col-container {
max-width: 1400px;
margin: 0 auto;
}
.step-column {
padding: 20px;
border-radius: 8px;
box-shadow: var(--card-shadow);
margin: 10px;
}
.step-title {
color: var(--primary-color);
text-align: center;
margin-bottom: 15px;
}
.image-preview {
border-radius: 8px;
overflow: hidden;
box-shadow: var(--card-shadow);
}
.result-section {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: var(--card-shadow);
}
.footer {
margin-top: 30px;
text-align: center;
}
.like-button {
background: linear-gradient(45deg, #ff6b6b, #ff8e8e);
border: none;
padding: 10px 20px;
font-size: 14px;
font-weight: bold;
color: white;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
}
.like-button:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(255, 107, 107, 0.5);
}
.interaction-section {
text-align: center;
padding: 20px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 8px;
margin-top: 20px;
color: white;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
}
.kontext-notice {
background: #fff3cd;
padding: 10px;
border-radius: 5px;
margin: 10px 0;
border-left: 4px solid #ffc107;
color: #856404;
}
"""
# Create the Gradio interface
with gr.Blocks(css=get_css_styles(), title=f"{COMPANY_NAME} AI Image Generator", theme=gr.themes.Ocean()) as demo:
with gr.Row():
with gr.Column(0.7):
gr.Markdown(f"""
<div style="display: flex; align-items: center;">
<img src="https://avatars.githubusercontent.com/u/211682198?s=200&v=4" style="width: 80px; margin-right: 20px;"/>
<div>
<h1 style="margin-bottom: 0;">{COMPANY_NAME} AI Image Generator π¨</h1>
<p style="margin-top: 0; color: #636e72;">Create stunning AI-generated images with text prompts</p>
</div>
</div>
""")
gr.HTML(create_instructions_html())
with gr.Column(0.3):
gr.Markdown(f"""
<div style="display: flex; align-items: center;">
<img src="https://miragic.ai/products/qrcode-vto.png" style="width: 450px; margin-left: 100px;"/>
</div>
""")
with gr.Row(elem_id="col-container"):
# Step 1: Prompt and Settings
with gr.Column(elem_classes="step-column"):
gr.HTML("""
<div class="step-title">
<span style="font-size: 24px;">1. Enter Prompt & Settings</span><br>
</div>
""")
prompt = gr.Textbox(
label="Prompt",
lines=3,
placeholder="Describe the image you want to generate...",
value=""
)
with gr.Row():
model = gr.Dropdown(
choices=get_available_models(),
value="flux",
label="Model"
)
seed = gr.Number(
label="Seed",
value=-1,
info="-1 for random seed"
)
with gr.Row():
width = gr.Slider(
minimum=256,
maximum=2048,
value=1024,
step=64,
label="Width"
)
height = gr.Slider(
minimum=256,
maximum=2048,
value=1024,
step=64,
label="Height"
)
image_url = gr.Textbox(
label="Image URL (for kontext model only)",
placeholder="https://example.com/image.jpg",
info="Required for image-to-image generation with kontext model"
)
with gr.Row():
enhance = gr.Checkbox(label="Enhance Prompt", value=False, info="Use AI to enhance your prompt")
safe = gr.Checkbox(label="Safe Filter", value=False, info="Enable strict NSFW filtering")
gr.HTML("""
<div class="kontext-notice">
<strong>Note:</strong> For the 'kontext' model, you must provide an Image URL for image-to-image generation.
Example: "bake_a_cake_from_this_logo" with image URL of a logo.
</div>
""")
generate_btn = gr.Button(
"Generate Image π¨",
elem_classes="button-gradient"
)
# Step 2: Results
with gr.Column(elem_classes="step-column"):
gr.HTML("""
<div class="step-title">
<span style="font-size: 24px;">2. Generated Image</span><br>
</div>
""")
result_img = gr.Image(
label="Generated Image",
interactive=False,
elem_classes="image-preview",
height=400
)
with gr.Row():
like_button = gr.Button(
"π Like this result!",
elem_classes="like-button",
visible=False
)
gr.HTML("""
<div class="interaction-section">
<p style="margin: 5px 0;">If you like our AI Image Generator, please give us a β€οΈ into our space!</p>
</div>
""")
signup_prompt = gr.HTML(
visible=True,
value=f"""<div class="signup-container">
<h3>π Want more AI tools?</h3>
<p>Visit {COMPANY_NAME}.ai for unlimited access to all our AI tools!</p>
<a href='{COMPANY_URL}/' target='_blank' class="signup-button">
Explore More Tools π
</a>
</div>"""
)
# Examples
examples = [
["An epic fantasy landscape with floating islands, cascading waterfalls, ancient ruins, magical aurora borealis in the sky, digital painting, concept art, unreal engine 5, 4K wallpaper", "flux", 2048, 1024, -1, "", False, False],
["A serene Japanese garden with cherry blossoms, koi pond, traditional pagoda, morning mist, sunlight filtering through trees, peaceful atmosphere, ultra detailed", "flux", 2048, 1024, -1, "", True, False],
["bake_a_cake_from_this_logo", "kontext", 1024, 1024, -1, "https://avatars.githubusercontent.com/u/86964862", False, False],
["A minimalist modern living room with large windows, Scandinavian design, plants, cozy atmosphere, architectural rendering", "turbo", 1024, 1024, 42, "", False, True],
["A beautiful tropical beach with turquoise water, white sand, palm trees, sunset colors, relaxing vibe, 4K wallpaper", "turbo", 2048, 1024, -1, "", True, False],
]
gr.Examples(
examples=examples,
inputs=[prompt, model, width, height, seed, image_url, enhance, safe],
outputs=[result_img, like_button],
fn=generate_image_via_api,
cache_examples=False,
label="Example Prompts"
)
# Button actions
generate_btn.click(
fn=generate_image_via_api,
inputs=[prompt, model, width, height, seed, image_url, enhance, safe],
outputs=[result_img, like_button],
api_name="generate_image"
)
like_button.click(
fn=handle_like_action,
inputs=[],
outputs=[like_button]
)
# Visitor badge
gr.HTML(f'<a href="https://visitorbadge.io/status?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2F{COMPANY_NAME}-AI%2F{COMPANY_NAME}-AI-Image-Generator"><img src="https://api.visitorbadge.io/api/combined?path=https%3A%2F%2Fhuggingface.co%2Fspaces%2F{COMPANY_NAME}-AI%2F{COMPANY_NAME}-AI-Image-Generator&label=VISITORS&labelColor=%2337d67a&countColor=%23f47373&style=plastic&labelStyle=upper" /></a>')
# Footer
gr.HTML(create_footer_html())
if __name__ == "__main__":
demo.launch(
show_api=False,
server_name="0.0.0.0",
server_port=7860
) |