Spaces:
Running
Running
File size: 29,496 Bytes
ccb88d2 e3355c4 ccb88d2 e3355c4 ccb88d2 d7e89a0 ccb88d2 a2576c7 e3355c4 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 3cf3832 ccb88d2 3cf3832 6380d03 3cf3832 ccb88d2 3cf3832 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 b0f52e3 ccb88d2 7ea41f5 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 6380d03 1d16c2b 6380d03 2622e9d 6380d03 ccb88d2 250ae72 ccb88d2 4bead13 ccb88d2 6380d03 ccb88d2 7ea41f5 ccb88d2 6380d03 ccb88d2 7ea41f5 2eb2f52 3758c3d 7ea41f5 ccb88d2 67635cf ccb88d2 2b0144f ccb88d2 6380d03 7ea41f5 42e2f1a 6380d03 7ea41f5 6380d03 ccb88d2 3cf3832 ccb88d2 7ea41f5 ccb88d2 6380d03 0e732d9 7ea41f5 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 1b285e0 6380d03 1b285e0 42e2f1a b3b6622 42e2f1a 6380d03 42e2f1a 7ea41f5 6380d03 42e2f1a 7ea41f5 42e2f1a 250ae72 7ea41f5 ccb88d2 6380d03 d81f080 6380d03 2622e9d 6380d03 ccb88d2 3cf3832 6380d03 3cf3832 ccb88d2 7ea41f5 ccb88d2 e3355c4 ccb88d2 7ea41f5 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 6380d03 ccb88d2 7ea41f5 ccb88d2 6380d03 ccb88d2 7ea41f5 ccb88d2 7ea41f5 ccb88d2 7ea41f5 ccb88d2 6380d03 ccb88d2 7ea41f5 ccb88d2 0b12d38 ccb88d2 e3355c4 11d8b5e ccb88d2 |
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 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 |
import gradio as gr
import asyncio
import aiohttp
import time
from datetime import datetime
import plotly.graph_objects as go
from typing import Dict, List
import os
from dotenv import load_dotenv
import json
from PIL import Image, ImageDraw, ImageFont
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
import uuid
import threading
import functools
# Load environment variables first
load_dotenv()
# Constants
API_BASE_URL = "https://api.wavespeed.ai/api/v2"
API_KEY = os.getenv("WAVESPEED_API_KEY") # Move API_KEY to global scope
if not API_KEY:
raise ValueError("WAVESPEED_API_KEY not found in environment variables")
# Rest of constants
BACKENDS = {
"flux-dev": {
"endpoint": f"{API_BASE_URL}/wavespeed-ai/flux-dev",
"name": "Flux-dev",
"color": "#FF9800",
},
"hidream-dev": {
"endpoint": f"{API_BASE_URL}/wavespeed-ai/hidream-i1-dev",
"name": "HiDream-dev",
"color": "#2196F3",
},
"hidream-full": {
"endpoint": f"{API_BASE_URL}/wavespeed-ai/hidream-i1-full",
"name": "HiDream-full",
"color": "#4CAF50",
},
}
MODEL_URL = "TostAI/nsfw-text-detection-large"
TITLE = "๐ผ๏ธ๐ Image Prompt Safety Classifier ๐ก๏ธ"
DESCRIPTION = "โจ Enter an image generation prompt to classify its safety level! โจ"
# Load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_URL)
model = AutoModelForSequenceClassification.from_pretrained(MODEL_URL)
# Define class names with emojis and detailed descriptions
CLASS_NAMES = {
0: "โ
SAFE - This prompt is appropriate and harmless.",
1: "โ ๏ธ QUESTIONABLE - This prompt may require further review.",
2: "๐ซ UNSAFE - This prompt is likely to generate inappropriate content."
}
@functools.lru_cache(maxsize=128)
def classify_text(text):
inputs = tokenizer(text,
return_tensors="pt",
truncation=True,
padding=True,
max_length=1024)
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits
predicted_class = torch.argmax(logits, dim=1).item()
return predicted_class, CLASS_NAMES[predicted_class]
class BackendStatus:
def __init__(self):
self.reset()
self.history: List[Dict] = []
def reset(self):
self.status = "idle"
self.progress = 0
self.start_time = None
self.end_time = None
def start(self):
self.status = "processing"
self.progress = 0
self.start_time = time.time()
self.end_time = None
def complete(self):
self.status = "completed"
self.progress = 100
self.end_time = time.time()
self.history.append({
"timestamp": datetime.now(),
"duration": self.end_time - self.start_time
})
def fail(self):
self.status = "failed"
self.end_time = time.time()
class SessionManager:
_instances = {}
_lock = threading.Lock()
@classmethod
def get_manager(cls, session_id=None):
if session_id is None:
session_id = str(uuid.uuid4())
with cls._lock:
if session_id not in cls._instances:
cls._instances[session_id] = GenerationManager()
return session_id, cls._instances[session_id]
@classmethod
def cleanup_old_sessions(cls, max_age=3600): # 1 hour default
current_time = time.time()
with cls._lock:
to_remove = []
for session_id, manager in cls._instances.items():
if (hasattr(manager, "last_activity")
and current_time - manager.last_activity > max_age):
to_remove.append(session_id)
for session_id in to_remove:
del cls._instances[session_id]
class GenerationManager:
def __init__(self):
self.backend_statuses = {
backend: BackendStatus()
for backend in BACKENDS
}
self.last_activity = time.time()
self.request_timestamps = [] # Track timestamps of requests
def update_activity(self):
self.last_activity = time.time()
def add_request_timestamp(self):
self.request_timestamps.append(time.time())
def has_exceeded_limit(self,
limit=10): # Default limit: 10 requests per hour
current_time = time.time()
# Filter timestamps to only include those within the last hour
self.request_timestamps = [
ts for ts in self.request_timestamps if current_time - ts <= 3600
]
return len(self.request_timestamps) >= limit
def get_performance_plot(self):
fig = go.Figure()
has_data = False
for backend, status in self.backend_statuses.items():
durations = [h["duration"] for h in status.history]
if durations:
has_data = True
avg_duration = sum(durations) / len(durations)
# Use bar chart instead of box plot
fig.add_trace(
go.Bar(
y=[avg_duration], #
x=[BACKENDS[backend]["name"]], # Backend name
name=BACKENDS[backend]["name"],
marker_color=BACKENDS[backend]["color"],
text=[f"{avg_duration:.2f}s"], # Show time in seconds
textposition="auto",
width=[0.5], # Make bars narrower
))
# Set a minimum y-axis range if we have data
if has_data:
max_duration = max([
max([h["duration"] for h in status.history] or [0])
for status in self.backend_statuses.values()
])
# Add 20% padding to the top
y_max = max_duration * 1.2
# Ensure the y-axis always starts at 0
fig.update_yaxes(range=[0, y_max])
fig.update_layout(
title="Average Generation Time (Including Network Latency)",
yaxis_title="Seconds",
xaxis_title="",
showlegend=False,
template="simple_white",
height=400, # Increase height
margin=dict(l=50, r=50, t=50, b=50), # Add margins
font=dict(size=14), # Larger font
)
# Make sure we have a valid figure even if no data
if not has_data:
fig.add_annotation(
text="No timing data available yet",
xref="paper",
yref="paper",
x=0.5,
y=0.5,
showarrow=False,
font=dict(size=16),
)
return fig
async def submit_task(self, backend: str, prompt: str) -> str:
status = self.backend_statuses[backend]
status.start()
try:
url = BACKENDS[backend]["endpoint"]
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
}
payload = {
"prompt": prompt,
"enable_safety_checker": True,
"enable_base64_output": True, # Enable base64 output
"size": "1024*1024",
"seed": -1,
}
print(f"Submitting task to {backend}")
print(f"URL: {url}")
print(f"Payload: {json.dumps(payload, indent=2)}")
# Use aiohttp instead of requests for async
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers,
json=payload) as response:
if response.status == 200:
result = await response.json()
request_id = result["data"]["id"]
print(
f"Task submitted successfully. Request ID: {request_id}"
)
return request_id
else:
text = await response.text()
raise Exception(
f"API error: {response.status}, {text}")
except Exception as e:
status.fail()
raise Exception(f"Failed to submit task: {str(e)}")
# Add this method to reset history
def reset_history(self):
"""Reset history for all backends"""
for status in self.backend_statuses.values():
status.history = [] # Clear history data
return self
class ClientManager:
_instances = {}
_lock = threading.Lock()
@classmethod
def get_manager(cls, client_id=None):
if not client_id:
client_id = str(uuid.uuid4())
with cls._lock:
if client_id not in cls._instances:
cls._instances[client_id] = ClientGenerationManager()
return cls._instances[client_id]
@classmethod
def cleanup_old_clients(cls, max_age=3600): # 1 hour default
current_time = time.time()
with cls._lock:
to_remove = []
for client_id, manager in cls._instances.items():
if (hasattr(manager, "last_activity")
and current_time - manager.last_activity > max_age):
to_remove.append(client_id)
for client_id in to_remove:
del cls._instances[client_id]
class ClientGenerationManager:
def __init__(self):
self.lock = threading.Lock()
self.last_activity = time.time()
self.request_timestamps = [] # Track timestamps of requests
def update_activity(self):
with self.lock:
self.last_activity = time.time()
def add_request_timestamp(self):
with self.lock:
self.request_timestamps.append(time.time())
def has_exceeded_limit(self, limit=20):
with self.lock:
current_time = time.time()
# Filter timestamps to only include those within the last hour
self.request_timestamps = [
ts for ts in self.request_timestamps
if current_time - ts <= 3600
]
return len(self.request_timestamps) >= limit
# Helper function to create error images as data URIs
def create_error_image(backend, error_message):
try:
import base64
from io import BytesIO
# Create an in-memory image
img = Image.new("RGB", (512, 512), color="#ffdddd")
draw = ImageDraw.Draw(img)
try:
font = ImageFont.truetype("Arial", 20)
except:
font = ImageFont.load_default()
# Wrap and draw error message
words = error_message.split(" ")
lines = []
line = ""
for word in words:
if len(line + word) < 40:
line += word + " "
else:
lines.append(line)
line = word + " "
if line:
lines.append(line)
y_position = 100
for line in lines:
draw.text((50, y_position), line, fill="black", font=font)
y_position += 30
# Save to a BytesIO object instead of a file
buffer = BytesIO()
img.save(buffer, format="JPEG")
img_bytes = buffer.getvalue()
# Convert to base64 and return as data URI
return f"data:image/jpeg;base64,{base64.b64encode(img_bytes).decode('utf-8')}"
except Exception as e:
print(f"Failed to create error image: {e}")
# Return a simple error message as fallback
return "Error: " + error_message
# Fix the poll_once function to accept a manager parameter
async def poll_once(manager, backend, request_id):
"""Poll once and return result if complete, otherwise None"""
headers = {"Authorization": f"Bearer {API_KEY}"}
url = f"{API_BASE_URL}/predictions/{request_id}/result"
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
if response.status == 200:
result = await response.json()
data = result["data"]
current_status = data["status"]
if current_status == "completed":
# IMPORTANT: Update status BEFORE returning - using the passed manager
manager.backend_statuses[backend].complete()
manager.update_activity()
# Handle base64 output
output = data["outputs"][0]
# Check if it's a base64 string or URL
if isinstance(output, str) and output.startswith("http"):
# It's a URL - return as is
return output
else:
# It's base64 data - format it as a data URI if needed
try:
# Format as data URI for Gradio to display directly
if isinstance(
output, str
) and not output.startswith("data:image"):
# Convert raw base64 to data URI format
return f"data:image/jpeg;base64,{output}"
else:
# Already in data URI format
return output
except Exception as e:
print(f"Error processing base64 image: {e}")
raise Exception(
f"Failed to process base64 image: {str(e)}")
elif current_status == "failed":
manager.backend_statuses[backend].fail()
manager.update_activity()
error = data.get("error", "Unknown error")
raise Exception(error)
# Still processing
return None
else:
raise Exception(f"Poll error: {response.status}")
# Store recent generations
recent_generations = []
# Example prompts
example_prompts = [
"A Ghibli-inspired scene featuring a giant, friendly creature walking through a lush forest and holding a sign saying 'HiDream', with vibrant colors, soft lighting, and whimsical details like floating lights and colorful, magical creatures. The scene captures a peaceful, enchanted atmosphere.",
"A neon-lit cyberpunk city at night, filled with towering skyscrapers, flying cars, and bustling streets. The air is thick with mist, and robots walk alongside humans, all illuminated by vibrant neon signs, holographic advertisements, and digital billboards.",
"A highly detailed, realistic portrait of an elderly man with deep wrinkles and a kind smile. Soft natural lighting, realistic skin textures, and lifelike details, capturing every strand of his white beard and the reflections in his glasses.",
]
# Use a state variable to store session ID
with gr.Blocks(theme=gr.themes.Soft()) as demo:
session_id = gr.State(None) # Add this to store session ID
# session_id = gr.BrowserState()(None) # Add this to store session ID
gr.Markdown("# ๐ WaveSpeedAI HiDream Arena")
# Add the introduction with link to WaveSpeedAI
gr.Markdown("""
[WaveSpeedAI](https://wavespeed.ai/) is the global pioneer in accelerating AI-powered video and image generation.
Our in-house inference accelerator provides lossless speedup on image & video generation based on our rich inference optimization software stack, including our in-house inference compiler, CUDA kernel libraries and parallel computing libraries.
""")
gr.Markdown("""
This demo showcases the performance and outputs of leading image generation models, including HiDream and Flux, on our accelerated inference platform.
""")
with gr.Row():
with gr.Column(scale=3):
example_dropdown = gr.Dropdown(
choices=example_prompts,
label="Choose an example prompt",
interactive=True,
)
input_text = gr.Textbox(
example_prompts[0],
label="Enter your prompt",
placeholder="Type here...",
lines=3,
)
with gr.Column(scale=1):
generate_btn = gr.Button("Generate", variant="primary")
example_dropdown.change(lambda ex: ex,
inputs=[example_dropdown],
outputs=[input_text],
api_name=False)
# Two status boxes - small (default) and big (during generation)
small_status_box = gr.Markdown("Ready to generate images",
elem_id="small-status")
# Big status box in its own row with styling
with gr.Row(elem_id="big-status-row"):
big_status_box = gr.Markdown("",
elem_id="big-status",
visible=False,
elem_classes="big-status-box")
with gr.Row():
with gr.Column():
draft_output = gr.Image(label="Flux-dev")
with gr.Column():
quick_output = gr.Image(label="HiDream-dev")
with gr.Column():
best_output = gr.Image(label="HiDream-full")
performance_plot = gr.Plot(label="Performance Metrics")
with gr.Accordion("Recent Generations (last 16)", open=False):
recent_gallery = gr.Gallery(label="Prompt and Output",
columns=3,
interactive=False)
def get_recent_gallery_items():
gallery_items = []
for r in reversed(recent_generations):
if any(x is None for x in r.values()):
continue
gallery_items.append((r["flux-dev"], f"FLUX-dev: {r['prompt']}"))
gallery_items.append(
(r["hidream-dev"], f"HiDream-dev: {r['prompt']}"))
gallery_items.append(
(r["hidream-full"], f"HiDream-full: {r['prompt']}"))
return gallery_items
def update_recent_gallery(prompt, results):
recent_generations.append({
"prompt": prompt,
"flux-dev": results["flux-dev"],
"hidream-dev": results["hidream-dev"],
"hidream-full": results["hidream-full"],
})
if len(recent_generations) > 16:
recent_generations.pop(0)
gallery_items = get_recent_gallery_items()
return gr.update(value=gallery_items)
# Add custom CSS for the big status box
css = """
#big-status-row {
margin: 20px 0;
}
#big-status {
font-size: 28px; /* Even larger font size */
font-weight: bold;
padding: 30px; /* More padding */
background-color: #0D47A1; /* Deeper blue background */
color: white; /* White text */
border-radius: 10px;
text-align: center;
margin: 0 auto;
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2); /* Stronger shadow */
animation: deep-breath 3s infinite; /* Slower, deeper breathing animation */
width: 100%; /* Full width */
max-width: 800px; /* Maximum width */
transition: all 0.3s ease; /* Smooth transitions */
border-left: 6px solid #64B5F6; /* Add a colored border */
border-right: 6px solid #64B5F6; /* Add a colored border */
}
/* Deeper breathing animation */
@keyframes deep-breath {
0% {
opacity: 0.7;
transform: scale(0.98);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
50% {
opacity: 1;
transform: scale(1.01);
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}
100% {
opacity: 0.7;
transform: scale(0.98);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
}
"""
gr.HTML(f"<style>{css}</style>")
# Update the generation function to use session manager
async def generate_all_backends_with_status_boxes(prompt,
current_session_id,
request: gr.Request):
client_ip = request.client.host
x_forwarded_for = request.headers.get('x-forwarded-for')
if x_forwarded_for:
client_ip = x_forwarded_for
print(f"Client IP: {client_ip}")
client_generation_manager = ClientManager.get_manager(client_ip)
client_generation_manager.update_activity()
if client_generation_manager.has_exceeded_limit(limit=20):
error_message = "โ Your network has exceeded the limit of 20 requests per hour. Please try again later."
yield (
error_message,
error_message,
gr.update(visible=False),
gr.update(visible=True),
None,
None,
None,
None,
current_session_id, # Return the session ID
None,
)
return
client_generation_manager.add_request_timestamp()
"""Generate images with big status box during generation"""
# Get or create a session manager
session_id, manager = SessionManager.get_manager(current_session_id)
manager.update_activity()
# Check if the user has exceeded the request limit
if manager.has_exceeded_limit(
limit=10): # Set the limit to 10 requests per hour
error_message = "โ You have exceeded the limit of 10 requests per hour. Please try again later."
yield (
error_message,
error_message,
gr.update(visible=False),
gr.update(visible=True),
None,
None,
None,
None,
session_id,
None,
)
return
# Add the current request timestamp
manager.add_request_timestamp()
# IMPORTANT: Reset history when starting a new generation
if prompt and prompt.strip() != "":
manager.reset_history() # Clear previous performance metrics
if not prompt or prompt.strip() == "":
# Handle empty prompt case
yield (
"โ ๏ธ Please enter a prompt first",
"โ ๏ธ Please enter a prompt first",
gr.update(visible=True),
gr.update(visible=False),
None,
None,
None,
None,
session_id, # Return the session ID
None,
)
return
# Check if the prompt is safe
classification, message = classify_text(prompt)
if classification != 0:
# Handle unsafe prompt case
yield (
message,
message,
gr.update(visible=True),
gr.update(visible=False),
None,
None,
None,
None,
session_id, # Return the session ID
None,
)
return
# Status message
status_message = f"๐ PROCESSING: '{prompt}'"
# Initial state - clear all images, show big status box
yield (
status_message,
status_message,
gr.update(visible=True),
gr.update(visible=False),
None,
None,
None,
None,
session_id, # Return the session ID
None,
)
# For production mode:
completed_backends = set()
results = {"flux-dev": None, "hidream-dev": None, "hidream-full": None}
try:
# Submit all tasks
request_ids = {}
for backend in BACKENDS:
try:
request_id = await manager.submit_task(backend, prompt)
request_ids[backend] = request_id
except Exception as e:
# Handle submission error
print(f"Error submitting task for {backend}: {e}")
results[backend] = create_error_image(backend, str(e))
completed_backends.add(backend)
# Poll all backends until they complete
max_poll_attempts = 300
poll_attempt = 0
# Main polling loop
while len(completed_backends
) < 3 and poll_attempt < max_poll_attempts:
poll_attempt += 1
# Poll each pending backend
for backend in list(BACKENDS.keys()):
if backend in completed_backends:
continue
try:
# Only do actual API calls every few attempts to reduce load
if poll_attempt % 2 == 0 or backend == "flux-dev":
# Use the session manager instead of global manager
result = await poll_once(manager, backend,
request_ids[backend])
if result: # Backend completed
results[backend] = result
completed_backends.add(backend)
# Yield updated state when an image completes
yield (
status_message,
status_message,
gr.update(visible=True),
gr.update(visible=False),
results["flux-dev"],
results["hidream-dev"],
results["hidream-full"],
(manager.get_performance_plot()
if any(completed_backends) else None),
session_id,
None,
)
except Exception as e:
print(f"Error polling {backend}: {str(e)}")
# Wait between poll attempts
await asyncio.sleep(0.1)
# Final status
final_status = ("โ
All generations completed!"
if len(completed_backends) == 3 else
"โ ๏ธ Some generations timed out")
gallery_update = update_recent_gallery(prompt, results)
# Final yield
yield (
final_status,
final_status,
gr.update(visible=False),
gr.update(visible=True),
results["flux-dev"],
results["hidream-dev"],
results["hidream-full"],
manager.get_performance_plot(),
session_id,
gallery_update,
)
except Exception as e:
# Error handling
error_message = f"โ Error: {str(e)}"
yield (
error_message,
error_message,
gr.update(visible=False),
gr.update(visible=True),
None,
None,
None,
None,
session_id,
None,
)
# Schedule periodic cleanup of old sessions
def cleanup_task():
SessionManager.cleanup_old_sessions()
ClientManager.cleanup_old_clients()
# Schedule the next cleanup
threading.Timer(3600, cleanup_task).start() # Run every hour
# Start the cleanup task
cleanup_task()
# Update the click handler to include session_id
generate_btn.click(
fn=generate_all_backends_with_status_boxes,
inputs=[input_text, session_id],
outputs=[
small_status_box,
big_status_box,
big_status_box, # visibility
small_status_box, # visibility
draft_output,
quick_output,
best_output,
performance_plot,
session_id, # Update the session ID
recent_gallery, # Update the gallery
],
# api_name="generate",
api_name=False,
max_batch_size=10, # Process up to 10 requests at once
concurrency_limit=20, # Allow up to 20 concurrent requests
concurrency_id="generation", # Group concurrent requests under this ID
)
# Launch with increased max_threads
if __name__ == "__main__":
demo.queue(max_size=50).launch(
server_name="0.0.0.0",
max_threads=16, # Increase thread count for better concurrency
)
demo.queue(max_size=4).launch(
server_name="0.0.0.0",
max_threads=16, # Increase thread count for better concurrency
)
|