File size: 33,185 Bytes
0131ae7 |
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 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 |
"""
Main AnyCoder application with advanced professional UI.
"""
import os
import uuid
import time
from typing import Dict, List, Optional, Tuple, Any
import gradio as gr
# Import all modules
from config import (
AVAILABLE_MODELS, DEFAULT_MODEL, THEME_CONFIGS, DEMO_LIST,
get_gradio_language, get_saved_theme, save_theme_preference
)
from utils import (
get_inference_client, remove_code_block, extract_text_from_file,
create_multimodal_message, apply_search_replace_changes,
cleanup_all_temp_media, cleanup_session_media, reap_old_media
)
from media_generation import (
generate_image_with_qwen, generate_image_to_image, generate_video_from_image,
generate_video_from_text, generate_music_from_text
)
from web_utils import extract_website_content, enhance_query_with_search, tavily_client
from code_processing import (
is_streamlit_code, is_gradio_code, parse_transformers_js_output,
format_transformers_js_output, parse_svelte_output, format_svelte_output,
parse_multipage_html_output, format_multipage_output, validate_and_autofix_files,
inline_multipage_into_single_preview, apply_generated_media_to_html,
extract_html_document, apply_search_replace_changes as apply_transformers_js_search_replace_changes
)
from sandbox import (
send_to_sandbox, send_to_sandbox_with_refresh, send_streamlit_to_stlite,
send_gradio_to_lite, send_transformers_to_sandbox, generate_preview
)
from deployment import (
deploy_to_user_space, deploy_to_spaces, deploy_to_spaces_static,
load_project_from_url, extract_import_statements
)
# Global state
History = List[Tuple[str, str]]
Messages = List[Dict[str, str]]
def history_to_messages(history: History, system: str) -> Messages:
"""Convert history to messages format"""
messages = [{'role': 'system', 'content': system}]
for h in history:
user_content = h[0]
if isinstance(user_content, list):
text_content = ""
for item in user_content:
if isinstance(item, dict) and item.get("type") == "text":
text_content += item.get("text", "")
user_content = text_content if text_content else str(user_content)
messages.append({'role': 'user', 'content': user_content})
messages.append({'role': 'assistant', 'content': h[1]})
return messages
def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:
"""Convert history tuples to chatbot message format"""
messages = []
for user_msg, assistant_msg in history:
if isinstance(user_msg, list):
text_content = ""
for item in user_msg:
if isinstance(item, dict) and item.get("type") == "text":
text_content += item.get("text", "")
user_msg = text_content if text_content else str(user_msg)
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": assistant_msg})
return messages
def clear_history():
"""Clear all history and reset UI"""
return [], [], None, ""
def update_image_input_visibility(model):
"""Update image input visibility based on selected model"""
is_vision_model = model.get("supports_vision", False)
return gr.update(visible=is_vision_model)
def generation_code(query: Optional[str], vlm_image: Optional[gr.Image], gen_image: Optional[gr.Image],
file: Optional[str], website_url: Optional[str], _setting: Dict[str, str],
_history: Optional[History], _current_model: Dict, enable_search: bool = False,
language: str = "html", provider: str = "auto", enable_image_generation: bool = False,
enable_image_to_image: bool = False, image_to_image_prompt: Optional[str] = None,
text_to_image_prompt: Optional[str] = None, enable_image_to_video: bool = False,
image_to_video_prompt: Optional[str] = None, enable_text_to_video: bool = False,
text_to_video_prompt: Optional[str] = None, enable_text_to_music: bool = False,
text_to_music_prompt: Optional[str] = None):
"""Main code generation function"""
if query is None:
query = ''
if _history is None:
_history = []
# Ensure proper history format
if not isinstance(_history, list):
_history = []
_history = [h for h in _history if isinstance(h, list) and len(h) == 2]
# Create/lookup session ID for temp file tracking
if _setting is not None and isinstance(_setting, dict):
session_id = _setting.get("__session_id__")
if not session_id:
session_id = str(uuid.uuid4())
_setting["__session_id__"] = session_id
else:
session_id = str(uuid.uuid4())
# Cleanup old files
try:
cleanup_session_media(session_id)
reap_old_media()
except Exception:
pass
# Check for existing content (modification request)
has_existing_content = False
last_assistant_msg = ""
if _history and len(_history[-1]) > 1:
last_assistant_msg = _history[-1][1]
if any(indicator in last_assistant_msg for indicator in [
'<!DOCTYPE html>', '<html', 'import gradio', 'import streamlit',
'def ', '=== index.html ===', '=== index.js ===', '=== style.css ==='
]):
has_existing_content = True
# Handle modification requests with search/replace
if has_existing_content and query.strip():
try:
client = get_inference_client(_current_model['id'], provider)
system_prompt = f"""You are a code editor assistant. Generate EXACT search/replace blocks using these markers:
{from config import SEARCH_START, DIVIDER, REPLACE_END}
CRITICAL REQUIREMENTS:
1. Use EXACTLY these markers: {SEARCH_START}, {DIVIDER}, {REPLACE_END}
2. The SEARCH block must match existing code EXACTLY (whitespace, indentation, line breaks)
3. Generate multiple blocks if needed for different changes
4. Include enough context to make search blocks unique
5. Do NOT include explanations outside the blocks"""
user_prompt = f"""Existing code:
{last_assistant_msg}
Modification instructions:
{query}
Generate the exact search/replace blocks needed."""
messages = [
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt}
]
# Generate search/replace instructions
if hasattr(client, 'chat'):
if hasattr(client.chat, 'completions'):
response = client.chat.completions.create(
model=_current_model['id'],
messages=messages,
max_tokens=4000,
temperature=0.1
)
changes_text = response.choices[0].message.content
else:
response = client.chat.complete(
model=_current_model['id'],
messages=messages,
max_tokens=4000,
temperature=0.1
)
changes_text = response.choices[0].message.content
else:
completion = client.chat.completions.create(
model=_current_model['id'],
messages=messages,
max_tokens=4000,
temperature=0.1
)
changes_text = completion.choices[0].message.content
# Apply changes
if language == "transformers.js" and ('=== index.html ===' in last_assistant_msg):
modified_content = apply_transformers_js_search_replace_changes(last_assistant_msg, changes_text)
else:
modified_content = apply_search_replace_changes(last_assistant_msg, changes_text)
# If changes were applied, return modified content
if modified_content != last_assistant_msg:
_history.append([query, modified_content])
# Generate preview
preview_val = generate_preview(modified_content, language)
yield {
code_output: modified_content,
history: _history,
sandbox: preview_val,
history_output: history_to_chatbot_messages(_history),
}
return
except Exception as e:
print(f"Search/replace failed, falling back to normal generation: {e}")
# Choose appropriate system prompt
from config import HTML_SYSTEM_PROMPT, TRANSFORMERS_JS_SYSTEM_PROMPT, SVELTE_SYSTEM_PROMPT, GENERIC_SYSTEM_PROMPT
if language == "html":
system_prompt = HTML_SYSTEM_PROMPT
elif language == "transformers.js":
system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT
elif language == "svelte":
system_prompt = SVELTE_SYSTEM_PROMPT
else:
system_prompt = GENERIC_SYSTEM_PROMPT.format(language=language)
messages = history_to_messages(_history, system_prompt)
# Process file input
file_text = ""
if file:
file_text = extract_text_from_file(file)
if file_text:
file_text = file_text[:5000]
query = f"{query}\n\n[Reference file content]\n{file_text}"
# Process website URL
if website_url and website_url.strip():
website_text = extract_website_content(website_url.strip())
if website_text and not website_text.startswith("Error"):
website_text = website_text[:8000]
query = f"{query}\n\n[Website content to redesign]\n{website_text}"
# Enhance with web search if enabled
enhanced_query = enhance_query_with_search(query, enable_search)
# Add message
if vlm_image is not None:
messages.append(create_multimodal_message(enhanced_query, vlm_image))
else:
messages.append({'role': 'user', 'content': enhanced_query})
# Generate code using the appropriate client
try:
client = get_inference_client(_current_model["id"], provider)
# Stream generation
if hasattr(client, 'chat') and hasattr(client.chat, 'completions'):
completion = client.chat.completions.create(
model=_current_model["id"],
messages=messages,
stream=True,
max_tokens=16384
)
else:
# Handle other client types
completion = client.chat.completions.create(
model=_current_model["id"],
messages=messages,
stream=True,
max_tokens=16384
)
content = ""
for chunk in completion:
chunk_content = None
if hasattr(chunk, "choices") and chunk.choices:
if hasattr(chunk.choices[0], "delta") and hasattr(chunk.choices[0].delta, "content"):
chunk_content = chunk.choices[0].delta.content
if chunk_content:
content += chunk_content
# Generate live preview
clean_code = remove_code_block(content)
preview_val = generate_preview(clean_code, language)
yield {
code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
history_output: history_to_chatbot_messages(_history),
sandbox: preview_val,
}
# Final processing
final_content = remove_code_block(content)
# Apply media generation
final_content = apply_generated_media_to_html(
final_content,
query,
enable_text_to_image=enable_image_generation,
enable_image_to_image=enable_image_to_image,
input_image_data=gen_image,
image_to_image_prompt=image_to_image_prompt,
text_to_image_prompt=text_to_image_prompt,
enable_image_to_video=enable_image_to_video,
image_to_video_prompt=image_to_video_prompt,
session_id=session_id,
enable_text_to_video=enable_text_to_video,
text_to_video_prompt=text_to_video_prompt,
enable_text_to_music=enable_text_to_music,
text_to_music_prompt=text_to_music_prompt,
)
_history.append([query, final_content])
# Generate final preview
preview_val = generate_preview(final_content, language)
yield {
code_output: final_content,
history: _history,
sandbox: preview_val,
history_output: history_to_chatbot_messages(_history),
}
except Exception as e:
error_message = f"Error: {str(e)}"
yield {
code_output: error_message,
history_output: history_to_chatbot_messages(_history),
}
def create_advanced_ui():
"""Create the advanced professional UI"""
# Load saved theme
current_theme_name = get_saved_theme()
current_theme = THEME_CONFIGS[current_theme_name]["theme"]
# Custom CSS for professional styling
custom_css = """
/* Professional styling */
.gradio-container {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif !important;
}
/* Advanced sidebar styling */
.advanced-sidebar {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 16px;
padding: 24px;
margin-bottom: 16px;
}
.advanced-sidebar h3 {
color: white;
font-weight: 600;
margin-bottom: 16px;
font-size: 18px;
}
/* Model cards */
.model-card {
background: rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px);
border-radius: 12px;
padding: 16px;
margin-bottom: 12px;
border: 1px solid rgba(255, 255, 255, 0.2);
}
.model-card.selected {
background: rgba(255, 255, 255, 0.2);
border-color: rgba(255, 255, 255, 0.4);
}
/* Demo cards */
.demo-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 16px;
margin: 20px 0;
}
.demo-card {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
border-radius: 12px;
padding: 20px;
cursor: pointer;
transition: all 0.3s ease;
border: 2px solid transparent;
}
.demo-card:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.demo-card h4 {
color: #2d3748;
font-weight: 600;
margin-bottom: 8px;
}
.demo-card p {
color: #4a5568;
font-size: 14px;
line-height: 1.5;
}
.demo-category {
display: inline-block;
background: #667eea;
color: white;
padding: 4px 8px;
border-radius: 12px;
font-size: 12px;
font-weight: 500;
margin-bottom: 8px;
}
/* Feature toggles */
.feature-toggle {
background: rgba(103, 126, 234, 0.1);
border: 1px solid rgba(103, 126, 234, 0.3);
border-radius: 8px;
padding: 12px;
margin-bottom: 8px;
}
/* Status indicators */
.status-indicator {
display: inline-flex;
align-items: center;
gap: 8px;
font-size: 14px;
color: #4a5568;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #48bb78;
}
.status-dot.warning {
background: #ed8936;
}
.status-dot.error {
background: #f56565;
}
/* Code editor enhancements */
.code-editor-wrapper {
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
/* Preview enhancements */
.preview-container {
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
background: white;
}
/* Deployment section */
.deployment-section {
background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
border-radius: 12px;
padding: 20px;
margin-top: 16px;
}
.deployment-section h4 {
color: #2d3748;
font-weight: 600;
margin-bottom: 12px;
}
"""
# Create the main interface
with gr.Blocks(
title="AnyCoder - Advanced AI Code Generator",
theme=current_theme,
css=custom_css
) as demo:
# State management
history = gr.State([])
setting = gr.State({"system": from config import HTML_SYSTEM_PROMPT})
current_model = gr.State(DEFAULT_MODEL)
# Header
with gr.Row():
with gr.Column(scale=1):
gr.HTML("""
<div style='text-align: center; padding: 20px 0;'>
<h1 style='font-size: 2.5em; font-weight: 700; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 8px;'>
AnyCoder Pro
</h1>
<p style='font-size: 1.1em; color: #4a5568; margin: 0;'>
Professional AI-Powered Code Generation Platform
</p>
</div>
""")
# Main layout
with gr.Row():
# Advanced Sidebar
with gr.Column(scale=1, elem_classes=["advanced-sidebar"]) as sidebar:
# Login section
login_button = gr.LoginButton()
# Model selection with categories
with gr.Accordion("π€ Model Selection", open=True):
# Group models by category
model_categories = {}
for model in AVAILABLE_MODELS:
category = model.get("category", "General")
if category not in model_categories:
model_categories[category] = []
model_categories[category].append(model)
model_dropdown = gr.Dropdown(
choices=[model['name'] for model in AVAILABLE_MODELS],
value=DEFAULT_MODEL['name'],
label="Select Model",
info="Choose the AI model for code generation"
)
# Model info display
model_info = gr.Markdown(DEFAULT_MODEL['description'])
# Project management
with gr.Accordion("π Project Management", open=False):
gr.Markdown("**Import Existing Project**")
load_project_url = gr.Textbox(
label="Project URL",
placeholder="https://huggingface.co/spaces/user/space",
info="Import from HF Spaces, GitHub, or HF Models"
)
load_project_btn = gr.Button("Import Project", variant="secondary")
load_project_status = gr.Markdown(visible=False)
# Code generation settings
with gr.Accordion("βοΈ Generation Settings", open=True):
language_dropdown = gr.Dropdown(
choices=["html", "streamlit", "gradio", "python", "transformers.js", "svelte"],
value="html",
label="Framework/Language",
info="Select the target framework"
)
enable_search = gr.Checkbox(
label="π Web Search Enhancement",
value=False,
info="Use real-time web search for up-to-date information"
)
if tavily_client:
search_status = gr.HTML("""
<div class="status-indicator">
<div class="status-dot"></div>
<span>Web search available</span>
</div>
""")
else:
search_status = gr.HTML("""
<div class="status-indicator">
<div class="status-dot error"></div>
<span>Web search unavailable</span>
</div>
""")
# Media generation features
with gr.Accordion("π¨ AI Media Generation", open=False):
enable_image_generation = gr.Checkbox(
label="Generate Images (Text β Image)",
value=False,
info="Auto-generate images using Qwen-Image"
)
text_to_image_prompt = gr.Textbox(
label="Image Generation Prompt",
placeholder="Describe the image to generate...",
lines=2,
visible=False
)
enable_image_to_image = gr.Checkbox(
label="Transform Images (Image β Image)",
value=False,
info="Transform uploaded images using AI"
)
image_to_image_prompt = gr.Textbox(
label="Image Transformation Prompt",
placeholder="Describe how to transform the image...",
lines=2,
visible=False
)
enable_image_to_video = gr.Checkbox(
label="Generate Videos (Image β Video)",
value=False,
info="Create videos from uploaded images"
)
enable_text_to_video = gr.Checkbox(
label="Generate Videos (Text β Video)",
value=False,
info="Create videos from text descriptions"
)
enable_text_to_music = gr.Checkbox(
label="Generate Music (Text β Music)",
value=False,
info="Compose music from text descriptions"
)
# Input section
with gr.Accordion("π Input & Files", open=True):
user_input = gr.Textbox(
label="What would you like to build?",
placeholder="Describe your application in detail...",
lines=4,
info="Be specific about features, design, and functionality"
)
website_url_input = gr.Textbox(
label="Website URL (for redesign)",
placeholder="https://example.com",
info="URL of website to redesign"
)
file_input = gr.File(
label="Reference Files",
file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".png"],
info="Upload reference documents or images"
)
vlm_image = gr.Image(
label="Design Reference Image",
visible=False,
info="Upload UI mockup or design reference"
)
generation_image = gr.Image(
label="Image for Generation",
visible=False,
info="Upload image for AI processing"
)
# Action buttons
with gr.Row():
generate_btn = gr.Button("π Generate", variant="primary", scale=2)
clear_btn = gr.Button("ποΈ Clear", variant="secondary", scale=1)
# Main content area
with gr.Column(scale=3):
# Quick start section
with gr.Row():
gr.HTML("""
<div style='background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); border-radius: 12px; padding: 20px; margin-bottom: 20px;'>
<h3 style='color: white; margin: 0 0 16px 0; font-weight: 600;'>Quick Start Examples</h3>
<div class='demo-grid'>
""")
# Demo cards
demo_cards = []
for i, demo in enumerate(DEMO_LIST[:6]): # Show first 6 demos
demo_card = gr.Button(
f"""
<div class='demo-card'>
<div class='demo-category'>{demo.get('category', 'General')}</div>
<h4>{demo['title']}</h4>
<p>{demo['description']}</p>
</div>
""",
variant="secondary",
elem_classes=["demo-card-btn"]
)
demo_cards.append(demo_card)
gr.HTML("</div></div>")
# Main tabs
with gr.Tabs() as main_tabs:
# Preview tab
with gr.Tab("π₯οΈ Live Preview"):
sandbox = gr.HTML(
label="Live Preview",
elem_classes=["preview-container"]
)
# Code editor tab
with gr.Tab("π Code Editor"):
with gr.Row():
with gr.Column():
code_output = gr.Code(
language="html",
lines=30,
interactive=True,
label="Generated Code",
elem_classes=["code-editor-wrapper"]
)
# Multi-file editors (hidden by default)
with gr.Group(visible=False) as transformers_group:
with gr.Tabs():
with gr.Tab("index.html"):
tjs_html_code = gr.Code(language="html", lines=25, interactive=True)
with gr.Tab("index.js"):
tjs_js_code = gr.Code(language="javascript", lines=25, interactive=True)
with gr.Tab("style.css"):
tjs_css_code = gr.Code(language="css", lines=25, interactive=True)
# Deployment section
with gr.Group(elem_classes=["deployment-section"], visible=False) as deployment_section:
gr.Markdown("### π Deploy Your Application")
with gr.Row():
space_name_input = gr.Textbox(
label="App Name",
placeholder="my-awesome-app",
scale=2
)
sdk_dropdown = gr.Dropdown(
choices=["Static (HTML)", "Gradio (Python)", "Streamlit (Python)", "Transformers.js", "Svelte"],
value="Static (HTML)",
label="App Type",
scale=1
)
with gr.Row():
deploy_btn = gr.Button("π Deploy to Spaces", variant="primary", scale=2)
deploy_status = gr.Markdown("", scale=3)
# Hidden components for state management
history_output = gr.Chatbot(visible=False, type="messages")
# Event handlers
def on_model_change(model_name):
for m in AVAILABLE_MODELS:
if m['name'] == model_name:
return m, gr.update(value=m['description']), update_image_input_visibility(m)
return AVAILABLE_MODELS[0], gr.update(value=AVAILABLE_MODELS[0]['description']), gr.update(visible=False)
def on_demo_click(demo_index):
if 0 <= demo_index < len(DEMO_LIST):
return DEMO_LIST[demo_index]['description']
return ""
def toggle_media_prompts(image_gen, img2img, img2vid, txt2vid, txt2music):
return [
gr.update(visible=image_gen), # text_to_image_prompt
gr.update(visible=img2img), # image_to_image_prompt
gr.update(visible=img2img or img2vid), # generation_image
]
def show_deployment_section():
return gr.update(visible=True)
def handle_import_project(url):
if not url.strip():
return gr.update(value="Please enter a URL.", visible=True), "", ""
status, code = load_project_from_url(url)
return gr.update(value=status, visible=True), code, gr.update(value="", visible=False)
# Wire up events
model_dropdown.change(
on_model_change,
inputs=[model_dropdown],
outputs=[current_model, model_info, vlm_image]
)
# Demo card clicks
for i, card in enumerate(demo_cards):
card.click(
lambda idx=i: on_demo_click(idx),
outputs=[user_input]
)
# Media generation toggles
for toggle in [enable_image_generation, enable_image_to_image, enable_image_to_video]:
toggle.change(
toggle_media_prompts,
inputs=[enable_image_generation, enable_image_to_image, enable_image_to_video, enable_text_to_video, enable_text_to_music],
outputs=[text_to_image_prompt, image_to_image_prompt, generation_image]
)
# Main generation
generate_btn.click(
generation_code,
inputs=[
user_input, vlm_image, generation_image, file_input, website_url_input,
setting, history, current_model, enable_search, language_dropdown,
gr.State("auto"), enable_image_generation, enable_image_to_image,
image_to_image_prompt, text_to_image_prompt, enable_image_to_video,
gr.State(None), enable_text_to_video, gr.State(None), enable_text_to_music, gr.State(None)
],
outputs=[code_output, history, sandbox, history_output]
).then(
show_deployment_section,
outputs=[deployment_section]
)
# Project import
load_project_btn.click(
handle_import_project,
inputs=[load_project_url],
outputs=[load_project_status, code_output, load_project_url]
)
# Clear functionality
clear_btn.click(
clear_history,
outputs=[history, history_output, file_input, website_url_input]
)
# Deployment
deploy_btn.click(
deploy_to_user_space,
inputs=[code_output, space_name_input, sdk_dropdown],
outputs=[deploy_status]
)
return demo
# Main application entry point
if __name__ == "__main__":
# Clean up any orphaned temporary files
cleanup_all_temp_media()
# Create and launch the application
demo = create_advanced_ui()
demo.queue(api_open=False, default_concurrency_limit=20).launch(
show_api=False,
server_name="0.0.0.0",
server_port=7860,
ssr_mode=True
) |