|
""" |
|
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 |
|
|
|
|
|
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 |
|
) |
|
|
|
|
|
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 = [] |
|
|
|
|
|
if not isinstance(_history, list): |
|
_history = [] |
|
_history = [h for h in _history if isinstance(h, list) and len(h) == 2] |
|
|
|
|
|
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()) |
|
|
|
|
|
try: |
|
cleanup_session_media(session_id) |
|
reap_old_media() |
|
except Exception: |
|
pass |
|
|
|
|
|
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 |
|
|
|
|
|
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} |
|
] |
|
|
|
|
|
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 |
|
|
|
|
|
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 modified_content != last_assistant_msg: |
|
_history.append([query, modified_content]) |
|
|
|
|
|
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}") |
|
|
|
|
|
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) |
|
|
|
|
|
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}" |
|
|
|
|
|
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}" |
|
|
|
|
|
enhanced_query = enhance_query_with_search(query, enable_search) |
|
|
|
|
|
if vlm_image is not None: |
|
messages.append(create_multimodal_message(enhanced_query, vlm_image)) |
|
else: |
|
messages.append({'role': 'user', 'content': enhanced_query}) |
|
|
|
|
|
try: |
|
client = get_inference_client(_current_model["id"], provider) |
|
|
|
|
|
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: |
|
|
|
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 |
|
|
|
|
|
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_content = remove_code_block(content) |
|
|
|
|
|
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]) |
|
|
|
|
|
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""" |
|
|
|
|
|
current_theme_name = get_saved_theme() |
|
current_theme = THEME_CONFIGS[current_theme_name]["theme"] |
|
|
|
|
|
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; |
|
} |
|
""" |
|
|
|
|
|
with gr.Blocks( |
|
title="AnyCoder - Advanced AI Code Generator", |
|
theme=current_theme, |
|
css=custom_css |
|
) as demo: |
|
|
|
|
|
history = gr.State([]) |
|
setting = gr.State({"system": from config import HTML_SYSTEM_PROMPT}) |
|
current_model = gr.State(DEFAULT_MODEL) |
|
|
|
|
|
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> |
|
""") |
|
|
|
|
|
with gr.Row(): |
|
|
|
with gr.Column(scale=1, elem_classes=["advanced-sidebar"]) as sidebar: |
|
|
|
login_button = gr.LoginButton() |
|
|
|
|
|
with gr.Accordion("π€ Model Selection", open=True): |
|
|
|
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 = gr.Markdown(DEFAULT_MODEL['description']) |
|
|
|
|
|
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) |
|
|
|
|
|
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> |
|
""") |
|
|
|
|
|
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" |
|
) |
|
|
|
|
|
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" |
|
) |
|
|
|
|
|
with gr.Row(): |
|
generate_btn = gr.Button("π Generate", variant="primary", scale=2) |
|
clear_btn = gr.Button("ποΈ Clear", variant="secondary", scale=1) |
|
|
|
|
|
with gr.Column(scale=3): |
|
|
|
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 = [] |
|
for i, demo in enumerate(DEMO_LIST[:6]): |
|
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>") |
|
|
|
|
|
with gr.Tabs() as main_tabs: |
|
|
|
with gr.Tab("π₯οΈ Live Preview"): |
|
sandbox = gr.HTML( |
|
label="Live Preview", |
|
elem_classes=["preview-container"] |
|
) |
|
|
|
|
|
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"] |
|
) |
|
|
|
|
|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
history_output = gr.Chatbot(visible=False, type="messages") |
|
|
|
|
|
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), |
|
gr.update(visible=img2img), |
|
gr.update(visible=img2img or img2vid), |
|
] |
|
|
|
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) |
|
|
|
|
|
model_dropdown.change( |
|
on_model_change, |
|
inputs=[model_dropdown], |
|
outputs=[current_model, model_info, vlm_image] |
|
) |
|
|
|
|
|
for i, card in enumerate(demo_cards): |
|
card.click( |
|
lambda idx=i: on_demo_click(idx), |
|
outputs=[user_input] |
|
) |
|
|
|
|
|
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] |
|
) |
|
|
|
|
|
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] |
|
) |
|
|
|
|
|
load_project_btn.click( |
|
handle_import_project, |
|
inputs=[load_project_url], |
|
outputs=[load_project_status, code_output, load_project_url] |
|
) |
|
|
|
|
|
clear_btn.click( |
|
clear_history, |
|
outputs=[history, history_output, file_input, website_url_input] |
|
) |
|
|
|
|
|
deploy_btn.click( |
|
deploy_to_user_space, |
|
inputs=[code_output, space_name_input, sdk_dropdown], |
|
outputs=[deploy_status] |
|
) |
|
|
|
return demo |
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
cleanup_all_temp_media() |
|
|
|
|
|
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 |
|
) |