yeye / main.py
mgbam's picture
Create main.py
0131ae7 verified
raw
history blame
33.2 kB
"""
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
)