akhaliq HF Staff commited on
Commit
715bb35
Β·
1 Parent(s): df3c3c8

major update

Browse files
anycoder_app/__init__.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AnyCoder - AI Code Generator Package
3
+ Modular structure for better code organization and maintainability.
4
+ """
5
+
6
+ __version__ = "1.0.0"
7
+
8
+ from . import config
9
+ from . import prompts
10
+ from . import docs_manager
11
+ from . import models
12
+ from . import parsers
13
+ from . import deploy
14
+ from . import themes
15
+ from . import ui
16
+
17
+ __all__ = [
18
+ "config",
19
+ "prompts",
20
+ "docs_manager",
21
+ "models",
22
+ "parsers",
23
+ "deploy",
24
+ "themes",
25
+ "ui",
26
+ ]
27
+
anycoder_app/config.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration constants for AnyCoder application.
3
+ """
4
+ import os
5
+ from datetime import datetime
6
+ from typing import Optional
7
+
8
+ # Gradio supported languages for syntax highlighting
9
+ GRADIO_SUPPORTED_LANGUAGES = [
10
+ "python", "json", "html", "javascript"
11
+ ]
12
+
13
+ # Search/Replace Constants
14
+ SEARCH_START = "<<<<<<< SEARCH"
15
+ DIVIDER = "======="
16
+ REPLACE_END = ">>>>>>> REPLACE"
17
+
18
+ # Gradio Documentation Auto-Update System
19
+ GRADIO_LLMS_TXT_URL = "https://www.gradio.app/llms.txt"
20
+ GRADIO_DOCS_CACHE_FILE = ".gradio_docs_cache.txt"
21
+ GRADIO_DOCS_LAST_UPDATE_FILE = ".gradio_docs_last_update.txt"
22
+ GRADIO_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
23
+
24
+ # Global variable to store the current Gradio documentation
25
+ _gradio_docs_content: Optional[str] = None
26
+ _gradio_docs_last_fetched: Optional[datetime] = None
27
+
28
+ # ComfyUI Documentation Auto-Update System
29
+ COMFYUI_LLMS_TXT_URL = "https://docs.comfy.org/llms.txt"
30
+ COMFYUI_DOCS_CACHE_FILE = ".comfyui_docs_cache.txt"
31
+ COMFYUI_DOCS_LAST_UPDATE_FILE = ".comfyui_docs_last_update.txt"
32
+ COMFYUI_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
33
+
34
+ # Global variable to store the current ComfyUI documentation
35
+ _comfyui_docs_content: Optional[str] = None
36
+ _comfyui_docs_last_fetched: Optional[datetime] = None
37
+
38
+ # FastRTC Documentation Auto-Update System
39
+ FASTRTC_LLMS_TXT_URL = "https://fastrtc.org/llms.txt"
40
+ FASTRTC_DOCS_CACHE_FILE = ".fastrtc_docs_cache.txt"
41
+ FASTRTC_DOCS_LAST_UPDATE_FILE = ".fastrtc_docs_last_update.txt"
42
+ FASTRTC_DOCS_UPDATE_ON_APP_UPDATE = True # Only update when app is updated, not on a timer
43
+
44
+ # Global variable to store the current FastRTC documentation
45
+ _fastrtc_docs_content: Optional[str] = None
46
+ _fastrtc_docs_last_fetched: Optional[datetime] = None
47
+
48
+ # Available Models Configuration
49
+ AVAILABLE_MODELS = [
50
+ {
51
+ "name": "DeepSeek V3.2-Exp",
52
+ "id": "deepseek-ai/DeepSeek-V3.2-Exp",
53
+ "description": "DeepSeek V3.2 Experimental model for cutting-edge code generation and reasoning"
54
+ },
55
+ {
56
+ "name": "DeepSeek R1",
57
+ "id": "deepseek-ai/DeepSeek-R1-0528",
58
+ "description": "DeepSeek R1 model for code generation"
59
+ },
60
+ {
61
+ "name": "GLM-4.6",
62
+ "id": "zai-org/GLM-4.6",
63
+ "description": "GLM-4.6 model for advanced code generation and general tasks"
64
+ },
65
+ {
66
+ "name": "Gemini Flash Latest",
67
+ "id": "gemini-flash-latest",
68
+ "description": "Google Gemini Flash Latest model via native Gemini API"
69
+ },
70
+ {
71
+ "name": "Gemini Flash Lite Latest",
72
+ "id": "gemini-flash-lite-latest",
73
+ "description": "Google Gemini Flash Lite Latest model via OpenAI-compatible API"
74
+ },
75
+ {
76
+ "name": "GPT-5",
77
+ "id": "gpt-5",
78
+ "description": "OpenAI GPT-5 model for advanced code generation and general tasks"
79
+ },
80
+ {
81
+ "name": "Grok-4",
82
+ "id": "grok-4",
83
+ "description": "Grok-4 model via Poe (OpenAI-compatible) for advanced tasks"
84
+ },
85
+ {
86
+ "name": "Grok-Code-Fast-1",
87
+ "id": "Grok-Code-Fast-1",
88
+ "description": "Grok-Code-Fast-1 model via Poe (OpenAI-compatible) for fast code generation"
89
+ },
90
+ {
91
+ "name": "Claude-Opus-4.1",
92
+ "id": "claude-opus-4.1",
93
+ "description": "Anthropic Claude Opus 4.1 via Poe (OpenAI-compatible)"
94
+ },
95
+ {
96
+ "name": "Claude-Sonnet-4.5",
97
+ "id": "claude-sonnet-4.5",
98
+ "description": "Anthropic Claude Sonnet 4.5 via Poe (OpenAI-compatible)"
99
+ },
100
+ {
101
+ "name": "Claude-Haiku-4.5",
102
+ "id": "claude-haiku-4.5",
103
+ "description": "Anthropic Claude Haiku 4.5 via Poe (OpenAI-compatible)"
104
+ },
105
+ {
106
+ "name": "Qwen3 Max Preview",
107
+ "id": "qwen3-max-preview",
108
+ "description": "Qwen3 Max Preview model via DashScope International API"
109
+ },
110
+ {
111
+ "name": "MiniMax M2",
112
+ "id": "MiniMaxAI/MiniMax-M2",
113
+ "description": "MiniMax M2 model via HuggingFace InferenceClient with Novita provider"
114
+ },
115
+ {
116
+ "name": "Kimi K2 Thinking",
117
+ "id": "moonshotai/Kimi-K2-Thinking",
118
+ "description": "Moonshot Kimi K2 Thinking model for advanced reasoning and code generation"
119
+ }
120
+ ]
121
+
122
+ k2_model_name_tag = "moonshotai/Kimi-K2-Thinking"
123
+
124
+ # Default model selection
125
+ DEFAULT_MODEL_NAME = "Kimi K2 Thinking"
126
+ DEFAULT_MODEL = None
127
+ for _m in AVAILABLE_MODELS:
128
+ if _m.get("name") == DEFAULT_MODEL_NAME:
129
+ DEFAULT_MODEL = _m
130
+ break
131
+ if DEFAULT_MODEL is None and AVAILABLE_MODELS:
132
+ DEFAULT_MODEL = AVAILABLE_MODELS[0]
133
+
134
+ # HF Inference Client
135
+ HF_TOKEN = os.getenv('HF_TOKEN')
136
+ # Note: HF_TOKEN is checked at runtime when needed, not at import time
137
+
138
+ # Language choices for code generation
139
+ LANGUAGE_CHOICES = [
140
+ "html", "gradio", "transformers.js", "streamlit", "comfyui", "react"
141
+ ]
142
+
143
+
144
+ def get_gradio_language(language):
145
+ """Map composite options to a supported syntax highlighting."""
146
+ if language == "streamlit":
147
+ return "python"
148
+ if language == "gradio":
149
+ return "python"
150
+ if language == "comfyui":
151
+ return "json"
152
+ if language == "react":
153
+ return "javascript"
154
+ return language if language in GRADIO_SUPPORTED_LANGUAGES else None
155
+
anycoder_app/deploy.py ADDED
@@ -0,0 +1,1852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Deployment utilities for publishing to HuggingFace Spaces.
3
+ Handles authentication, space creation, and code deployment.
4
+ """
5
+ import os
6
+ import re
7
+ import json
8
+ import uuid
9
+ import tempfile
10
+ import shutil
11
+ from typing import Dict, List, Optional, Tuple
12
+ from urllib.parse import urlparse
13
+ import requests
14
+ from bs4 import BeautifulSoup
15
+ import html2text
16
+
17
+ import gradio as gr
18
+ from huggingface_hub import HfApi, InferenceClient
19
+ from openai import OpenAI
20
+
21
+ from .config import HF_TOKEN, get_gradio_language
22
+ from .parsers import (
23
+ parse_transformers_js_output, parse_multipage_html_output,
24
+ parse_multi_file_python_output, parse_react_output,
25
+ remove_code_block, is_streamlit_code, is_gradio_code,
26
+ clean_requirements_txt_content, History,
27
+ format_transformers_js_output, build_transformers_inline_html,
28
+ send_transformers_to_sandbox, validate_and_autofix_files,
29
+ inline_multipage_into_single_preview, apply_search_replace_changes,
30
+ apply_transformers_js_search_replace_changes, send_to_sandbox,
31
+ format_multi_file_python_output, send_streamlit_to_stlite,
32
+ send_gradio_to_lite, extract_html_document
33
+ )
34
+ from .models import (
35
+ get_inference_client, get_real_model_id, history_to_messages,
36
+ history_to_chatbot_messages, strip_placeholder_thinking,
37
+ is_placeholder_thinking_only, extract_last_thinking_line
38
+ )
39
+ from .prompts import (
40
+ HTML_SYSTEM_PROMPT,
41
+ TRANSFORMERS_JS_SYSTEM_PROMPT, STREAMLIT_SYSTEM_PROMPT,
42
+ REACT_SYSTEM_PROMPT, REACT_FOLLOW_UP_SYSTEM_PROMPT,
43
+ GRADIO_SYSTEM_PROMPT, JSON_SYSTEM_PROMPT,
44
+ GENERIC_SYSTEM_PROMPT, MULTIPAGE_HTML_SYSTEM_PROMPT,
45
+ DYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPT,
46
+ FollowUpSystemPrompt, GradioFollowUpSystemPrompt,
47
+ TransformersJSFollowUpSystemPrompt
48
+ )
49
+ from .docs_manager import get_comfyui_system_prompt
50
+
51
+
52
+ def check_authentication(profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None) -> Tuple[bool, str]:
53
+ """Check if user is authenticated and return status with message."""
54
+ if not profile or not token:
55
+ return False, "Please log in with your Hugging Face account to use AnyCoder."
56
+
57
+ if not token.token:
58
+ return False, "Authentication token is invalid. Please log in again."
59
+
60
+ return True, f"Authenticated as {profile.username}"
61
+
62
+
63
+ def update_ui_for_auth_status(profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None):
64
+ """Update UI components based on authentication status."""
65
+ is_authenticated, auth_message = check_authentication(profile, token)
66
+
67
+ if is_authenticated:
68
+ # User is authenticated - enable all components
69
+ return (
70
+ gr.update(interactive=True, placeholder="Describe your application..."), # input
71
+ gr.update(interactive=True, variant="primary") # btn
72
+ )
73
+ else:
74
+ # User not authenticated - disable main components
75
+ return (
76
+ gr.update(
77
+ interactive=False,
78
+ placeholder="πŸ”’ Click Sign in with Hugging Face button to use AnyCoder for free"
79
+ ), # input
80
+ gr.update(interactive=False, variant="secondary") # btn
81
+ )
82
+
83
+
84
+ def generation_code(query: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, language: str = "html", provider: str = "auto", profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None, code_output=None, history_output=None, history=None):
85
+ # Check authentication first
86
+ is_authenticated, auth_message = check_authentication(profile, token)
87
+ if not is_authenticated:
88
+ error_message = f"πŸ”’ Authentication Required\n\n{auth_message}\n\nPlease click the 'Sign in with Hugging Face' button in the sidebar to continue."
89
+ if code_output is not None and history_output is not None:
90
+ yield {
91
+ code_output: error_message,
92
+ history_output: history_to_chatbot_messages(_history or []),
93
+ }
94
+ else:
95
+ yield (error_message, _history or [], history_to_chatbot_messages(_history or []))
96
+ return
97
+
98
+ if query is None:
99
+ query = ''
100
+ if _history is None:
101
+ _history = []
102
+ # Ensure _history is always a list of lists with at least 2 elements per item
103
+ if not isinstance(_history, list):
104
+ _history = []
105
+ _history = [h for h in _history if isinstance(h, list) and len(h) == 2]
106
+
107
+ # Check if there's existing content in history to determine if this is a modification request
108
+ has_existing_content = False
109
+ last_assistant_msg = ""
110
+ if _history and len(_history[-1]) > 1:
111
+ last_assistant_msg = _history[-1][1]
112
+ # Check for various content types that indicate an existing project
113
+ if ('<!DOCTYPE html>' in last_assistant_msg or
114
+ '<html' in last_assistant_msg or
115
+ 'import gradio' in last_assistant_msg or
116
+ 'import streamlit' in last_assistant_msg or
117
+ 'def ' in last_assistant_msg and 'app' in last_assistant_msg or
118
+ 'IMPORTED PROJECT FROM HUGGING FACE SPACE' in last_assistant_msg or
119
+ '=== index.html ===' in last_assistant_msg or
120
+ '=== index.js ===' in last_assistant_msg or
121
+ '=== style.css ===' in last_assistant_msg or
122
+ '=== app.py ===' in last_assistant_msg or
123
+ '=== requirements.txt ===' in last_assistant_msg):
124
+ has_existing_content = True
125
+
126
+ # If this is a modification request, try to apply search/replace first
127
+ if has_existing_content and query.strip():
128
+ try:
129
+ # Use the current model to generate search/replace instructions
130
+ client = get_inference_client(_current_model['id'], provider)
131
+
132
+ system_prompt = """You are a code editor assistant. Given existing code and modification instructions, generate EXACT search/replace blocks.
133
+
134
+ CRITICAL REQUIREMENTS:
135
+ 1. Use EXACTLY these markers: <<<<<<< SEARCH, =======, >>>>>>> REPLACE
136
+ 2. The SEARCH block must match the existing code EXACTLY (including whitespace, indentation, line breaks)
137
+ 3. The REPLACE block should contain the modified version
138
+ 4. Only include the specific lines that need to change, with enough context to make them unique
139
+ 5. Generate multiple search/replace blocks if needed for different changes
140
+ 6. Do NOT include any explanations or comments outside the blocks
141
+
142
+ Example format:
143
+ <<<<<<< SEARCH
144
+ function oldFunction() {
145
+ return "old";
146
+ }
147
+ =======
148
+ function newFunction() {
149
+ return "new";
150
+ }
151
+ >>>>>>> REPLACE"""
152
+
153
+ user_prompt = f"""Existing code:
154
+ {last_assistant_msg}
155
+ Modification instructions:
156
+ {query}
157
+
158
+ Generate the exact search/replace blocks needed to make these changes."""
159
+
160
+ messages = [
161
+ {"role": "system", "content": system_prompt},
162
+ {"role": "user", "content": user_prompt}
163
+ ]
164
+
165
+ # Generate search/replace instructions
166
+ if _current_model.get('type') == 'openai':
167
+ response = client.chat.completions.create(
168
+ model=get_real_model_id(_current_model['id']),
169
+ messages=messages,
170
+ max_tokens=4000,
171
+ temperature=0.1
172
+ )
173
+ changes_text = response.choices[0].message.content
174
+ elif _current_model.get('type') == 'mistral':
175
+ response = client.chat.complete(
176
+ model=get_real_model_id(_current_model['id']),
177
+ messages=messages,
178
+ max_tokens=4000,
179
+ temperature=0.1
180
+ )
181
+ changes_text = response.choices[0].message.content
182
+ else: # Hugging Face or other
183
+ completion = client.chat.completions.create(
184
+ model=get_real_model_id(_current_model['id']),
185
+ messages=messages,
186
+ max_tokens=4000,
187
+ temperature=0.1
188
+ )
189
+ changes_text = completion.choices[0].message.content
190
+
191
+ # Apply the search/replace changes
192
+ if language == "transformers.js" and ('=== index.html ===' in last_assistant_msg):
193
+ modified_content = apply_transformers_js_search_replace_changes(last_assistant_msg, changes_text)
194
+ else:
195
+ modified_content = apply_search_replace_changes(last_assistant_msg, changes_text)
196
+
197
+ # If changes were successfully applied, return the modified content
198
+ if modified_content != last_assistant_msg:
199
+ _history.append([query, modified_content])
200
+
201
+ # Generate deployment message instead of preview
202
+ deploy_message = f"""
203
+ <div style='padding: 1.5em; text-align: center; background: #f0f9ff; border: 2px solid #0ea5e9; border-radius: 10px; color: #0c4a6e;'>
204
+ <h3 style='margin-top: 0; color: #0ea5e9;'>βœ… Code Updated Successfully!</h3>
205
+ <p style='margin: 0.5em 0; font-size: 1.1em;'>Your {language.upper()} code has been modified and is ready for deployment.</p>
206
+ <p style='margin: 0.5em 0; font-weight: bold;'>πŸ‘‰ Use the Deploy button in the sidebar to publish your app!</p>
207
+ </div>
208
+ """
209
+
210
+ yield {
211
+ code_output: modified_content,
212
+ history: _history,
213
+ history_output: history_to_chatbot_messages(_history),
214
+ }
215
+ return
216
+
217
+ except Exception as e:
218
+ print(f"Search/replace failed, falling back to normal generation: {e}")
219
+ # If search/replace fails, continue with normal generation
220
+
221
+ # Create/lookup a session id for temp-file tracking and cleanup
222
+ if _setting is not None and isinstance(_setting, dict):
223
+ session_id = _setting.get("__session_id__")
224
+ if not session_id:
225
+ session_id = str(uuid.uuid4())
226
+ _setting["__session_id__"] = session_id
227
+ else:
228
+ session_id = str(uuid.uuid4())
229
+
230
+ # Update Gradio system prompts if needed
231
+ if language == "gradio":
232
+ update_gradio_system_prompts()
233
+
234
+ # Choose system prompt based on context
235
+ # Special case: If user is asking about model identity, use neutral prompt
236
+ if query and any(phrase in query.lower() for phrase in ["what model are you", "who are you", "identify yourself", "what ai are you", "which model"]):
237
+ system_prompt = "You are a helpful AI assistant. Please respond truthfully about your identity and capabilities."
238
+ elif has_existing_content:
239
+ # Use follow-up prompt for modifying existing content
240
+ if language == "transformers.js":
241
+ system_prompt = TransformersJSFollowUpSystemPrompt
242
+ elif language == "gradio":
243
+ system_prompt = GradioFollowUpSystemPrompt
244
+ elif language == "react":
245
+ system_prompt = REACT_FOLLOW_UP_SYSTEM_PROMPT
246
+ else:
247
+ system_prompt = FollowUpSystemPrompt
248
+ else:
249
+ # Use language-specific prompt
250
+ if language == "html":
251
+ # Dynamic file selection always enabled
252
+ system_prompt = DYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPT
253
+ elif language == "transformers.js":
254
+ system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT
255
+ elif language == "react":
256
+ system_prompt = REACT_SYSTEM_PROMPT
257
+ elif language == "gradio":
258
+ system_prompt = GRADIO_SYSTEM_PROMPT
259
+ elif language == "streamlit":
260
+ system_prompt = STREAMLIT_SYSTEM_PROMPT
261
+ elif language == "json":
262
+ system_prompt = JSON_SYSTEM_PROMPT
263
+ elif language == "comfyui":
264
+ system_prompt = get_comfyui_system_prompt()
265
+ else:
266
+ system_prompt = GENERIC_SYSTEM_PROMPT.format(language=language)
267
+
268
+ messages = history_to_messages(_history, system_prompt)
269
+
270
+
271
+
272
+ # Use the original query without search enhancement
273
+ enhanced_query = query
274
+
275
+ # Check if this is GLM-4.5 model and handle with simple HuggingFace InferenceClient
276
+ if _current_model["id"] == "zai-org/GLM-4.5":
277
+ messages.append({'role': 'user', 'content': enhanced_query})
278
+
279
+ try:
280
+ client = InferenceClient(
281
+ provider="auto",
282
+ api_key=os.environ["HF_TOKEN"],
283
+ bill_to="huggingface",
284
+ )
285
+
286
+ stream = client.chat.completions.create(
287
+ model="zai-org/GLM-4.5",
288
+ messages=messages,
289
+ stream=True,
290
+ max_tokens=16384,
291
+ )
292
+
293
+ content = ""
294
+ for chunk in stream:
295
+ if chunk.choices[0].delta.content:
296
+ content += chunk.choices[0].delta.content
297
+ clean_code = remove_code_block(content)
298
+ # Show generation progress message
299
+ progress_message = f"""
300
+ <div style='padding: 1.5em; text-align: center; background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); color: white; border-radius: 10px;'>
301
+ <h3 style='margin-top: 0; color: white;'>⚑ Generating Your {language.upper()} App...</h3>
302
+ <p style='margin: 0.5em 0; opacity: 0.9;'>Code is being generated in real-time!</p>
303
+ <div style='background: rgba(255,255,255,0.2); padding: 1em; border-radius: 8px; margin: 1em 0;'>
304
+ <p style='margin: 0; font-size: 1.1em;'>Get ready to deploy once generation completes!</p>
305
+ </div>
306
+ </div>
307
+ """
308
+ yield {
309
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
310
+ history_output: history_to_chatbot_messages(_history),
311
+ }
312
+
313
+ except Exception as e:
314
+ content = f"Error with GLM-4.5: {str(e)}\n\nPlease make sure HF_TOKEN environment variable is set."
315
+
316
+ clean_code = remove_code_block(content)
317
+
318
+ # Use clean code as final content without media generation
319
+ final_content = clean_code
320
+
321
+ _history.append([query, final_content])
322
+
323
+ if language == "transformers.js":
324
+ files = parse_transformers_js_output(clean_code)
325
+ if files['index.html'] and files['index.js'] and files['style.css']:
326
+ formatted_output = format_transformers_js_output(files)
327
+ yield {
328
+ code_output: formatted_output,
329
+ history: _history,
330
+ history_output: history_to_chatbot_messages(_history),
331
+ }
332
+ else:
333
+ yield {
334
+ code_output: clean_code,
335
+ history: _history,
336
+ history_output: history_to_chatbot_messages(_history),
337
+ }
338
+ else:
339
+ if has_existing_content and not (clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html")):
340
+ last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""
341
+ modified_content = apply_search_replace_changes(last_content, clean_code)
342
+ clean_content = remove_code_block(modified_content)
343
+
344
+ # Use clean content without media generation
345
+
346
+ yield {
347
+ code_output: clean_content,
348
+ history: _history,
349
+ history_output: history_to_chatbot_messages(_history),
350
+ }
351
+ else:
352
+ # Use clean code as final content without media generation
353
+ final_content = clean_code
354
+
355
+ # Generate deployment message instead of preview
356
+ deploy_message = f"""
357
+ <div style='padding: 2em; text-align: center; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(16, 185, 129, 0.3);'>
358
+ <h2 style='margin-top: 0; font-size: 2em;'>πŸŽ‰ Code Generated Successfully!</h2>
359
+ <p style='font-size: 1.2em; margin: 1em 0; opacity: 0.95;'>Your {language.upper()} application is ready to deploy!</p>
360
+
361
+ <div style='background: rgba(255,255,255,0.15); padding: 1.5em; border-radius: 10px; margin: 1.5em 0;'>
362
+ <h3 style='margin-top: 0; font-size: 1.3em;'>πŸš€ Next Steps:</h3>
363
+ <div style='text-align: left; max-width: 500px; margin: 0 auto;'>
364
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
365
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>1</span>
366
+ Use the <strong>Deploy button</strong> in the sidebar
367
+ </p>
368
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
369
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>2</span>
370
+ Enter your app name below
371
+ </p>
372
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
373
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>3</span>
374
+ Click <strong>"Publish"</strong>
375
+ </p>
376
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
377
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>4</span>
378
+ Share your creation! 🌍
379
+ </p>
380
+ </div>
381
+ </div>
382
+
383
+ <p style='font-size: 1em; opacity: 0.9; margin-bottom: 0;'>
384
+ πŸ’‘ Your app will be live on Hugging Face Spaces in seconds!
385
+ </p>
386
+ </div>
387
+ """
388
+
389
+ yield {
390
+ code_output: final_content,
391
+ history: _history,
392
+ history_output: history_to_chatbot_messages(_history),
393
+ }
394
+ return
395
+
396
+ # Use dynamic client based on selected model
397
+ client = get_inference_client(_current_model["id"], provider)
398
+
399
+ messages.append({'role': 'user', 'content': enhanced_query})
400
+ try:
401
+ # Handle Mistral API method difference
402
+ if _current_model["id"] in ("codestral-2508", "mistral-medium-2508"):
403
+ completion = client.chat.stream(
404
+ model=get_real_model_id(_current_model["id"]),
405
+ messages=messages,
406
+ max_tokens=16384
407
+ )
408
+
409
+ else:
410
+ # Poe expects model id "GPT-5" and uses max_tokens
411
+ if _current_model["id"] == "gpt-5":
412
+ completion = client.chat.completions.create(
413
+ model="GPT-5",
414
+ messages=messages,
415
+ stream=True,
416
+ max_tokens=16384
417
+ )
418
+ elif _current_model["id"] == "grok-4":
419
+ completion = client.chat.completions.create(
420
+ model="Grok-4",
421
+ messages=messages,
422
+ stream=True,
423
+ max_tokens=16384
424
+ )
425
+ elif _current_model["id"] == "claude-opus-4.1":
426
+ completion = client.chat.completions.create(
427
+ model="Claude-Opus-4.1",
428
+ messages=messages,
429
+ stream=True,
430
+ max_tokens=16384
431
+ )
432
+ elif _current_model["id"] == "claude-sonnet-4.5":
433
+ completion = client.chat.completions.create(
434
+ model="Claude-Sonnet-4.5",
435
+ messages=messages,
436
+ stream=True,
437
+ max_tokens=16384
438
+ )
439
+ elif _current_model["id"] == "claude-haiku-4.5":
440
+ completion = client.chat.completions.create(
441
+ model="Claude-Haiku-4.5",
442
+ messages=messages,
443
+ stream=True,
444
+ max_tokens=16384
445
+ )
446
+ else:
447
+ completion = client.chat.completions.create(
448
+ model=get_real_model_id(_current_model["id"]),
449
+ messages=messages,
450
+ stream=True,
451
+ max_tokens=16384
452
+ )
453
+ content = ""
454
+ # For Poe/GPT-5, maintain a simple code-fence state machine to only accumulate code
455
+ poe_inside_code_block = False
456
+ poe_partial_buffer = ""
457
+ for chunk in completion:
458
+ # Handle different response formats for Mistral vs others
459
+ chunk_content = None
460
+ if _current_model["id"] in ("codestral-2508", "mistral-medium-2508"):
461
+ # Mistral format: chunk.data.choices[0].delta.content
462
+ if (
463
+ hasattr(chunk, "data") and chunk.data and
464
+ hasattr(chunk.data, "choices") and chunk.data.choices and
465
+ hasattr(chunk.data.choices[0], "delta") and
466
+ hasattr(chunk.data.choices[0].delta, "content") and
467
+ chunk.data.choices[0].delta.content is not None
468
+ ):
469
+ chunk_content = chunk.data.choices[0].delta.content
470
+ else:
471
+ # OpenAI format: chunk.choices[0].delta.content
472
+ if (
473
+ hasattr(chunk, "choices") and chunk.choices and
474
+ hasattr(chunk.choices[0], "delta") and
475
+ hasattr(chunk.choices[0].delta, "content") and
476
+ chunk.choices[0].delta.content is not None
477
+ ):
478
+ chunk_content = chunk.choices[0].delta.content
479
+
480
+ if chunk_content:
481
+ # Ensure chunk_content is always a string to avoid regex errors
482
+ if not isinstance(chunk_content, str):
483
+ # Handle structured thinking chunks (like ThinkChunk objects from magistral)
484
+ chunk_str = str(chunk_content) if chunk_content is not None else ""
485
+ if '[ThinkChunk(' in chunk_str:
486
+ # This is a structured thinking chunk, skip it to avoid polluting output
487
+ continue
488
+ chunk_content = chunk_str
489
+ if _current_model["id"] == "gpt-5":
490
+ # If this chunk is only placeholder thinking, surface a status update without polluting content
491
+ if is_placeholder_thinking_only(chunk_content):
492
+ status_line = extract_last_thinking_line(chunk_content)
493
+ yield {
494
+ code_output: gr.update(value=(content or "") + "\n<!-- " + status_line + " -->", language="html"),
495
+ history_output: history_to_chatbot_messages(_history),
496
+ }
497
+ continue
498
+ # Filter placeholders
499
+ incoming = strip_placeholder_thinking(chunk_content)
500
+ # Process code fences incrementally, only keep content inside fences
501
+ s = poe_partial_buffer + incoming
502
+ append_text = ""
503
+ i = 0
504
+ # Find all triple backticks positions
505
+ for m in re.finditer(r"```", s):
506
+ if not poe_inside_code_block:
507
+ # Opening fence. Require a newline to confirm full opener so we can skip optional language line
508
+ nl = s.find("\n", m.end())
509
+ if nl == -1:
510
+ # Incomplete opener; buffer from this fence and wait for more
511
+ poe_partial_buffer = s[m.start():]
512
+ s = None
513
+ break
514
+ # Enter code, skip past newline after optional language token
515
+ poe_inside_code_block = True
516
+ i = nl + 1
517
+ else:
518
+ # Closing fence, append content inside and exit code
519
+ append_text += s[i:m.start()]
520
+ poe_inside_code_block = False
521
+ i = m.end()
522
+ if s is not None:
523
+ if poe_inside_code_block:
524
+ append_text += s[i:]
525
+ poe_partial_buffer = ""
526
+ else:
527
+ poe_partial_buffer = s[i:]
528
+ if append_text:
529
+ content += append_text
530
+ else:
531
+ # Append content, filtering out placeholder thinking lines
532
+ content += strip_placeholder_thinking(chunk_content)
533
+ search_status = ""
534
+
535
+ # Handle transformers.js output differently
536
+ if language == "transformers.js":
537
+ files = parse_transformers_js_output(content)
538
+
539
+ # Stream ALL code by merging current parts into a single HTML (inline CSS & JS)
540
+ has_any_part = any([files.get('index.html'), files.get('index.js'), files.get('style.css')])
541
+ if has_any_part:
542
+ merged_html = build_transformers_inline_html(files)
543
+ preview_val = None
544
+ if files['index.html'] and files['index.js'] and files['style.css']:
545
+ preview_val = send_transformers_to_sandbox(files)
546
+ yield {
547
+ code_output: gr.update(value=merged_html, language="html"),
548
+ history_output: history_to_chatbot_messages(_history),
549
+ }
550
+ elif has_existing_content:
551
+ # Model is returning search/replace changes for transformers.js - apply them
552
+ last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""
553
+ modified_content = apply_transformers_js_search_replace_changes(last_content, content)
554
+ _mf = parse_transformers_js_output(modified_content)
555
+ yield {
556
+ code_output: gr.update(value=modified_content, language="html"),
557
+ history_output: history_to_chatbot_messages(_history),
558
+ }
559
+ else:
560
+ # Still streaming, show partial content
561
+ yield {
562
+ code_output: gr.update(value=content, language="html"),
563
+ history_output: history_to_chatbot_messages(_history),
564
+ }
565
+ else:
566
+ clean_code = remove_code_block(content)
567
+ if has_existing_content:
568
+ # Handle modification of existing content
569
+ if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):
570
+ # Model returned a complete HTML file
571
+ preview_val = None
572
+ if language == "html":
573
+ _mpc3 = parse_multipage_html_output(clean_code)
574
+ _mpc3 = validate_and_autofix_files(_mpc3)
575
+ preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc3)) if _mpc3.get('index.html') else send_to_sandbox(clean_code)
576
+ elif language == "python" and is_streamlit_code(clean_code):
577
+ preview_val = send_streamlit_to_stlite(clean_code)
578
+ elif language == "gradio" or (language == "python" and is_gradio_code(clean_code)):
579
+ preview_val = send_gradio_to_lite(clean_code)
580
+ yield {
581
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
582
+ history_output: history_to_chatbot_messages(_history),
583
+ }
584
+ else:
585
+ # Model returned search/replace changes - apply them
586
+ last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""
587
+ modified_content = apply_search_replace_changes(last_content, clean_code)
588
+ clean_content = remove_code_block(modified_content)
589
+ preview_val = None
590
+ if language == "html":
591
+ _mpc4 = parse_multipage_html_output(clean_content)
592
+ _mpc4 = validate_and_autofix_files(_mpc4)
593
+ preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc4)) if _mpc4.get('index.html') else send_to_sandbox(clean_content)
594
+ elif language == "python" and is_streamlit_code(clean_content):
595
+ preview_val = send_streamlit_to_stlite(clean_content)
596
+ elif language == "gradio" or (language == "python" and is_gradio_code(clean_content)):
597
+ preview_val = send_gradio_to_lite(clean_content)
598
+ yield {
599
+ code_output: gr.update(value=clean_content, language=get_gradio_language(language)),
600
+ history_output: history_to_chatbot_messages(_history),
601
+ }
602
+ else:
603
+ preview_val = None
604
+ if language == "html":
605
+ _mpc5 = parse_multipage_html_output(clean_code)
606
+ _mpc5 = validate_and_autofix_files(_mpc5)
607
+ preview_val = send_to_sandbox(inline_multipage_into_single_preview(_mpc5)) if _mpc5.get('index.html') else send_to_sandbox(clean_code)
608
+ elif language == "python" and is_streamlit_code(clean_code):
609
+ preview_val = send_streamlit_to_stlite(clean_code)
610
+ elif language == "gradio" or (language == "python" and is_gradio_code(clean_code)):
611
+ preview_val = send_gradio_to_lite(clean_code)
612
+ yield {
613
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
614
+ history_output: history_to_chatbot_messages(_history),
615
+ }
616
+ # Skip chunks with empty choices (end of stream)
617
+ # Do not treat as error
618
+ # Handle response based on whether this is a modification or new generation
619
+ if language == "transformers.js":
620
+ # Handle transformers.js output
621
+ files = parse_transformers_js_output(content)
622
+ if files['index.html'] and files['index.js'] and files['style.css']:
623
+ # Model returned complete transformers.js output
624
+ formatted_output = format_transformers_js_output(files)
625
+ _history.append([query, formatted_output])
626
+ yield {
627
+ code_output: formatted_output,
628
+ history: _history,
629
+ history_output: history_to_chatbot_messages(_history),
630
+ }
631
+ elif has_existing_content:
632
+ # Model returned search/replace changes for transformers.js - apply them
633
+ last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""
634
+ modified_content = apply_transformers_js_search_replace_changes(last_content, content)
635
+ _history.append([query, modified_content])
636
+ _mf = parse_transformers_js_output(modified_content)
637
+ yield {
638
+ code_output: modified_content,
639
+ history: _history,
640
+ history_output: history_to_chatbot_messages(_history),
641
+ }
642
+ else:
643
+ # Fallback if parsing failed
644
+ _history.append([query, content])
645
+ yield {
646
+ code_output: content,
647
+ history: _history,
648
+ history_output: history_to_chatbot_messages(_history),
649
+ }
650
+ elif language == "gradio":
651
+ # Handle Gradio output - check if it's multi-file format or single file
652
+ if ('=== app.py ===' in content or '=== requirements.txt ===' in content):
653
+ # Model returned multi-file Gradio output - ensure requirements.txt is present
654
+ files = parse_multi_file_python_output(content)
655
+ if files and 'app.py' in files:
656
+ # Check if requirements.txt is missing and auto-generate it
657
+ if 'requirements.txt' not in files:
658
+ import_statements = extract_import_statements(files['app.py'])
659
+ requirements_content = generate_requirements_txt_with_llm(import_statements)
660
+ files['requirements.txt'] = requirements_content
661
+
662
+ # Reformat with the auto-generated requirements.txt
663
+ content = format_multi_file_python_output(files)
664
+
665
+ _history.append([query, content])
666
+ yield {
667
+ code_output: content,
668
+ history: _history,
669
+ history_output: history_to_chatbot_messages(_history),
670
+ }
671
+ elif has_existing_content:
672
+ # Check if this is a followup that should maintain multi-file structure
673
+ last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""
674
+
675
+ # If the original was multi-file but the response isn't, try to convert it
676
+ if ('=== app.py ===' in last_content or '=== requirements.txt ===' in last_content):
677
+ # Original was multi-file, but response is single block - need to convert
678
+ if not ('=== app.py ===' in content or '=== requirements.txt ===' in content):
679
+ # Try to parse as single-block Gradio code and convert to multi-file format
680
+ clean_content = remove_code_block(content)
681
+ if 'import gradio' in clean_content or 'from gradio' in clean_content:
682
+ # This looks like Gradio code, convert to multi-file format
683
+ files = parse_multi_file_python_output(clean_content)
684
+ if not files:
685
+ # Single file - create multi-file structure
686
+ files = {'app.py': clean_content}
687
+
688
+ # Extract requirements from imports
689
+ import_statements = extract_import_statements(clean_content)
690
+ requirements_content = generate_requirements_txt_with_llm(import_statements)
691
+ files['requirements.txt'] = requirements_content
692
+
693
+ # Format as multi-file output
694
+ formatted_content = format_multi_file_python_output(files)
695
+ _history.append([query, formatted_content])
696
+ yield {
697
+ code_output: formatted_content,
698
+ history: _history,
699
+ history_output: history_to_chatbot_messages(_history),
700
+ }
701
+ else:
702
+ # Not Gradio code, apply search/replace
703
+ modified_content = apply_search_replace_changes(last_content, content)
704
+ _history.append([query, modified_content])
705
+ yield {
706
+ code_output: modified_content,
707
+ history: _history,
708
+ history_output: history_to_chatbot_messages(_history),
709
+ }
710
+ else:
711
+ # Response is already multi-file format
712
+ _history.append([query, content])
713
+ yield {
714
+ code_output: content,
715
+ history: _history,
716
+ history_output: history_to_chatbot_messages(_history),
717
+ }
718
+ else:
719
+ # Original was single file, apply search/replace
720
+ modified_content = apply_search_replace_changes(last_content, content)
721
+ _history.append([query, modified_content])
722
+ yield {
723
+ code_output: modified_content,
724
+ history: _history,
725
+ history_output: history_to_chatbot_messages(_history),
726
+ }
727
+ else:
728
+ # Fallback - treat as single file Gradio app
729
+ _history.append([query, content])
730
+ yield {
731
+ code_output: content,
732
+ history: _history,
733
+ history_output: history_to_chatbot_messages(_history),
734
+ }
735
+ elif has_existing_content:
736
+ # Handle modification of existing content
737
+ final_code = remove_code_block(content)
738
+ if final_code.strip().startswith("<!DOCTYPE html>") or final_code.strip().startswith("<html"):
739
+ # Model returned a complete HTML file
740
+ clean_content = final_code
741
+ else:
742
+ # Model returned search/replace changes - apply them
743
+ last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""
744
+ modified_content = apply_search_replace_changes(last_content, final_code)
745
+ clean_content = remove_code_block(modified_content)
746
+
747
+ # Use clean content without media generation
748
+
749
+ # Update history with the cleaned content
750
+ _history.append([query, clean_content])
751
+ yield {
752
+ code_output: clean_content,
753
+ history: _history,
754
+ history_output: history_to_chatbot_messages(_history),
755
+ }
756
+ else:
757
+ # Regular generation - use the content as is
758
+ final_content = remove_code_block(content)
759
+
760
+ # Use final content without media generation
761
+
762
+ _history.append([query, final_content])
763
+
764
+ # Generate deployment message instead of preview
765
+ deploy_message = f"""
766
+ <div style='padding: 2em; text-align: center; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(16, 185, 129, 0.3);'>
767
+ <h2 style='margin-top: 0; font-size: 2em;'>πŸŽ‰ Code Generated Successfully!</h2>
768
+ <p style='font-size: 1.2em; margin: 1em 0; opacity: 0.95;'>Your {language.upper()} application is ready to deploy!</p>
769
+
770
+ <div style='background: rgba(255,255,255,0.15); padding: 1.5em; border-radius: 10px; margin: 1.5em 0;'>
771
+ <h3 style='margin-top: 0; font-size: 1.3em;'>πŸš€ Next Steps:</h3>
772
+ <div style='text-align: left; max-width: 500px; margin: 0 auto;'>
773
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
774
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>1</span>
775
+ Use the <strong>Deploy button</strong> in the sidebar
776
+ </p>
777
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
778
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>2</span>
779
+ Enter your app name below
780
+ </p>
781
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
782
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>3</span>
783
+ Click <strong>"Publish"</strong>
784
+ </p>
785
+ <p style='margin: 0.8em 0; font-size: 1.1em; display: flex; align-items: center;'>
786
+ <span style='background: rgba(255,255,255,0.2); border-radius: 50%; width: 24px; height: 24px; display: inline-flex; align-items: center; justify-content: center; margin-right: 10px; font-weight: bold;'>4</span>
787
+ Share your creation! 🌍
788
+ </p>
789
+ </div>
790
+ </div>
791
+
792
+ <p style='font-size: 1em; opacity: 0.9; margin-bottom: 0;'>
793
+ πŸ’‘ Your app will be live on Hugging Face Spaces in seconds!
794
+ </p>
795
+ </div>
796
+ """
797
+
798
+ yield {
799
+ code_output: final_content,
800
+ history: _history,
801
+ history_output: history_to_chatbot_messages(_history),
802
+ }
803
+ except Exception as e:
804
+ error_message = f"Error: {str(e)}"
805
+ yield {
806
+ code_output: error_message,
807
+ history_output: history_to_chatbot_messages(_history),
808
+ }
809
+
810
+ # Deploy to Spaces logic
811
+
812
+ def add_anycoder_tag_to_readme(api, repo_id, app_port=None):
813
+ """Download existing README, add anycoder tag and app_port if needed, and upload back.
814
+
815
+ Args:
816
+ api: HuggingFace API client
817
+ repo_id: Repository ID
818
+ app_port: Optional port number to set for Docker spaces (e.g., 7860 for React apps)
819
+ """
820
+ try:
821
+ import tempfile
822
+ import re
823
+
824
+ # Download the existing README
825
+ readme_path = api.hf_hub_download(
826
+ repo_id=repo_id,
827
+ filename="README.md",
828
+ repo_type="space"
829
+ )
830
+
831
+ # Read the existing README content
832
+ with open(readme_path, 'r', encoding='utf-8') as f:
833
+ content = f.read()
834
+
835
+ # Parse frontmatter and content
836
+ if content.startswith('---'):
837
+ # Split frontmatter and body
838
+ parts = content.split('---', 2)
839
+ if len(parts) >= 3:
840
+ frontmatter = parts[1].strip()
841
+ body = parts[2] if len(parts) > 2 else ""
842
+
843
+ # Check if tags already exist
844
+ if 'tags:' in frontmatter:
845
+ # Add anycoder to existing tags if not present
846
+ if '- anycoder' not in frontmatter:
847
+ frontmatter = re.sub(r'(tags:\s*\n(?:\s*-\s*[^\n]+\n)*)', r'\1- anycoder\n', frontmatter)
848
+ else:
849
+ # Add tags section with anycoder
850
+ frontmatter += '\ntags:\n- anycoder'
851
+
852
+ # Add app_port if specified and not already present
853
+ if app_port is not None and 'app_port:' not in frontmatter:
854
+ frontmatter += f'\napp_port: {app_port}'
855
+
856
+ # Reconstruct the README
857
+ new_content = f"---\n{frontmatter}\n---{body}"
858
+ else:
859
+ # Malformed frontmatter, just add tags at the end of frontmatter
860
+ new_content = content.replace('---', '---\ntags:\n- anycoder\n---', 1)
861
+ else:
862
+ # No frontmatter, add it at the beginning
863
+ app_port_line = f'\napp_port: {app_port}' if app_port else ''
864
+ new_content = f"---\ntags:\n- anycoder{app_port_line}\n---\n\n{content}"
865
+
866
+ # Upload the modified README
867
+ with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False, encoding='utf-8') as f:
868
+ f.write(new_content)
869
+ temp_path = f.name
870
+
871
+ api.upload_file(
872
+ path_or_fileobj=temp_path,
873
+ path_in_repo="README.md",
874
+ repo_id=repo_id,
875
+ repo_type="space"
876
+ )
877
+
878
+ import os
879
+ os.unlink(temp_path)
880
+
881
+ except Exception as e:
882
+ print(f"Warning: Could not modify README.md to add anycoder tag: {e}")
883
+
884
+ def extract_import_statements(code):
885
+ """Extract import statements from generated code."""
886
+ import ast
887
+ import re
888
+
889
+ import_statements = []
890
+
891
+ # Built-in Python modules to exclude
892
+ builtin_modules = {
893
+ 'os', 'sys', 'json', 'time', 'datetime', 'random', 'math', 're', 'collections',
894
+ 'itertools', 'functools', 'pathlib', 'urllib', 'http', 'email', 'html', 'xml',
895
+ 'csv', 'tempfile', 'shutil', 'subprocess', 'threading', 'multiprocessing',
896
+ 'asyncio', 'logging', 'typing', 'base64', 'hashlib', 'secrets', 'uuid',
897
+ 'copy', 'pickle', 'io', 'contextlib', 'warnings', 'sqlite3', 'gzip', 'zipfile',
898
+ 'tarfile', 'socket', 'ssl', 'platform', 'getpass', 'pwd', 'grp', 'stat',
899
+ 'glob', 'fnmatch', 'linecache', 'traceback', 'inspect', 'keyword', 'token',
900
+ 'tokenize', 'ast', 'code', 'codeop', 'dis', 'py_compile', 'compileall',
901
+ 'importlib', 'pkgutil', 'modulefinder', 'runpy', 'site', 'sysconfig'
902
+ }
903
+
904
+ try:
905
+ # Try to parse as Python AST
906
+ tree = ast.parse(code)
907
+
908
+ for node in ast.walk(tree):
909
+ if isinstance(node, ast.Import):
910
+ for alias in node.names:
911
+ module_name = alias.name.split('.')[0]
912
+ if module_name not in builtin_modules and not module_name.startswith('_'):
913
+ import_statements.append(f"import {alias.name}")
914
+
915
+ elif isinstance(node, ast.ImportFrom):
916
+ if node.module:
917
+ module_name = node.module.split('.')[0]
918
+ if module_name not in builtin_modules and not module_name.startswith('_'):
919
+ names = [alias.name for alias in node.names]
920
+ import_statements.append(f"from {node.module} import {', '.join(names)}")
921
+
922
+ except SyntaxError:
923
+ # Fallback: use regex to find import statements
924
+ for line in code.split('\n'):
925
+ line = line.strip()
926
+ if line.startswith('import ') or line.startswith('from '):
927
+ # Check if it's not a builtin module
928
+ if line.startswith('import '):
929
+ module_name = line.split()[1].split('.')[0]
930
+ elif line.startswith('from '):
931
+ module_name = line.split()[1].split('.')[0]
932
+
933
+ if module_name not in builtin_modules and not module_name.startswith('_'):
934
+ import_statements.append(line)
935
+
936
+ return list(set(import_statements)) # Remove duplicates
937
+
938
+ def generate_requirements_txt_with_llm(import_statements):
939
+ """Generate requirements.txt content using LLM based on import statements."""
940
+ if not import_statements:
941
+ return "# No additional dependencies required\n"
942
+
943
+ # Use a lightweight model for this task
944
+ try:
945
+ client = get_inference_client("zai-org/GLM-4.6", "auto")
946
+
947
+ imports_text = '\n'.join(import_statements)
948
+
949
+ prompt = f"""Based on the following Python import statements, generate a comprehensive requirements.txt file with all necessary and commonly used related packages:
950
+
951
+ {imports_text}
952
+
953
+ Instructions:
954
+ - Include the direct packages needed for the imports
955
+ - Include commonly used companion packages and dependencies for better functionality
956
+ - Use correct PyPI package names (e.g., PIL -> Pillow, sklearn -> scikit-learn)
957
+ - IMPORTANT: For diffusers, ALWAYS use: git+https://github.com/huggingface/diffusers
958
+ - IMPORTANT: For transformers, ALWAYS use: git+https://github.com/huggingface/transformers
959
+ - IMPORTANT: If diffusers is installed, also include transformers and sentencepiece as they usually go together
960
+ - Examples of comprehensive dependencies:
961
+ * diffusers often needs: git+https://github.com/huggingface/transformers, sentencepiece, accelerate, torch, tokenizers
962
+ * transformers often needs: accelerate, torch, tokenizers, datasets
963
+ * gradio often needs: requests, Pillow for image handling
964
+ * pandas often needs: numpy, openpyxl for Excel files
965
+ * matplotlib often needs: numpy, pillow for image saving
966
+ * sklearn often needs: numpy, scipy, joblib
967
+ * streamlit often needs: pandas, numpy, requests
968
+ * opencv-python often needs: numpy, pillow
969
+ * fastapi often needs: uvicorn, pydantic
970
+ * torch often needs: torchvision, torchaudio (if doing computer vision/audio)
971
+ - Include packages for common file formats if relevant (openpyxl, python-docx, PyPDF2)
972
+ - Do not include Python built-in modules
973
+ - Do not specify versions unless there are known compatibility issues
974
+ - One package per line
975
+ - If no external packages are needed, return "# No additional dependencies required"
976
+
977
+ 🚨 CRITICAL OUTPUT FORMAT:
978
+ - Output ONLY the package names, one per line (plain text format)
979
+ - Do NOT use markdown formatting (no ```, no bold, no headings, no lists)
980
+ - Do NOT add any explanatory text before or after the package list
981
+ - Do NOT wrap the output in code blocks
982
+ - Just output raw package names as they would appear in requirements.txt
983
+
984
+ Generate a comprehensive requirements.txt that ensures the application will work smoothly:"""
985
+
986
+ messages = [
987
+ {"role": "system", "content": "You are a Python packaging expert specializing in creating comprehensive, production-ready requirements.txt files. Output ONLY plain text package names without any markdown formatting, code blocks, or explanatory text. Your goal is to ensure applications work smoothly by including not just direct dependencies but also commonly needed companion packages, popular extensions, and supporting libraries that developers typically need together."},
988
+ {"role": "user", "content": prompt}
989
+ ]
990
+
991
+ response = client.chat.completions.create(
992
+ model="zai-org/GLM-4.6",
993
+ messages=messages,
994
+ max_tokens=1024,
995
+ temperature=0.1
996
+ )
997
+
998
+ requirements_content = response.choices[0].message.content.strip()
999
+
1000
+ # Clean up the response in case it includes extra formatting
1001
+ if '```' in requirements_content:
1002
+ # Use the existing remove_code_block function for consistent cleaning
1003
+ requirements_content = remove_code_block(requirements_content)
1004
+
1005
+ # Enhanced cleanup for markdown and formatting
1006
+ lines = requirements_content.split('\n')
1007
+ clean_lines = []
1008
+ for line in lines:
1009
+ stripped_line = line.strip()
1010
+
1011
+ # Skip lines that are markdown formatting
1012
+ if (stripped_line == '```' or
1013
+ stripped_line.startswith('```') or
1014
+ stripped_line.startswith('#') and not stripped_line.startswith('# ') or # Skip markdown headers but keep comments
1015
+ stripped_line.startswith('**') or # Skip bold text
1016
+ stripped_line.startswith('*') and not stripped_line[1:2].isalnum() or # Skip markdown lists but keep package names starting with *
1017
+ stripped_line.startswith('-') and not stripped_line[1:2].isalnum() or # Skip markdown lists but keep package names starting with -
1018
+ stripped_line.startswith('===') or # Skip section dividers
1019
+ stripped_line.startswith('---') or # Skip horizontal rules
1020
+ stripped_line.lower().startswith('here') or # Skip explanatory text
1021
+ stripped_line.lower().startswith('this') or # Skip explanatory text
1022
+ stripped_line.lower().startswith('the') or # Skip explanatory text
1023
+ stripped_line.lower().startswith('based on') or # Skip explanatory text
1024
+ stripped_line == ''): # Skip empty lines unless they're at natural boundaries
1025
+ continue
1026
+
1027
+ # Keep lines that look like valid package specifications
1028
+ # Valid lines: package names, git+https://, comments starting with "# "
1029
+ if (stripped_line.startswith('# ') or # Valid comments
1030
+ stripped_line.startswith('git+') or # Git dependencies
1031
+ stripped_line[0].isalnum() or # Package names start with alphanumeric
1032
+ '==' in stripped_line or # Version specifications
1033
+ '>=' in stripped_line or # Version specifications
1034
+ '<=' in stripped_line): # Version specifications
1035
+ clean_lines.append(line)
1036
+
1037
+ requirements_content = '\n'.join(clean_lines).strip()
1038
+
1039
+ # Ensure it ends with a newline
1040
+ if requirements_content and not requirements_content.endswith('\n'):
1041
+ requirements_content += '\n'
1042
+
1043
+ return requirements_content if requirements_content else "# No additional dependencies required\n"
1044
+
1045
+ except Exception as e:
1046
+ # Fallback: simple extraction with basic mapping
1047
+ dependencies = set()
1048
+ special_cases = {
1049
+ 'PIL': 'Pillow',
1050
+ 'sklearn': 'scikit-learn',
1051
+ 'skimage': 'scikit-image',
1052
+ 'bs4': 'beautifulsoup4'
1053
+ }
1054
+
1055
+ for stmt in import_statements:
1056
+ if stmt.startswith('import '):
1057
+ module_name = stmt.split()[1].split('.')[0]
1058
+ package_name = special_cases.get(module_name, module_name)
1059
+ dependencies.add(package_name)
1060
+ elif stmt.startswith('from '):
1061
+ module_name = stmt.split()[1].split('.')[0]
1062
+ package_name = special_cases.get(module_name, module_name)
1063
+ dependencies.add(package_name)
1064
+
1065
+ if dependencies:
1066
+ return '\n'.join(sorted(dependencies)) + '\n'
1067
+ else:
1068
+ return "# No additional dependencies required\n"
1069
+
1070
+ def wrap_html_in_gradio_app(html_code):
1071
+ # Escape triple quotes for safe embedding
1072
+ safe_html = html_code.replace('"""', r'\"\"\"')
1073
+
1074
+ # Extract import statements and generate requirements.txt with LLM
1075
+ import_statements = extract_import_statements(html_code)
1076
+ requirements_comment = ""
1077
+ if import_statements:
1078
+ requirements_content = generate_requirements_txt_with_llm(import_statements)
1079
+ requirements_comment = (
1080
+ "# Generated requirements.txt content (create this file manually if needed):\n"
1081
+ + '\n'.join(f"# {line}" for line in requirements_content.strip().split('\n')) + '\n\n'
1082
+ )
1083
+
1084
+ return (
1085
+ f'{requirements_comment}'
1086
+ 'import gradio as gr\n\n'
1087
+ 'def show_html():\n'
1088
+ f' return """{safe_html}"""\n\n'
1089
+ 'demo = gr.Interface(fn=show_html, inputs=None, outputs=gr.HTML())\n\n'
1090
+ 'if __name__ == "__main__":\n'
1091
+ ' demo.launch()\n'
1092
+ )
1093
+ def deploy_to_spaces(code):
1094
+ if not code or not code.strip():
1095
+ return # Do nothing if code is empty
1096
+ # Wrap the HTML code in a Gradio app
1097
+ app_py = wrap_html_in_gradio_app(code.strip())
1098
+ base_url = "https://huggingface.co/new-space"
1099
+ params = urllib.parse.urlencode({
1100
+ "name": "new-space",
1101
+ "sdk": "gradio"
1102
+ })
1103
+ # Use urlencode for file params
1104
+ files_params = urllib.parse.urlencode({
1105
+ "files[0][path]": "app.py",
1106
+ "files[0][content]": app_py
1107
+ })
1108
+ full_url = f"{base_url}?{params}&{files_params}"
1109
+ webbrowser.open_new_tab(full_url)
1110
+
1111
+ def wrap_html_in_static_app(html_code):
1112
+ # For static Spaces, just use the HTML code as-is
1113
+ return html_code
1114
+
1115
+ def prettify_comfyui_json_for_html(json_content: str) -> str:
1116
+ """Convert ComfyUI JSON to prettified HTML display"""
1117
+ try:
1118
+ import json
1119
+ # Parse and prettify the JSON
1120
+ parsed_json = json.loads(json_content)
1121
+ prettified_json = json.dumps(parsed_json, indent=2, ensure_ascii=False)
1122
+
1123
+ # Create HTML wrapper with syntax highlighting
1124
+ html_content = f"""<!DOCTYPE html>
1125
+ <html lang="en">
1126
+ <head>
1127
+ <meta charset="UTF-8">
1128
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1129
+ <title>ComfyUI Workflow</title>
1130
+ <style>
1131
+ body {{
1132
+ font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
1133
+ background-color: #1e1e1e;
1134
+ color: #d4d4d4;
1135
+ margin: 0;
1136
+ padding: 20px;
1137
+ line-height: 1.4;
1138
+ }}
1139
+ .header {{
1140
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
1141
+ color: white;
1142
+ padding: 20px;
1143
+ border-radius: 10px;
1144
+ margin-bottom: 20px;
1145
+ text-align: center;
1146
+ }}
1147
+ .header h1 {{
1148
+ margin: 0;
1149
+ font-size: 2em;
1150
+ }}
1151
+ .header a {{
1152
+ color: #ffffff;
1153
+ text-decoration: none;
1154
+ font-weight: bold;
1155
+ opacity: 0.9;
1156
+ }}
1157
+ .header a:hover {{
1158
+ opacity: 1;
1159
+ text-decoration: underline;
1160
+ }}
1161
+ .json-container {{
1162
+ background-color: #2d2d30;
1163
+ border-radius: 8px;
1164
+ padding: 20px;
1165
+ overflow-x: auto;
1166
+ border: 1px solid #3e3e42;
1167
+ }}
1168
+ pre {{
1169
+ margin: 0;
1170
+ white-space: pre-wrap;
1171
+ word-wrap: break-word;
1172
+ }}
1173
+ .json-key {{
1174
+ color: #9cdcfe;
1175
+ }}
1176
+ .json-string {{
1177
+ color: #ce9178;
1178
+ }}
1179
+ .json-number {{
1180
+ color: #b5cea8;
1181
+ }}
1182
+ .json-boolean {{
1183
+ color: #569cd6;
1184
+ }}
1185
+ .json-null {{
1186
+ color: #569cd6;
1187
+ }}
1188
+ .copy-btn {{
1189
+ background: #007acc;
1190
+ color: white;
1191
+ border: none;
1192
+ padding: 10px 20px;
1193
+ border-radius: 5px;
1194
+ cursor: pointer;
1195
+ margin-bottom: 10px;
1196
+ font-family: inherit;
1197
+ }}
1198
+ .copy-btn:hover {{
1199
+ background: #005a9e;
1200
+ }}
1201
+ .download-btn {{
1202
+ background: #28a745;
1203
+ color: white;
1204
+ border: none;
1205
+ padding: 10px 20px;
1206
+ border-radius: 5px;
1207
+ cursor: pointer;
1208
+ margin-bottom: 10px;
1209
+ margin-left: 10px;
1210
+ font-family: inherit;
1211
+ }}
1212
+ .download-btn:hover {{
1213
+ background: #218838;
1214
+ }}
1215
+ </style>
1216
+ </head>
1217
+ <body>
1218
+ <div class="header">
1219
+ <h1>ComfyUI Workflow</h1>
1220
+ <p>Built with <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank">anycoder</a></p>
1221
+ </div>
1222
+
1223
+ <button class="copy-btn" onclick="copyToClipboard()">πŸ“‹ Copy JSON</button>
1224
+ <button class="download-btn" onclick="downloadJSON()">πŸ’Ύ Download JSON</button>
1225
+
1226
+ <div class="json-container">
1227
+ <pre id="json-content">{prettified_json}</pre>
1228
+ </div>
1229
+
1230
+ <script>
1231
+ function copyToClipboard() {{
1232
+ const jsonContent = document.getElementById('json-content').textContent;
1233
+ navigator.clipboard.writeText(jsonContent).then(() => {{
1234
+ const btn = document.querySelector('.copy-btn');
1235
+ const originalText = btn.textContent;
1236
+ btn.textContent = 'βœ… Copied!';
1237
+ setTimeout(() => {{
1238
+ btn.textContent = originalText;
1239
+ }}, 2000);
1240
+ }});
1241
+ }}
1242
+
1243
+ function downloadJSON() {{
1244
+ const jsonContent = document.getElementById('json-content').textContent;
1245
+ const blob = new Blob([jsonContent], {{ type: 'application/json' }});
1246
+ const url = URL.createObjectURL(blob);
1247
+ const a = document.createElement('a');
1248
+ a.href = url;
1249
+ a.download = 'comfyui_workflow.json';
1250
+ document.body.appendChild(a);
1251
+ a.click();
1252
+ document.body.removeChild(a);
1253
+ URL.revokeObjectURL(url);
1254
+ }}
1255
+
1256
+ // Add syntax highlighting
1257
+ function highlightJSON() {{
1258
+ const content = document.getElementById('json-content');
1259
+ let html = content.innerHTML;
1260
+
1261
+ // Highlight different JSON elements
1262
+ html = html.replace(/"([^"]+)":/g, '<span class="json-key">"$1":</span>');
1263
+ html = html.replace(/: "([^"]*)"/g, ': <span class="json-string">"$1"</span>');
1264
+ html = html.replace(/: (-?\d+\.?\d*)/g, ': <span class="json-number">$1</span>');
1265
+ html = html.replace(/: (true|false)/g, ': <span class="json-boolean">$1</span>');
1266
+ html = html.replace(/: null/g, ': <span class="json-null">null</span>');
1267
+
1268
+ content.innerHTML = html;
1269
+ }}
1270
+
1271
+ // Apply syntax highlighting after page load
1272
+ window.addEventListener('load', highlightJSON);
1273
+ </script>
1274
+ </body>
1275
+ </html>"""
1276
+ return html_content
1277
+ except json.JSONDecodeError:
1278
+ # If it's not valid JSON, return as-is
1279
+ return json_content
1280
+ except Exception as e:
1281
+ print(f"Error prettifying ComfyUI JSON: {e}")
1282
+ return json_content
1283
+
1284
+ def check_hf_space_url(url: str) -> Tuple[bool, Optional[str], Optional[str]]:
1285
+ """Check if URL is a valid Hugging Face Spaces URL and extract username/project"""
1286
+ import re
1287
+
1288
+ # Pattern to match HF Spaces URLs (allows dots in space names)
1289
+ url_pattern = re.compile(
1290
+ r'^(https?://)?(huggingface\.co|hf\.co)/spaces/([\w.-]+)/([\w.-]+)$',
1291
+ re.IGNORECASE
1292
+ )
1293
+
1294
+ match = url_pattern.match(url.strip())
1295
+ if match:
1296
+ username = match.group(3)
1297
+ project_name = match.group(4)
1298
+ return True, username, project_name
1299
+ return False, None, None
1300
+
1301
+ def detect_transformers_js_space(api, username: str, project_name: str) -> bool:
1302
+ """Check if a space is a transformers.js app by looking for the three key files"""
1303
+ try:
1304
+ from huggingface_hub import list_repo_files
1305
+ files = list_repo_files(repo_id=f"{username}/{project_name}", repo_type="space")
1306
+
1307
+ # Check for the three transformers.js files
1308
+ has_index_html = any('index.html' in f for f in files)
1309
+ has_index_js = any('index.js' in f for f in files)
1310
+ has_style_css = any('style.css' in f for f in files)
1311
+
1312
+ return has_index_html and has_index_js and has_style_css
1313
+ except:
1314
+ return False
1315
+
1316
+ def fetch_transformers_js_files(api, username: str, project_name: str) -> dict:
1317
+ """Fetch all three transformers.js files from a space"""
1318
+ files = {}
1319
+ file_names = ['index.html', 'index.js', 'style.css']
1320
+
1321
+ for file_name in file_names:
1322
+ try:
1323
+ content_path = api.hf_hub_download(
1324
+ repo_id=f"{username}/{project_name}",
1325
+ filename=file_name,
1326
+ repo_type="space"
1327
+ )
1328
+
1329
+ with open(content_path, 'r', encoding='utf-8') as f:
1330
+ files[file_name] = f.read()
1331
+ except:
1332
+ files[file_name] = ""
1333
+
1334
+ return files
1335
+
1336
+ def combine_transformers_js_files(files: dict, username: str, project_name: str) -> str:
1337
+ """Combine transformers.js files into the expected format for the LLM"""
1338
+ combined = f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
1339
+ ==============================================
1340
+
1341
+ Space: {username}/{project_name}
1342
+ SDK: static (transformers.js)
1343
+ Type: Transformers.js Application
1344
+
1345
+ """
1346
+
1347
+ if files.get('index.html'):
1348
+ combined += f"=== index.html ===\n{files['index.html']}\n\n"
1349
+
1350
+ if files.get('index.js'):
1351
+ combined += f"=== index.js ===\n{files['index.js']}\n\n"
1352
+
1353
+ if files.get('style.css'):
1354
+ combined += f"=== style.css ===\n{files['style.css']}\n\n"
1355
+
1356
+ return combined
1357
+
1358
+ def fetch_all_space_files(api, username: str, project_name: str, sdk: str) -> dict:
1359
+ """Fetch all relevant files from a Hugging Face Space"""
1360
+ files = {}
1361
+
1362
+ try:
1363
+ from huggingface_hub import list_repo_files
1364
+ all_files = list_repo_files(repo_id=f"{username}/{project_name}", repo_type="space")
1365
+
1366
+ # Filter out unwanted files
1367
+ relevant_files = []
1368
+ for file in all_files:
1369
+ # Skip hidden files, git files, and certain extensions
1370
+ if (file.startswith('.') or
1371
+ file.endswith('.md') or
1372
+ (file.endswith('.txt') and file not in ['requirements.txt', 'packages.txt']) or
1373
+ file.endswith('.log') or
1374
+ file.endswith('.pyc') or
1375
+ '__pycache__' in file):
1376
+ continue
1377
+ relevant_files.append(file)
1378
+
1379
+ # Define priority files based on SDK
1380
+ priority_files = []
1381
+ if sdk == "gradio":
1382
+ priority_files = ["app.py", "main.py", "gradio_app.py", "requirements.txt", "packages.txt"]
1383
+ elif sdk == "streamlit":
1384
+ priority_files = ["streamlit_app.py", "app.py", "main.py", "requirements.txt", "packages.txt"]
1385
+ elif sdk == "static":
1386
+ priority_files = ["index.html", "index.js", "style.css", "script.js"]
1387
+
1388
+ # Add priority files first, then other Python files, then other files
1389
+ files_to_fetch = []
1390
+
1391
+ # Add priority files that exist
1392
+ for pfile in priority_files:
1393
+ if pfile in relevant_files:
1394
+ files_to_fetch.append(pfile)
1395
+ relevant_files.remove(pfile)
1396
+
1397
+ # Add other Python files
1398
+ python_files = [f for f in relevant_files if f.endswith('.py')]
1399
+ files_to_fetch.extend(python_files)
1400
+ for pf in python_files:
1401
+ if pf in relevant_files:
1402
+ relevant_files.remove(pf)
1403
+
1404
+ # Add other important files (JS, CSS, JSON, etc.)
1405
+ other_important = [f for f in relevant_files if any(f.endswith(ext) for ext in ['.js', '.css', '.json', '.html', '.yml', '.yaml'])]
1406
+ files_to_fetch.extend(other_important)
1407
+
1408
+ # Limit to reasonable number of files to avoid overwhelming
1409
+ files_to_fetch = files_to_fetch[:20] # Max 20 files
1410
+
1411
+ # Download each file
1412
+ for file_name in files_to_fetch:
1413
+ try:
1414
+ content_path = api.hf_hub_download(
1415
+ repo_id=f"{username}/{project_name}",
1416
+ filename=file_name,
1417
+ repo_type="space"
1418
+ )
1419
+
1420
+ # Read file content with appropriate encoding
1421
+ try:
1422
+ with open(content_path, 'r', encoding='utf-8') as f:
1423
+ files[file_name] = f.read()
1424
+ except UnicodeDecodeError:
1425
+ # For binary files or files with different encoding
1426
+ with open(content_path, 'rb') as f:
1427
+ content = f.read()
1428
+ # Skip binary files that are too large or not text
1429
+ if len(content) > 100000: # Skip files > 100KB
1430
+ files[file_name] = f"[Binary file: {file_name} - {len(content)} bytes]"
1431
+ else:
1432
+ try:
1433
+ files[file_name] = content.decode('utf-8')
1434
+ except:
1435
+ files[file_name] = f"[Binary file: {file_name} - {len(content)} bytes]"
1436
+ except Exception as e:
1437
+ files[file_name] = f"[Error loading {file_name}: {str(e)}]"
1438
+
1439
+ except Exception as e:
1440
+ # Fallback to single file loading
1441
+ return {}
1442
+
1443
+ return files
1444
+
1445
+ def format_multi_file_space(files: dict, username: str, project_name: str, sdk: str) -> str:
1446
+ """Format multiple files from a space into a readable format"""
1447
+ if not files:
1448
+ return ""
1449
+
1450
+ header = f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
1451
+ ==============================================
1452
+
1453
+ Space: {username}/{project_name}
1454
+ SDK: {sdk}
1455
+ Files: {len(files)} files loaded
1456
+
1457
+ """
1458
+
1459
+ # Sort files to show main files first
1460
+ main_files = []
1461
+ other_files = []
1462
+
1463
+ priority_order = ["app.py", "main.py", "streamlit_app.py", "gradio_app.py", "index.html", "requirements.txt"]
1464
+
1465
+ for priority_file in priority_order:
1466
+ if priority_file in files:
1467
+ main_files.append(priority_file)
1468
+
1469
+ for file_name in sorted(files.keys()):
1470
+ if file_name not in main_files:
1471
+ other_files.append(file_name)
1472
+
1473
+ content = header
1474
+
1475
+ # Add main files first
1476
+ for file_name in main_files:
1477
+ content += f"=== {file_name} ===\n{files[file_name]}\n\n"
1478
+
1479
+ # Add other files
1480
+ for file_name in other_files:
1481
+ content += f"=== {file_name} ===\n{files[file_name]}\n\n"
1482
+
1483
+ return content
1484
+
1485
+ def fetch_hf_space_content(username: str, project_name: str) -> str:
1486
+ """Fetch content from a Hugging Face Space"""
1487
+ try:
1488
+ import requests
1489
+ from huggingface_hub import HfApi
1490
+
1491
+ # Try to get space info first
1492
+ api = HfApi()
1493
+ space_info = api.space_info(f"{username}/{project_name}")
1494
+
1495
+ # Check if this is a transformers.js space first
1496
+ if space_info.sdk == "static" and detect_transformers_js_space(api, username, project_name):
1497
+ files = fetch_transformers_js_files(api, username, project_name)
1498
+ return combine_transformers_js_files(files, username, project_name)
1499
+
1500
+ # Use the new multi-file loading approach for all space types
1501
+ sdk = space_info.sdk
1502
+ files = fetch_all_space_files(api, username, project_name, sdk)
1503
+
1504
+ if files:
1505
+ # Use the multi-file format
1506
+ return format_multi_file_space(files, username, project_name, sdk)
1507
+ else:
1508
+ # Fallback to single file loading for compatibility
1509
+ main_file = None
1510
+
1511
+ # Define file patterns to try based on SDK
1512
+ if sdk == "static":
1513
+ file_patterns = ["index.html"]
1514
+ elif sdk == "gradio":
1515
+ file_patterns = ["app.py", "main.py", "gradio_app.py"]
1516
+ elif sdk == "streamlit":
1517
+ file_patterns = ["streamlit_app.py", "src/streamlit_app.py", "app.py", "src/app.py", "main.py", "src/main.py", "Home.py", "src/Home.py", "🏠_Home.py", "src/🏠_Home.py", "1_🏠_Home.py", "src/1_🏠_Home.py"]
1518
+ else:
1519
+ # Try common files for unknown SDKs
1520
+ file_patterns = ["app.py", "src/app.py", "index.html", "streamlit_app.py", "src/streamlit_app.py", "main.py", "src/main.py", "Home.py", "src/Home.py"]
1521
+
1522
+ # Try to find and download the main file
1523
+ for file in file_patterns:
1524
+ try:
1525
+ content = api.hf_hub_download(
1526
+ repo_id=f"{username}/{project_name}",
1527
+ filename=file,
1528
+ repo_type="space"
1529
+ )
1530
+ main_file = file
1531
+ break
1532
+ except:
1533
+ continue
1534
+
1535
+ if main_file:
1536
+ content = api.hf_hub_download(
1537
+ repo_id=f"{username}/{project_name}",
1538
+ filename=main_file,
1539
+ repo_type="space"
1540
+ )
1541
+
1542
+ # Read the file content
1543
+ with open(content, 'r', encoding='utf-8') as f:
1544
+ file_content = f.read()
1545
+
1546
+ return f"""IMPORTED PROJECT FROM HUGGING FACE SPACE
1547
+ ==============================================
1548
+
1549
+ Space: {username}/{project_name}
1550
+ SDK: {sdk}
1551
+ Main File: {main_file}
1552
+
1553
+ {file_content}"""
1554
+ else:
1555
+ # Try to get more information about available files for debugging
1556
+ try:
1557
+ from huggingface_hub import list_repo_files
1558
+ files_list = list_repo_files(repo_id=f"{username}/{project_name}", repo_type="space")
1559
+ available_files = [f for f in files_list if not f.startswith('.') and not f.endswith('.md')]
1560
+ return f"Error: Could not find main file in space {username}/{project_name}.\n\nSDK: {sdk}\nAvailable files: {', '.join(available_files[:10])}{'...' if len(available_files) > 10 else ''}\n\nTried looking for: {', '.join(file_patterns)}"
1561
+ except:
1562
+ return f"Error: Could not find main file in space {username}/{project_name}. Expected files for {sdk} SDK: {', '.join(file_patterns) if 'file_patterns' in locals() else 'standard files'}"
1563
+
1564
+ except Exception as e:
1565
+ return f"Error fetching space content: {str(e)}"
1566
+
1567
+ def load_project_from_url(url: str) -> Tuple[str, str]:
1568
+ """Load project from Hugging Face Space URL"""
1569
+ # Validate URL
1570
+ is_valid, username, project_name = check_hf_space_url(url)
1571
+
1572
+ if not is_valid:
1573
+ return "Error: Please enter a valid Hugging Face Spaces URL.\n\nExpected format: https://huggingface.co/spaces/username/project", ""
1574
+
1575
+ # Fetch content
1576
+ content = fetch_hf_space_content(username, project_name)
1577
+
1578
+ if content.startswith("Error:"):
1579
+ return content, ""
1580
+
1581
+ # Extract the actual code content by removing metadata
1582
+ lines = content.split('\n')
1583
+ code_start = 0
1584
+ for i, line in enumerate(lines):
1585
+ # Skip metadata lines and find the start of actual code
1586
+ if (line.strip() and
1587
+ not line.startswith('=') and
1588
+ not line.startswith('IMPORTED PROJECT') and
1589
+ not line.startswith('Space:') and
1590
+ not line.startswith('SDK:') and
1591
+ not line.startswith('Main File:')):
1592
+ code_start = i
1593
+ break
1594
+
1595
+ code_content = '\n'.join(lines[code_start:])
1596
+
1597
+ return f"βœ… Successfully imported project from {username}/{project_name}", code_content
1598
+
1599
+ # -------- Repo/Model Import (GitHub & Hugging Face model) --------
1600
+ def _parse_repo_or_model_url(url: str) -> Tuple[str, Optional[dict]]:
1601
+ """Parse a URL and detect if it's a GitHub repo, HF Space, or HF Model.
1602
+
1603
+ Returns a tuple of (kind, meta) where kind in {"github", "hf_space", "hf_model", "unknown"}
1604
+ Meta contains parsed identifiers.
1605
+ """
1606
+ try:
1607
+ parsed = urlparse(url.strip())
1608
+ netloc = (parsed.netloc or "").lower()
1609
+ path = (parsed.path or "").strip("/")
1610
+ # Hugging Face spaces
1611
+ if ("huggingface.co" in netloc or netloc.endswith("hf.co")) and path.startswith("spaces/"):
1612
+ parts = path.split("/")
1613
+ if len(parts) >= 3:
1614
+ return "hf_space", {"username": parts[1], "project": parts[2]}
1615
+ # Hugging Face model repo (default)
1616
+ if ("huggingface.co" in netloc or netloc.endswith("hf.co")) and not path.startswith(("spaces/", "datasets/", "organizations/")):
1617
+ parts = path.split("/")
1618
+ if len(parts) >= 2:
1619
+ repo_id = f"{parts[0]}/{parts[1]}"
1620
+ return "hf_model", {"repo_id": repo_id}
1621
+ # GitHub repo
1622
+ if "github.com" in netloc:
1623
+ parts = path.split("/")
1624
+ if len(parts) >= 2:
1625
+ return "github", {"owner": parts[0], "repo": parts[1]}
1626
+ except Exception:
1627
+ pass
1628
+ return "unknown", None
1629
+
1630
+ def _fetch_hf_model_readme(repo_id: str) -> Optional[str]:
1631
+ """Fetch README.md (model card) for a Hugging Face model repo."""
1632
+ try:
1633
+ api = HfApi()
1634
+ # Try direct README.md first
1635
+ try:
1636
+ local_path = api.hf_hub_download(repo_id=repo_id, filename="README.md", repo_type="model")
1637
+ with open(local_path, "r", encoding="utf-8") as f:
1638
+ return f.read()
1639
+ except Exception:
1640
+ # Some repos use README at root without explicit type
1641
+ local_path = api.hf_hub_download(repo_id=repo_id, filename="README.md")
1642
+ with open(local_path, "r", encoding="utf-8") as f:
1643
+ return f.read()
1644
+ except Exception:
1645
+ return None
1646
+
1647
+ def _fetch_github_readme(owner: str, repo: str) -> Optional[str]:
1648
+ """Fetch README.md from a GitHub repo via raw URLs, trying HEAD/main/master."""
1649
+ bases = [
1650
+ f"https://raw.githubusercontent.com/{owner}/{repo}/HEAD/README.md",
1651
+ f"https://raw.githubusercontent.com/{owner}/{repo}/main/README.md",
1652
+ f"https://raw.githubusercontent.com/{owner}/{repo}/master/README.md",
1653
+ ]
1654
+ for url in bases:
1655
+ try:
1656
+ resp = requests.get(url, timeout=10)
1657
+ if resp.status_code == 200 and resp.text:
1658
+ return resp.text
1659
+ except Exception:
1660
+ continue
1661
+ return None
1662
+
1663
+ def _extract_transformers_or_diffusers_snippet(markdown_text: str) -> Tuple[Optional[str], Optional[str]]:
1664
+ """Extract the most relevant Python code block referencing transformers/diffusers from markdown.
1665
+
1666
+ Returns (language, code). If not found, returns (None, None).
1667
+ """
1668
+ if not markdown_text:
1669
+ return None, None
1670
+ # Find fenced code blocks
1671
+ code_blocks = []
1672
+ import re as _re
1673
+ for match in _re.finditer(r"```([\w+-]+)?\s*\n([\s\S]*?)```", markdown_text, _re.IGNORECASE):
1674
+ lang = (match.group(1) or "").lower()
1675
+ code = match.group(2) or ""
1676
+ code_blocks.append((lang, code.strip()))
1677
+ # Filter for transformers/diffusers relevance
1678
+ def score_block(code: str) -> int:
1679
+ score = 0
1680
+ kws = [
1681
+ "from transformers", "import transformers", "pipeline(",
1682
+ "AutoModel", "AutoTokenizer", "text-generation",
1683
+ "from diffusers", "import diffusers", "DiffusionPipeline",
1684
+ "StableDiffusion", "UNet", "EulerDiscreteScheduler"
1685
+ ]
1686
+ for kw in kws:
1687
+ if kw in code:
1688
+ score += 1
1689
+ # Prefer longer, self-contained snippets
1690
+ score += min(len(code) // 200, 5)
1691
+ return score
1692
+ scored = sorted(
1693
+ [cb for cb in code_blocks if any(kw in cb[1] for kw in ["transformers", "diffusers", "pipeline(", "StableDiffusion"])],
1694
+ key=lambda x: score_block(x[1]),
1695
+ reverse=True,
1696
+ )
1697
+ if scored:
1698
+ return scored[0][0] or None, scored[0][1]
1699
+ return None, None
1700
+
1701
+ def _infer_task_from_context(snippet: Optional[str], pipeline_tag: Optional[str]) -> str:
1702
+ """Infer a task string for transformers pipeline; fall back to provided pipeline_tag or 'text-generation'."""
1703
+ if pipeline_tag:
1704
+ return pipeline_tag
1705
+ if not snippet:
1706
+ return "text-generation"
1707
+ lowered = snippet.lower()
1708
+ task_hints = {
1709
+ "text-generation": ["text-generation", "automodelforcausallm"],
1710
+ "text2text-generation": ["text2text-generation", "t5forconditionalgeneration"],
1711
+ "fill-mask": ["fill-mask", "automodelformaskedlm"],
1712
+ "summarization": ["summarization"],
1713
+ "translation": ["translation"],
1714
+ "text-classification": ["text-classification", "sequenceclassification"],
1715
+ "automatic-speech-recognition": ["speechrecognition", "automatic-speech-recognition", "asr"],
1716
+ "image-classification": ["image-classification"],
1717
+ "zero-shot-image-classification": ["zero-shot-image-classification"],
1718
+ }
1719
+ for task, hints in task_hints.items():
1720
+ if any(h in lowered for h in hints):
1721
+ return task
1722
+ # Inspect explicit pipeline("task")
1723
+ import re as _re
1724
+ m = _re.search(r"pipeline\(\s*['\"]([\w\-]+)['\"]", snippet)
1725
+ if m:
1726
+ return m.group(1)
1727
+ return "text-generation"
1728
+
1729
+ def _generate_gradio_app_from_transformers(repo_id: str, task: str) -> str:
1730
+ """Build a minimal Gradio app using transformers.pipeline for a given model and task."""
1731
+ # Map simple UI per task; default to text in/out
1732
+ if task in {"text-generation", "text2text-generation", "summarization", "translation", "fill-mask"}:
1733
+ return (
1734
+ "import gradio as gr\n"
1735
+ "from transformers import pipeline\n\n"
1736
+ f"pipe = pipeline(task='{task}', model='{repo_id}')\n\n"
1737
+ "def infer(prompt, max_new_tokens=256, temperature=0.7, top_p=0.95):\n"
1738
+ " if '\u2047' in prompt:\n"
1739
+ " # Fill-mask often uses [MASK]; keep generic handling\n"
1740
+ " pass\n"
1741
+ " out = pipe(prompt, max_new_tokens=max_new_tokens, do_sample=True, temperature=temperature, top_p=top_p)\n"
1742
+ " if isinstance(out, list):\n"
1743
+ " if isinstance(out[0], dict):\n"
1744
+ " return next(iter(out[0].values())) if out[0] else str(out)\n"
1745
+ " return str(out[0])\n"
1746
+ " return str(out)\n\n"
1747
+ "demo = gr.Interface(\n"
1748
+ " fn=infer,\n"
1749
+ " inputs=[gr.Textbox(label='Input', lines=8), gr.Slider(1, 2048, value=256, label='max_new_tokens'), gr.Slider(0.0, 1.5, value=0.7, step=0.01, label='temperature'), gr.Slider(0.0, 1.0, value=0.95, step=0.01, label='top_p')],\n"
1750
+ " outputs=gr.Textbox(label='Output', lines=8),\n"
1751
+ " title='Transformers Demo'\n"
1752
+ ")\n\n"
1753
+ "if __name__ == '__main__':\n"
1754
+ " demo.launch()\n"
1755
+ )
1756
+ elif task in {"text-classification"}:
1757
+ return (
1758
+ "import gradio as gr\n"
1759
+ "from transformers import pipeline\n\n"
1760
+ f"pipe = pipeline(task='{task}', model='{repo_id}')\n\n"
1761
+ "def infer(text):\n"
1762
+ " out = pipe(text)\n"
1763
+ " # Expect list of dicts with label/score\n"
1764
+ " return {o['label']: float(o['score']) for o in out}\n\n"
1765
+ "demo = gr.Interface(fn=infer, inputs=gr.Textbox(lines=6), outputs=gr.Label(), title='Text Classification')\n\n"
1766
+ "if __name__ == '__main__':\n"
1767
+ " demo.launch()\n"
1768
+ )
1769
+ else:
1770
+ # Fallback generic text pipeline (pipeline infers task from model config)
1771
+ return (
1772
+ "import gradio as gr\n"
1773
+ "from transformers import pipeline\n\n"
1774
+ f"pipe = pipeline(model='{repo_id}')\n\n"
1775
+ "def infer(prompt):\n"
1776
+ " out = pipe(prompt)\n"
1777
+ " if isinstance(out, list):\n"
1778
+ " if isinstance(out[0], dict):\n"
1779
+ " return next(iter(out[0].values())) if out[0] else str(out)\n"
1780
+ " return str(out[0])\n"
1781
+ " return str(out)\n\n"
1782
+ "demo = gr.Interface(fn=infer, inputs=gr.Textbox(lines=8), outputs=gr.Textbox(lines=8), title='Transformers Demo')\n\n"
1783
+ "if __name__ == '__main__':\n"
1784
+ " demo.launch()\n"
1785
+ )
1786
+
1787
+ def _generate_gradio_app_from_diffusers(repo_id: str) -> str:
1788
+ """Build a minimal Gradio app for text-to-image using diffusers."""
1789
+ return (
1790
+ "import gradio as gr\n"
1791
+ "import torch\n"
1792
+ "from diffusers import DiffusionPipeline\n\n"
1793
+ f"pipe = DiffusionPipeline.from_pretrained('{repo_id}')\n"
1794
+ "device = 'cuda' if torch.cuda.is_available() else 'cpu'\n"
1795
+ "pipe = pipe.to(device)\n\n"
1796
+ "def infer(prompt, guidance_scale=7.0, num_inference_steps=30, seed=0):\n"
1797
+ " generator = None if seed == 0 else torch.Generator(device=device).manual_seed(int(seed))\n"
1798
+ " image = pipe(prompt, guidance_scale=float(guidance_scale), num_inference_steps=int(num_inference_steps), generator=generator).images[0]\n"
1799
+ " return image\n\n"
1800
+ "demo = gr.Interface(\n"
1801
+ " fn=infer,\n"
1802
+ " inputs=[gr.Textbox(label='Prompt'), gr.Slider(0.0, 15.0, value=7.0, step=0.1, label='guidance_scale'), gr.Slider(1, 100, value=30, step=1, label='num_inference_steps'), gr.Slider(0, 2**32-1, value=0, step=1, label='seed')],\n"
1803
+ " outputs=gr.Image(type='pil'),\n"
1804
+ " title='Diffusers Text-to-Image'\n"
1805
+ ")\n\n"
1806
+ "if __name__ == '__main__':\n"
1807
+ " demo.launch()\n"
1808
+ )
1809
+
1810
+ def import_repo_to_app(url: str, framework: str = "Gradio") -> Tuple[str, str, str]:
1811
+ """Import a GitHub or HF model repo and return the raw code snippet from README/model card.
1812
+
1813
+ Returns (status_markdown, code_snippet, preview_html). Preview left empty; UI will decide.
1814
+ """
1815
+ if not url or not url.strip():
1816
+ return "Please enter a repository URL.", "", ""
1817
+ kind, meta = _parse_repo_or_model_url(url)
1818
+ if kind == "hf_space" and meta:
1819
+ # Spaces already contain runnable apps; keep existing behavior to fetch main file raw
1820
+ status, code = load_project_from_url(url)
1821
+ return status, code, ""
1822
+ # Fetch markdown
1823
+ markdown = None
1824
+ repo_id = None
1825
+ pipeline_tag = None
1826
+ library_name = None
1827
+ if kind == "hf_model" and meta:
1828
+ repo_id = meta.get("repo_id")
1829
+ # Try model info to get pipeline tag/library
1830
+ try:
1831
+ api = HfApi()
1832
+ info = api.model_info(repo_id)
1833
+ pipeline_tag = getattr(info, "pipeline_tag", None)
1834
+ library_name = getattr(info, "library_name", None)
1835
+ except Exception:
1836
+ pass
1837
+ markdown = _fetch_hf_model_readme(repo_id)
1838
+ elif kind == "github" and meta:
1839
+ markdown = _fetch_github_readme(meta.get("owner"), meta.get("repo"))
1840
+ else:
1841
+ return "Error: Unsupported or invalid URL. Provide a GitHub repo or Hugging Face model URL.", "", ""
1842
+
1843
+ if not markdown:
1844
+ return "Error: Could not fetch README/model card.", "", ""
1845
+
1846
+ lang, snippet = _extract_transformers_or_diffusers_snippet(markdown)
1847
+ if not snippet:
1848
+ return "Error: No relevant transformers/diffusers code block found in README/model card.", "", ""
1849
+
1850
+ status = "βœ… Imported code snippet from README/model card. Use it as a starting point."
1851
+ return status, snippet, ""
1852
+
anycoder_app/docs_manager.py ADDED
@@ -0,0 +1,1415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Documentation management for Gradio, ComfyUI, and FastRTC.
3
+ Handles fetching, caching, and updating documentation from llms.txt files.
4
+ """
5
+ import os
6
+ import requests
7
+ import re
8
+ from datetime import datetime, timedelta
9
+ from typing import Optional
10
+
11
+ from .config import (
12
+ GRADIO_LLMS_TXT_URL, GRADIO_DOCS_CACHE_FILE, GRADIO_DOCS_LAST_UPDATE_FILE,
13
+ GRADIO_DOCS_UPDATE_ON_APP_UPDATE, _gradio_docs_content, _gradio_docs_last_fetched,
14
+ COMFYUI_LLMS_TXT_URL, COMFYUI_DOCS_CACHE_FILE, COMFYUI_DOCS_LAST_UPDATE_FILE,
15
+ COMFYUI_DOCS_UPDATE_ON_APP_UPDATE, _comfyui_docs_content, _comfyui_docs_last_fetched,
16
+ FASTRTC_LLMS_TXT_URL, FASTRTC_DOCS_CACHE_FILE, FASTRTC_DOCS_LAST_UPDATE_FILE,
17
+ FASTRTC_DOCS_UPDATE_ON_APP_UPDATE, _fastrtc_docs_content, _fastrtc_docs_last_fetched
18
+ )
19
+
20
+ def fetch_gradio_docs() -> Optional[str]:
21
+ """Fetch the latest Gradio documentation from llms.txt"""
22
+ try:
23
+ response = requests.get(GRADIO_LLMS_TXT_URL, timeout=10)
24
+ response.raise_for_status()
25
+ return response.text
26
+ except Exception as e:
27
+ print(f"Warning: Failed to fetch Gradio docs from {GRADIO_LLMS_TXT_URL}: {e}")
28
+ return None
29
+
30
+ def fetch_comfyui_docs() -> Optional[str]:
31
+ """Fetch the latest ComfyUI documentation from llms.txt"""
32
+ try:
33
+ response = requests.get(COMFYUI_LLMS_TXT_URL, timeout=10)
34
+ response.raise_for_status()
35
+ return response.text
36
+ except Exception as e:
37
+ print(f"Warning: Failed to fetch ComfyUI docs from {COMFYUI_LLMS_TXT_URL}: {e}")
38
+ return None
39
+
40
+ def fetch_fastrtc_docs() -> Optional[str]:
41
+ """Fetch the latest FastRTC documentation from llms.txt"""
42
+ try:
43
+ response = requests.get(FASTRTC_LLMS_TXT_URL, timeout=10)
44
+ response.raise_for_status()
45
+ return response.text
46
+ except Exception as e:
47
+ print(f"Warning: Failed to fetch FastRTC docs from {FASTRTC_LLMS_TXT_URL}: {e}")
48
+ return None
49
+
50
+ def filter_problematic_instructions(content: str) -> str:
51
+ """Filter out problematic instructions that cause LLM to stop generation prematurely"""
52
+ if not content:
53
+ return content
54
+
55
+ # List of problematic phrases that cause early termination when LLM encounters ``` in user code
56
+ problematic_patterns = [
57
+ r"Output ONLY the code inside a ``` code block, and do not include any explanations or extra text",
58
+ r"output only the code inside a ```.*?``` code block",
59
+ r"Always output only the.*?code.*?inside.*?```.*?```.*?block",
60
+ r"Return ONLY the code inside a.*?```.*?``` code block",
61
+ r"Do NOT add the language name at the top of the code output",
62
+ r"do not include any explanations or extra text",
63
+ r"Always output only the.*?code blocks.*?shown above, and do not include any explanations",
64
+ r"Output.*?ONLY.*?code.*?inside.*?```.*?```",
65
+ r"Return.*?ONLY.*?code.*?inside.*?```.*?```",
66
+ r"Generate.*?ONLY.*?code.*?inside.*?```.*?```",
67
+ r"Provide.*?ONLY.*?code.*?inside.*?```.*?```",
68
+ ]
69
+
70
+ # Remove problematic patterns
71
+ filtered_content = content
72
+ for pattern in problematic_patterns:
73
+ # Use case-insensitive matching
74
+ filtered_content = re.sub(pattern, "", filtered_content, flags=re.IGNORECASE | re.DOTALL)
75
+
76
+ # Clean up any double newlines or extra whitespace left by removals
77
+ filtered_content = re.sub(r'\n\s*\n\s*\n', '\n\n', filtered_content)
78
+ filtered_content = re.sub(r'^\s+', '', filtered_content, flags=re.MULTILINE)
79
+
80
+ return filtered_content
81
+
82
+ def load_cached_gradio_docs() -> Optional[str]:
83
+ """Load cached Gradio documentation from file"""
84
+ try:
85
+ if os.path.exists(GRADIO_DOCS_CACHE_FILE):
86
+ with open(GRADIO_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
87
+ return f.read()
88
+ except Exception as e:
89
+ print(f"Warning: Failed to load cached Gradio docs: {e}")
90
+ return None
91
+
92
+ def save_gradio_docs_cache(content: str):
93
+ """Save Gradio documentation to cache file"""
94
+ try:
95
+ with open(GRADIO_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
96
+ f.write(content)
97
+ with open(GRADIO_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
98
+ f.write(datetime.now().isoformat())
99
+ except Exception as e:
100
+ print(f"Warning: Failed to save Gradio docs cache: {e}")
101
+
102
+ def load_comfyui_docs_cache() -> Optional[str]:
103
+ """Load ComfyUI documentation from cache file"""
104
+ try:
105
+ if os.path.exists(COMFYUI_DOCS_CACHE_FILE):
106
+ with open(COMFYUI_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
107
+ return f.read()
108
+ except Exception as e:
109
+ print(f"Warning: Failed to load cached ComfyUI docs: {e}")
110
+ return None
111
+
112
+ def save_comfyui_docs_cache(content: str):
113
+ """Save ComfyUI documentation to cache file"""
114
+ try:
115
+ with open(COMFYUI_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
116
+ f.write(content)
117
+ with open(COMFYUI_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
118
+ f.write(datetime.now().isoformat())
119
+ except Exception as e:
120
+ print(f"Warning: Failed to save ComfyUI docs cache: {e}")
121
+
122
+ def load_fastrtc_docs_cache() -> Optional[str]:
123
+ """Load FastRTC documentation from cache file"""
124
+ try:
125
+ if os.path.exists(FASTRTC_DOCS_CACHE_FILE):
126
+ with open(FASTRTC_DOCS_CACHE_FILE, 'r', encoding='utf-8') as f:
127
+ return f.read()
128
+ except Exception as e:
129
+ print(f"Warning: Failed to load cached FastRTC docs: {e}")
130
+ return None
131
+
132
+ def save_fastrtc_docs_cache(content: str):
133
+ """Save FastRTC documentation to cache file"""
134
+ try:
135
+ with open(FASTRTC_DOCS_CACHE_FILE, 'w', encoding='utf-8') as f:
136
+ f.write(content)
137
+ with open(FASTRTC_DOCS_LAST_UPDATE_FILE, 'w', encoding='utf-8') as f:
138
+ f.write(datetime.now().isoformat())
139
+ except Exception as e:
140
+ print(f"Warning: Failed to save FastRTC docs cache: {e}")
141
+
142
+ def get_last_update_time() -> Optional[datetime]:
143
+ """Get the last update time from file"""
144
+ try:
145
+ if os.path.exists(GRADIO_DOCS_LAST_UPDATE_FILE):
146
+ with open(GRADIO_DOCS_LAST_UPDATE_FILE, 'r', encoding='utf-8') as f:
147
+ return datetime.fromisoformat(f.read().strip())
148
+ except Exception as e:
149
+ print(f"Warning: Failed to read last update time: {e}")
150
+ return None
151
+
152
+ def should_update_gradio_docs() -> bool:
153
+ """Check if Gradio documentation should be updated"""
154
+ # Only update if we don't have cached content (first run or cache deleted)
155
+ return not os.path.exists(GRADIO_DOCS_CACHE_FILE)
156
+
157
+ def should_update_comfyui_docs() -> bool:
158
+ """Check if ComfyUI documentation should be updated"""
159
+ # Only update if we don't have cached content (first run or cache deleted)
160
+ return not os.path.exists(COMFYUI_DOCS_CACHE_FILE)
161
+
162
+ def should_update_fastrtc_docs() -> bool:
163
+ """Check if FastRTC documentation should be updated"""
164
+ # Only update if we don't have cached content (first run or cache deleted)
165
+ return not os.path.exists(FASTRTC_DOCS_CACHE_FILE)
166
+
167
+ def force_update_gradio_docs():
168
+ """
169
+ Force an update of Gradio documentation (useful when app is updated).
170
+
171
+ To manually refresh docs, you can call this function or simply delete the cache file:
172
+ rm .gradio_docs_cache.txt && restart the app
173
+ """
174
+ global _gradio_docs_content, _gradio_docs_last_fetched
175
+
176
+ print("πŸ”„ Forcing Gradio documentation update...")
177
+ latest_content = fetch_gradio_docs()
178
+
179
+ if latest_content:
180
+ # Filter out problematic instructions that cause early termination
181
+ filtered_content = filter_problematic_instructions(latest_content)
182
+ _gradio_docs_content = filtered_content
183
+ _gradio_docs_last_fetched = datetime.now()
184
+ save_gradio_docs_cache(filtered_content)
185
+ update_gradio_system_prompts()
186
+ print("βœ… Gradio documentation updated successfully")
187
+ return True
188
+ else:
189
+ print("❌ Failed to update Gradio documentation")
190
+ return False
191
+
192
+ def force_update_comfyui_docs():
193
+ """
194
+ Force an update of ComfyUI documentation (useful when app is updated).
195
+
196
+ To manually refresh docs, you can call this function or simply delete the cache file:
197
+ rm .comfyui_docs_cache.txt && restart the app
198
+ """
199
+ global _comfyui_docs_content, _comfyui_docs_last_fetched
200
+
201
+ print("πŸ”„ Forcing ComfyUI documentation update...")
202
+ latest_content = fetch_comfyui_docs()
203
+
204
+ if latest_content:
205
+ # Filter out problematic instructions that cause early termination
206
+ filtered_content = filter_problematic_instructions(latest_content)
207
+ _comfyui_docs_content = filtered_content
208
+ _comfyui_docs_last_fetched = datetime.now()
209
+ save_comfyui_docs_cache(filtered_content)
210
+ update_json_system_prompts()
211
+ print("βœ… ComfyUI documentation updated successfully")
212
+ return True
213
+ else:
214
+ print("❌ Failed to update ComfyUI documentation")
215
+ return False
216
+
217
+ def force_update_fastrtc_docs():
218
+ """
219
+ Force an update of FastRTC documentation (useful when app is updated).
220
+
221
+ To manually refresh docs, you can call this function or simply delete the cache file:
222
+ rm .fastrtc_docs_cache.txt && restart the app
223
+ """
224
+ global _fastrtc_docs_content, _fastrtc_docs_last_fetched
225
+
226
+ print("πŸ”„ Forcing FastRTC documentation update...")
227
+ latest_content = fetch_fastrtc_docs()
228
+
229
+ if latest_content:
230
+ # Filter out problematic instructions that cause early termination
231
+ filtered_content = filter_problematic_instructions(latest_content)
232
+ _fastrtc_docs_content = filtered_content
233
+ _fastrtc_docs_last_fetched = datetime.now()
234
+ save_fastrtc_docs_cache(filtered_content)
235
+ update_gradio_system_prompts()
236
+ print("βœ… FastRTC documentation updated successfully")
237
+ return True
238
+ else:
239
+ print("❌ Failed to update FastRTC documentation")
240
+ return False
241
+
242
+ def get_gradio_docs_content() -> str:
243
+ """Get the current Gradio documentation content, updating if necessary"""
244
+ global _gradio_docs_content, _gradio_docs_last_fetched
245
+
246
+ # Check if we need to update
247
+ if (_gradio_docs_content is None or
248
+ _gradio_docs_last_fetched is None or
249
+ should_update_gradio_docs()):
250
+
251
+ print("Updating Gradio documentation...")
252
+
253
+ # Try to fetch latest content
254
+ latest_content = fetch_gradio_docs()
255
+
256
+ if latest_content:
257
+ # Filter out problematic instructions that cause early termination
258
+ filtered_content = filter_problematic_instructions(latest_content)
259
+ _gradio_docs_content = filtered_content
260
+ _gradio_docs_last_fetched = datetime.now()
261
+ save_gradio_docs_cache(filtered_content)
262
+ print("βœ… Gradio documentation updated successfully")
263
+ else:
264
+ # Fallback to cached content
265
+ cached_content = load_cached_gradio_docs()
266
+ if cached_content:
267
+ _gradio_docs_content = cached_content
268
+ _gradio_docs_last_fetched = datetime.now()
269
+ print("⚠️ Using cached Gradio documentation (network fetch failed)")
270
+ else:
271
+ # Fallback to minimal content
272
+ _gradio_docs_content = """
273
+ # Gradio API Reference (Offline Fallback)
274
+
275
+ This is a minimal fallback when documentation cannot be fetched.
276
+ Please check your internet connection for the latest API reference.
277
+
278
+ Basic Gradio components: Button, Textbox, Slider, Image, Audio, Video, File, etc.
279
+ Use gr.Blocks() for custom layouts and gr.Interface() for simple apps.
280
+ """
281
+ print("❌ Using minimal fallback documentation")
282
+
283
+ return _gradio_docs_content or ""
284
+
285
+ def get_comfyui_docs_content() -> str:
286
+ """Get the current ComfyUI documentation content, updating if necessary"""
287
+ global _comfyui_docs_content, _comfyui_docs_last_fetched
288
+
289
+ # Check if we need to update
290
+ if (_comfyui_docs_content is None or
291
+ _comfyui_docs_last_fetched is None or
292
+ should_update_comfyui_docs()):
293
+
294
+ print("Updating ComfyUI documentation...")
295
+
296
+ # Try to fetch latest content
297
+ latest_content = fetch_comfyui_docs()
298
+
299
+ if latest_content:
300
+ # Filter out problematic instructions that cause early termination
301
+ filtered_content = filter_problematic_instructions(latest_content)
302
+ _comfyui_docs_content = filtered_content
303
+ _comfyui_docs_last_fetched = datetime.now()
304
+ save_comfyui_docs_cache(filtered_content)
305
+ print("βœ… ComfyUI documentation updated successfully")
306
+ else:
307
+ # Fallback to cached content
308
+ cached_content = load_comfyui_docs_cache()
309
+ if cached_content:
310
+ _comfyui_docs_content = cached_content
311
+ _comfyui_docs_last_fetched = datetime.now()
312
+ print("⚠️ Using cached ComfyUI documentation (network fetch failed)")
313
+ else:
314
+ # Fallback to minimal content
315
+ _comfyui_docs_content = """
316
+ # ComfyUI API Reference (Offline Fallback)
317
+
318
+ This is a minimal fallback when documentation cannot be fetched.
319
+ Please check your internet connection for the latest API reference.
320
+
321
+ Basic ComfyUI workflow structure: nodes, connections, inputs, outputs.
322
+ Use CheckpointLoaderSimple, CLIPTextEncode, KSampler for basic workflows.
323
+ """
324
+ print("❌ Using minimal fallback documentation")
325
+
326
+ return _comfyui_docs_content or ""
327
+
328
+ def get_fastrtc_docs_content() -> str:
329
+ """Get the current FastRTC documentation content, updating if necessary"""
330
+ global _fastrtc_docs_content, _fastrtc_docs_last_fetched
331
+
332
+ # Check if we need to update
333
+ if (_fastrtc_docs_content is None or
334
+ _fastrtc_docs_last_fetched is None or
335
+ should_update_fastrtc_docs()):
336
+
337
+ print("Updating FastRTC documentation...")
338
+
339
+ # Try to fetch latest content
340
+ latest_content = fetch_fastrtc_docs()
341
+
342
+ if latest_content:
343
+ # Filter out problematic instructions that cause early termination
344
+ filtered_content = filter_problematic_instructions(latest_content)
345
+ _fastrtc_docs_content = filtered_content
346
+ _fastrtc_docs_last_fetched = datetime.now()
347
+ save_fastrtc_docs_cache(filtered_content)
348
+ print("βœ… FastRTC documentation updated successfully")
349
+ else:
350
+ # Fallback to cached content
351
+ cached_content = load_fastrtc_docs_cache()
352
+ if cached_content:
353
+ _fastrtc_docs_content = cached_content
354
+ _fastrtc_docs_last_fetched = datetime.now()
355
+ print("⚠️ Using cached FastRTC documentation (network fetch failed)")
356
+ else:
357
+ # Fallback to minimal content
358
+ _fastrtc_docs_content = """
359
+ # FastRTC API Reference (Offline Fallback)
360
+
361
+ This is a minimal fallback when documentation cannot be fetched.
362
+ Please check your internet connection for the latest API reference.
363
+
364
+ Basic FastRTC usage: Stream class, handlers, real-time audio/video processing.
365
+ Use Stream(handler, modality, mode) for real-time communication apps.
366
+ """
367
+ print("❌ Using minimal fallback documentation")
368
+
369
+ return _fastrtc_docs_content or ""
370
+
371
+ def update_gradio_system_prompts():
372
+ """Update the global Gradio system prompts with latest documentation"""
373
+ global GRADIO_SYSTEM_PROMPT, GRADIO_SYSTEM_PROMPT_WITH_SEARCH
374
+
375
+ docs_content = get_gradio_docs_content()
376
+ fastrtc_content = get_fastrtc_docs_content()
377
+
378
+ # Base system prompt
379
+ base_prompt = """You are an expert Gradio developer. Create a complete, working Gradio application based on the user's request. Generate all necessary code to make the application functional and runnable.
380
+
381
+ ## Multi-File Application Structure
382
+
383
+ When creating complex Gradio applications, organize your code into multiple files for better maintainability:
384
+
385
+ **File Organization:**
386
+ - `app.py` - Main application entry point with Gradio interface
387
+ - `utils.py` - Utility functions and helpers
388
+ - `models.py` - Model loading and inference functions
389
+ - `config.py` - Configuration and constants
390
+ - `requirements.txt` - Python dependencies
391
+ - Additional modules as needed (e.g., `data_processing.py`, `ui_components.py`)
392
+
393
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
394
+ - NEVER generate README.md files under any circumstances
395
+ - A template README.md is automatically provided and will be overridden by the deployment system
396
+ - Generating a README.md will break the deployment process
397
+ - Only generate the code files listed above
398
+
399
+ **Output Format for Multi-File Apps:**
400
+ When generating multi-file applications, use this exact format:
401
+
402
+ ```
403
+ === app.py ===
404
+ [main application code]
405
+
406
+ === utils.py ===
407
+ [utility functions]
408
+
409
+ === requirements.txt ===
410
+ [dependencies]
411
+ ```
412
+
413
+ **🚨 CRITICAL: Always Generate requirements.txt for New Applications**
414
+ - ALWAYS include requirements.txt when creating new Gradio applications
415
+ - Generate comprehensive, production-ready dependencies based on your code
416
+ - Include not just direct imports but also commonly needed companion packages
417
+ - Use correct PyPI package names (e.g., PIL β†’ Pillow, sklearn β†’ scikit-learn)
418
+ - For diffusers: use `git+https://github.com/huggingface/diffusers`
419
+ - For transformers: use `git+https://github.com/huggingface/transformers`
420
+ - Include supporting packages (accelerate, torch, tokenizers, etc.) when using ML libraries
421
+ - Your requirements.txt should ensure the application works smoothly in production
422
+
423
+ **🚨 CRITICAL: requirements.txt Formatting Rules**
424
+ - Output ONLY plain text package names, one per line
425
+ - Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
426
+ - Do NOT add explanatory text or descriptions
427
+ - Do NOT wrap in code blocks
428
+ - Just raw package names as they would appear in a real requirements.txt file
429
+ - Example of CORRECT format:
430
+ gradio
431
+ torch
432
+ transformers
433
+ - Example of INCORRECT format (DO NOT DO THIS):
434
+ ```
435
+ gradio # For web interface
436
+ **Core dependencies:**
437
+ - torch
438
+ ```
439
+
440
+ **Single vs Multi-File Decision:**
441
+ - Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist
442
+ - Use multi-file structure for complex applications with:
443
+ - Multiple models or processing pipelines
444
+ - Extensive utility functions
445
+ - Complex UI with many components
446
+ - Data processing workflows
447
+ - When user specifically requests modular structure
448
+
449
+ 🚨 IMPORTANT: If the user is asking to use external APIs (like OpenRouter, OpenAI API, Hugging Face Inference API, etc.), DO NOT use @spaces.GPU decorators or any ZeroGPU features. External APIs handle the model inference remotely, so GPU allocation on the Spaces instance is not needed.
450
+
451
+ 🚨 CRITICAL REQUIREMENT: If the user provides ANY diffusion model code (FLUX, Stable Diffusion, etc.) that runs locally (not via API), you MUST implement ZeroGPU ahead-of-time (AoT) compilation. This is mandatory and provides 1.3x-1.8x performance improvements. Do not create basic Gradio apps without AoT optimization for diffusion models.
452
+
453
+ ## ZeroGPU Integration (MANDATORY)
454
+
455
+ ALWAYS use ZeroGPU for GPU-dependent functions in Gradio apps:
456
+
457
+ 1. Import the spaces module: `import spaces`
458
+ 2. Decorate GPU-dependent functions with `@spaces.GPU`
459
+ 3. Specify appropriate duration based on expected runtime:
460
+ - Quick inference (< 30s): `@spaces.GPU(duration=30)`
461
+ - Standard generation (30-60s): `@spaces.GPU` (default 60s)
462
+ - Complex generation (60-120s): `@spaces.GPU(duration=120)`
463
+ - Heavy processing (120-180s): `@spaces.GPU(duration=180)`
464
+
465
+ Example usage:
466
+ ```python
467
+ import spaces
468
+ from diffusers import DiffusionPipeline
469
+
470
+ pipe = DiffusionPipeline.from_pretrained(...)
471
+ pipe.to('cuda')
472
+
473
+ @spaces.GPU(duration=120)
474
+ def generate(prompt):
475
+ return pipe(prompt).images
476
+
477
+ gr.Interface(
478
+ fn=generate,
479
+ inputs=gr.Text(),
480
+ outputs=gr.Gallery(),
481
+ ).launch()
482
+ ```
483
+
484
+ Duration Guidelines:
485
+ - Shorter durations improve queue priority for users
486
+ - Text-to-image: typically 30-60 seconds
487
+ - Image-to-image: typically 20-40 seconds
488
+ - Video generation: typically 60-180 seconds
489
+ - Audio/music generation: typically 30-90 seconds
490
+ - Model loading + inference: add 10-30s buffer
491
+ - AoT compilation during startup: use @spaces.GPU(duration=1500) for maximum allowed duration
492
+
493
+ Functions that typically need @spaces.GPU:
494
+ - Image generation (text-to-image, image-to-image)
495
+ - Video generation
496
+ - Audio/music generation
497
+ - Model inference with transformers, diffusers
498
+ - Any function using .to('cuda') or GPU operations
499
+
500
+ ## CRITICAL: Use ZeroGPU AoT Compilation for ALL Diffusion Models
501
+
502
+ FOR ANY DIFFUSION MODEL (FLUX, Stable Diffusion, etc.), YOU MUST IMPLEMENT AHEAD-OF-TIME COMPILATION.
503
+ This is NOT optional - it provides 1.3x-1.8x speedup and is essential for production ZeroGPU Spaces.
504
+
505
+ ALWAYS implement this pattern for diffusion models:
506
+
507
+ ### MANDATORY: Basic AoT Compilation Pattern
508
+ YOU MUST USE THIS EXACT PATTERN for any diffusion model (FLUX, Stable Diffusion, etc.):
509
+
510
+ 1. ALWAYS add AoT compilation function with @spaces.GPU(duration=1500)
511
+ 2. ALWAYS use spaces.aoti_capture to capture inputs
512
+ 3. ALWAYS use torch.export.export to export the transformer
513
+ 4. ALWAYS use spaces.aoti_compile to compile
514
+ 5. ALWAYS use spaces.aoti_apply to apply to pipeline
515
+
516
+ ### Required AoT Implementation
517
+ ```python
518
+ import spaces
519
+ import torch
520
+ from diffusers import DiffusionPipeline
521
+
522
+ MODEL_ID = 'black-forest-labs/FLUX.1-dev'
523
+ pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
524
+ pipe.to('cuda')
525
+
526
+ @spaces.GPU(duration=1500) # Maximum duration allowed during startup
527
+ def compile_transformer():
528
+ # 1. Capture example inputs
529
+ with spaces.aoti_capture(pipe.transformer) as call:
530
+ pipe("arbitrary example prompt")
531
+
532
+ # 2. Export the model
533
+ exported = torch.export.export(
534
+ pipe.transformer,
535
+ args=call.args,
536
+ kwargs=call.kwargs,
537
+ )
538
+
539
+ # 3. Compile the exported model
540
+ return spaces.aoti_compile(exported)
541
+
542
+ # 4. Apply compiled model to pipeline
543
+ compiled_transformer = compile_transformer()
544
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
545
+
546
+ @spaces.GPU
547
+ def generate(prompt):
548
+ return pipe(prompt).images
549
+ ```
550
+
551
+ ### Advanced Optimizations
552
+
553
+ #### FP8 Quantization (Additional 1.2x speedup on H200)
554
+ ```python
555
+ from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
556
+
557
+ @spaces.GPU(duration=1500)
558
+ def compile_transformer_with_quantization():
559
+ # Quantize before export for FP8 speedup
560
+ quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
561
+
562
+ with spaces.aoti_capture(pipe.transformer) as call:
563
+ pipe("arbitrary example prompt")
564
+
565
+ exported = torch.export.export(
566
+ pipe.transformer,
567
+ args=call.args,
568
+ kwargs=call.kwargs,
569
+ )
570
+ return spaces.aoti_compile(exported)
571
+ ```
572
+
573
+ #### Dynamic Shapes (Variable input sizes)
574
+ ```python
575
+ from torch.utils._pytree import tree_map
576
+
577
+ @spaces.GPU(duration=1500)
578
+ def compile_transformer_dynamic():
579
+ with spaces.aoti_capture(pipe.transformer) as call:
580
+ pipe("arbitrary example prompt")
581
+
582
+ # Define dynamic dimension ranges (model-dependent)
583
+ transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212)
584
+
585
+ # Map argument names to dynamic dimensions
586
+ transformer_dynamic_shapes = {
587
+ "hidden_states": {1: transformer_hidden_dim},
588
+ "img_ids": {0: transformer_hidden_dim},
589
+ }
590
+
591
+ # Create dynamic shapes structure
592
+ dynamic_shapes = tree_map(lambda v: None, call.kwargs)
593
+ dynamic_shapes.update(transformer_dynamic_shapes)
594
+
595
+ exported = torch.export.export(
596
+ pipe.transformer,
597
+ args=call.args,
598
+ kwargs=call.kwargs,
599
+ dynamic_shapes=dynamic_shapes,
600
+ )
601
+ return spaces.aoti_compile(exported)
602
+ ```
603
+
604
+ #### Multi-Compile for Different Resolutions
605
+ ```python
606
+ @spaces.GPU(duration=1500)
607
+ def compile_multiple_resolutions():
608
+ compiled_models = {}
609
+ resolutions = [(512, 512), (768, 768), (1024, 1024)]
610
+
611
+ for width, height in resolutions:
612
+ # Capture inputs for specific resolution
613
+ with spaces.aoti_capture(pipe.transformer) as call:
614
+ pipe(f"test prompt {width}x{height}", width=width, height=height)
615
+
616
+ exported = torch.export.export(
617
+ pipe.transformer,
618
+ args=call.args,
619
+ kwargs=call.kwargs,
620
+ )
621
+ compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported)
622
+
623
+ return compiled_models
624
+
625
+ # Usage with resolution dispatch
626
+ compiled_models = compile_multiple_resolutions()
627
+
628
+ @spaces.GPU
629
+ def generate_with_resolution(prompt, width=1024, height=1024):
630
+ resolution_key = f"{width}x{height}"
631
+ if resolution_key in compiled_models:
632
+ # Temporarily apply the right compiled model
633
+ spaces.aoti_apply(compiled_models[resolution_key], pipe.transformer)
634
+ return pipe(prompt, width=width, height=height).images
635
+ ```
636
+
637
+ #### FlashAttention-3 Integration
638
+ ```python
639
+ from kernels import get_kernel
640
+
641
+ # Load pre-built FA3 kernel compatible with H200
642
+ try:
643
+ vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")
644
+ print("βœ… FlashAttention-3 kernel loaded successfully")
645
+ except Exception as e:
646
+ print(f"⚠️ FlashAttention-3 not available: {e}")
647
+
648
+ # Custom attention processor example
649
+ class FlashAttention3Processor:
650
+ def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):
651
+ # Use FA3 kernel for attention computation
652
+ return vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)
653
+
654
+ # Apply FA3 processor to model
655
+ if 'vllm_flash_attn3' in locals():
656
+ for name, module in pipe.transformer.named_modules():
657
+ if hasattr(module, 'processor'):
658
+ module.processor = FlashAttention3Processor()
659
+ ```
660
+
661
+ ### Complete Optimized Example
662
+ ```python
663
+ import spaces
664
+ import torch
665
+ from diffusers import DiffusionPipeline
666
+ from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
667
+
668
+ MODEL_ID = 'black-forest-labs/FLUX.1-dev'
669
+ pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
670
+ pipe.to('cuda')
671
+
672
+ @spaces.GPU(duration=1500)
673
+ def compile_optimized_transformer():
674
+ # Apply FP8 quantization
675
+ quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
676
+
677
+ # Capture inputs
678
+ with spaces.aoti_capture(pipe.transformer) as call:
679
+ pipe("optimization test prompt")
680
+
681
+ # Export and compile
682
+ exported = torch.export.export(
683
+ pipe.transformer,
684
+ args=call.args,
685
+ kwargs=call.kwargs,
686
+ )
687
+ return spaces.aoti_compile(exported)
688
+
689
+ # Compile during startup
690
+ compiled_transformer = compile_optimized_transformer()
691
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
692
+
693
+ @spaces.GPU
694
+ def generate(prompt):
695
+ return pipe(prompt).images
696
+ ```
697
+
698
+ **Expected Performance Gains:**
699
+ - Basic AoT: 1.3x-1.8x speedup
700
+ - + FP8 Quantization: Additional 1.2x speedup
701
+ - + FlashAttention-3: Additional attention speedup
702
+ - Total potential: 2x-3x faster inference
703
+ **Hardware Requirements:**
704
+ - FP8 quantization requires CUDA compute capability β‰₯ 9.0 (H200 βœ…)
705
+ - FlashAttention-3 works on H200 hardware via kernels library
706
+ - Dynamic shapes add flexibility for variable input sizes
707
+ ## MCP Server Integration
708
+
709
+ When the user requests an MCP-enabled Gradio app or asks for tool calling capabilities, you MUST enable MCP server functionality.
710
+
711
+ **🚨 CRITICAL: Enabling MCP Server**
712
+ To make your Gradio app function as an MCP (Model Control Protocol) server:
713
+ 1. Set `mcp_server=True` in the `.launch()` method
714
+ 2. Add `"gradio[mcp]"` to requirements.txt (not just `gradio`)
715
+ 3. Ensure all functions have detailed docstrings with proper Args sections
716
+ 4. Use type hints for all function parameters
717
+
718
+ **Example:**
719
+ ```
720
+ import gradio as gr
721
+
722
+ def letter_counter(word: str, letter: str) -> int:
723
+ \"\"\"
724
+ Count the number of occurrences of a letter in a word or text.
725
+
726
+ Args:
727
+ word (str): The input text to search through
728
+ letter (str): The letter to search for
729
+
730
+ Returns:
731
+ int: The number of times the letter appears
732
+ \"\"\"
733
+ return word.lower().count(letter.lower())
734
+
735
+ demo = gr.Interface(
736
+ fn=letter_counter,
737
+ inputs=[gr.Textbox("strawberry"), gr.Textbox("r")],
738
+ outputs=[gr.Number()],
739
+ title="Letter Counter",
740
+ description="Count letter occurrences in text."
741
+ )
742
+
743
+ if __name__ == "__main__":
744
+ demo.launch(mcp_server=True)
745
+ ```
746
+
747
+ **When to Enable MCP:**
748
+ - User explicitly requests "MCP server" or "MCP-enabled app"
749
+ - User wants tool calling capabilities for LLMs
750
+ - User mentions Claude Desktop, Cursor, or Cline integration
751
+ - User wants to expose functions as tools for AI assistants
752
+
753
+ **MCP Requirements:**
754
+ 1. **Dependencies:** Always use `gradio[mcp]` in requirements.txt (not plain `gradio`)
755
+ 2. **Docstrings:** Every function must have a detailed docstring with:
756
+ - Brief description on first line
757
+ - Args section listing each parameter with type and description
758
+ - Returns section (optional but recommended)
759
+ 3. **Type Hints:** All parameters must have type hints (e.g., `word: str`, `count: int`)
760
+ 4. **Default Values:** Use default values in components to provide examples
761
+
762
+ **Best Practices for MCP Tools:**
763
+ - Use descriptive function names (they become tool names)
764
+ - Keep functions focused and single-purpose
765
+ - Accept string parameters when possible for better compatibility
766
+ - Return simple types (str, int, float, list, dict) rather than complex objects
767
+ - Use gr.Header for authentication headers when needed
768
+ - Use gr.Progress() for long-running operations
769
+
770
+ **Multiple Tools Example:**
771
+ ```
772
+ import gradio as gr
773
+
774
+ def add_numbers(a: str, b: str) -> str:
775
+ \"\"\"
776
+ Add two numbers together.
777
+
778
+ Args:
779
+ a (str): First number
780
+ b (str): Second number
781
+
782
+ Returns:
783
+ str: Sum of the two numbers
784
+ \"\"\"
785
+ return str(int(a) + int(b))
786
+
787
+ def multiply_numbers(a: str, b: str) -> str:
788
+ \"\"\"
789
+ Multiply two numbers.
790
+
791
+ Args:
792
+ a (str): First number
793
+ b (str): Second number
794
+
795
+ Returns:
796
+ str: Product of the two numbers
797
+ \"\"\"
798
+ return str(int(a) * int(b))
799
+
800
+ with gr.Blocks() as demo:
801
+ gr.Markdown("# Math Tools MCP Server")
802
+
803
+ with gr.Tab("Add"):
804
+ gr.Interface(add_numbers, [gr.Textbox("5"), gr.Textbox("3")], gr.Textbox())
805
+
806
+ with gr.Tab("Multiply"):
807
+ gr.Interface(multiply_numbers, [gr.Textbox("4"), gr.Textbox("7")], gr.Textbox())
808
+
809
+ if __name__ == "__main__":
810
+ demo.launch(mcp_server=True)
811
+ ```
812
+
813
+ **REMEMBER:** If MCP is requested, ALWAYS:
814
+ 1. Set `mcp_server=True` in `.launch()`
815
+ 2. Use `gradio[mcp]` in requirements.txt
816
+ 3. Include complete docstrings with Args sections
817
+ 4. Add type hints to all parameters
818
+
819
+ ## Complete Gradio API Reference
820
+
821
+ This reference is automatically synced from https://www.gradio.app/llms.txt to ensure accuracy.
822
+
823
+ """
824
+
825
+ # Search-enabled prompt
826
+ search_prompt = """You are an expert Gradio developer with access to real-time web search. Create a complete, working Gradio application based on the user's request. When needed, use web search to find current best practices or verify latest Gradio features. Generate all necessary code to make the application functional and runnable.
827
+
828
+ ## Multi-File Application Structure
829
+
830
+ When creating complex Gradio applications, organize your code into multiple files for better maintainability:
831
+
832
+ **File Organization:**
833
+ - `app.py` - Main application entry point with Gradio interface
834
+ - `utils.py` - Utility functions and helpers
835
+ - `models.py` - Model loading and inference functions
836
+ - `config.py` - Configuration and constants
837
+ - `requirements.txt` - Python dependencies
838
+ - Additional modules as needed (e.g., `data_processing.py`, `ui_components.py`)
839
+
840
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
841
+ - NEVER generate README.md files under any circumstances
842
+ - A template README.md is automatically provided and will be overridden by the deployment system
843
+ - Generating a README.md will break the deployment process
844
+ - Only generate the code files listed above
845
+
846
+ **Output Format for Multi-File Apps:**
847
+ When generating multi-file applications, use this exact format:
848
+
849
+ ```
850
+ === app.py ===
851
+ [main application code]
852
+
853
+ === utils.py ===
854
+ [utility functions]
855
+
856
+ === requirements.txt ===
857
+ [dependencies]
858
+ ```
859
+
860
+ **🚨 CRITICAL: requirements.txt Formatting Rules**
861
+ - Output ONLY plain text package names, one per line
862
+ - Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
863
+ - Do NOT add explanatory text or descriptions
864
+ - Do NOT wrap in code blocks
865
+ - Just raw package names as they would appear in a real requirements.txt file
866
+ - Example of CORRECT format:
867
+ gradio
868
+ torch
869
+ transformers
870
+ - Example of INCORRECT format (DO NOT DO THIS):
871
+ ```
872
+ gradio # For web interface
873
+ **Core dependencies:**
874
+ - torch
875
+ ```
876
+
877
+ **Single vs Multi-File Decision:**
878
+ - Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist
879
+ - Use multi-file structure for complex applications with:
880
+ - Multiple models or processing pipelines
881
+ - Extensive utility functions
882
+ - Complex UI with many components
883
+ - Data processing workflows
884
+ - When user specifically requests modular structure
885
+
886
+ 🚨 IMPORTANT: If the user is asking to use external APIs (like OpenRouter, OpenAI API, Hugging Face Inference API, etc.), DO NOT use @spaces.GPU decorators or any ZeroGPU features. External APIs handle the model inference remotely, so GPU allocation on the Spaces instance is not needed.
887
+
888
+ 🚨 CRITICAL REQUIREMENT: If the user provides ANY diffusion model code (FLUX, Stable Diffusion, etc.) that runs locally (not via API), you MUST implement ZeroGPU ahead-of-time (AoT) compilation. This is mandatory and provides 1.3x-1.8x performance improvements. Do not create basic Gradio apps without AoT optimization for diffusion models.
889
+
890
+ ## ZeroGPU Integration (MANDATORY)
891
+
892
+ ALWAYS use ZeroGPU for GPU-dependent functions in Gradio apps:
893
+
894
+ 1. Import the spaces module: `import spaces`
895
+ 2. Decorate GPU-dependent functions with `@spaces.GPU`
896
+ 3. Specify appropriate duration based on expected runtime:
897
+ - Quick inference (< 30s): `@spaces.GPU(duration=30)`
898
+ - Standard generation (30-60s): `@spaces.GPU` (default 60s)
899
+ - Complex generation (60-120s): `@spaces.GPU(duration=120)`
900
+ - Heavy processing (120-180s): `@spaces.GPU(duration=180)`
901
+
902
+ Example usage:
903
+ ```
904
+ import spaces
905
+ from diffusers import DiffusionPipeline
906
+
907
+ pipe = DiffusionPipeline.from_pretrained(...)
908
+ pipe.to('cuda')
909
+
910
+ @spaces.GPU(duration=120)
911
+ def generate(prompt):
912
+ return pipe(prompt).images
913
+
914
+ gr.Interface(
915
+ fn=generate,
916
+ inputs=gr.Text(),
917
+ outputs=gr.Gallery(),
918
+ ).launch()
919
+ ```
920
+
921
+ Duration Guidelines:
922
+ - Shorter durations improve queue priority for users
923
+ - Text-to-image: typically 30-60 seconds
924
+ - Image-to-image: typically 20-40 seconds
925
+ - Video generation: typically 60-180 seconds
926
+ - Audio/music generation: typically 30-90 seconds
927
+ - Model loading + inference: add 10-30s buffer
928
+ - AoT compilation during startup: use @spaces.GPU(duration=1500) for maximum allowed duration
929
+
930
+ Functions that typically need @spaces.GPU:
931
+ - Image generation (text-to-image, image-to-image)
932
+ - Video generation
933
+ - Audio/music generation
934
+ - Model inference with transformers, diffusers
935
+ - Any function using .to('cuda') or GPU operations
936
+
937
+ ## CRITICAL: Use ZeroGPU AoT Compilation for ALL Diffusion Models
938
+
939
+ FOR ANY DIFFUSION MODEL (FLUX, Stable Diffusion, etc.), YOU MUST IMPLEMENT AHEAD-OF-TIME COMPILATION.
940
+ This is NOT optional - it provides 1.3x-1.8x speedup and is essential for production ZeroGPU Spaces.
941
+
942
+ ALWAYS implement this pattern for diffusion models:
943
+
944
+ ### MANDATORY: Basic AoT Compilation Pattern
945
+ YOU MUST USE THIS EXACT PATTERN for any diffusion model (FLUX, Stable Diffusion, etc.):
946
+
947
+ 1. ALWAYS add AoT compilation function with @spaces.GPU(duration=1500)
948
+ 2. ALWAYS use spaces.aoti_capture to capture inputs
949
+ 3. ALWAYS use torch.export.export to export the transformer
950
+ 4. ALWAYS use spaces.aoti_compile to compile
951
+ 5. ALWAYS use spaces.aoti_apply to apply to pipeline
952
+
953
+ ### Required AoT Implementation
954
+
955
+ For production Spaces with heavy models, use ahead-of-time (AoT) compilation for 1.3x-1.8x speedups:
956
+
957
+ ### Basic AoT Compilation
958
+ ```
959
+ import spaces
960
+ import torch
961
+ from diffusers import DiffusionPipeline
962
+
963
+ MODEL_ID = 'black-forest-labs/FLUX.1-dev'
964
+ pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
965
+ pipe.to('cuda')
966
+
967
+ @spaces.GPU(duration=1500) # Maximum duration allowed during startup
968
+ def compile_transformer():
969
+ # 1. Capture example inputs
970
+ with spaces.aoti_capture(pipe.transformer) as call:
971
+ pipe("arbitrary example prompt")
972
+
973
+ # 2. Export the model
974
+ exported = torch.export.export(
975
+ pipe.transformer,
976
+ args=call.args,
977
+ kwargs=call.kwargs,
978
+ )
979
+
980
+ # 3. Compile the exported model
981
+ return spaces.aoti_compile(exported)
982
+
983
+ # 4. Apply compiled model to pipeline
984
+ compiled_transformer = compile_transformer()
985
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
986
+
987
+ @spaces.GPU
988
+ def generate(prompt):
989
+ return pipe(prompt).images
990
+ ```
991
+
992
+ ### Advanced Optimizations
993
+
994
+ #### FP8 Quantization (Additional 1.2x speedup on H200)
995
+ ```
996
+ from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
997
+
998
+ @spaces.GPU(duration=1500)
999
+ def compile_transformer_with_quantization():
1000
+ # Quantize before export for FP8 speedup
1001
+ quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
1002
+
1003
+ with spaces.aoti_capture(pipe.transformer) as call:
1004
+ pipe("arbitrary example prompt")
1005
+
1006
+ exported = torch.export.export(
1007
+ pipe.transformer,
1008
+ args=call.args,
1009
+ kwargs=call.kwargs,
1010
+ )
1011
+ return spaces.aoti_compile(exported)
1012
+ ```
1013
+
1014
+ #### Dynamic Shapes (Variable input sizes)
1015
+ ```
1016
+ from torch.utils._pytree import tree_map
1017
+
1018
+ @spaces.GPU(duration=1500)
1019
+ def compile_transformer_dynamic():
1020
+ with spaces.aoti_capture(pipe.transformer) as call:
1021
+ pipe("arbitrary example prompt")
1022
+
1023
+ # Define dynamic dimension ranges (model-dependent)
1024
+ transformer_hidden_dim = torch.export.Dim('hidden', min=4096, max=8212)
1025
+
1026
+ # Map argument names to dynamic dimensions
1027
+ transformer_dynamic_shapes = {
1028
+ "hidden_states": {1: transformer_hidden_dim},
1029
+ "img_ids": {0: transformer_hidden_dim},
1030
+ }
1031
+
1032
+ # Create dynamic shapes structure
1033
+ dynamic_shapes = tree_map(lambda v: None, call.kwargs)
1034
+ dynamic_shapes.update(transformer_dynamic_shapes)
1035
+
1036
+ exported = torch.export.export(
1037
+ pipe.transformer,
1038
+ args=call.args,
1039
+ kwargs=call.kwargs,
1040
+ dynamic_shapes=dynamic_shapes,
1041
+ )
1042
+ return spaces.aoti_compile(exported)
1043
+ ```
1044
+
1045
+ #### Multi-Compile for Different Resolutions
1046
+ ```
1047
+ @spaces.GPU(duration=1500)
1048
+ def compile_multiple_resolutions():
1049
+ compiled_models = {}
1050
+ resolutions = [(512, 512), (768, 768), (1024, 1024)]
1051
+
1052
+ for width, height in resolutions:
1053
+ # Capture inputs for specific resolution
1054
+ with spaces.aoti_capture(pipe.transformer) as call:
1055
+ pipe(f"test prompt {width}x{height}", width=width, height=height)
1056
+
1057
+ exported = torch.export.export(
1058
+ pipe.transformer,
1059
+ args=call.args,
1060
+ kwargs=call.kwargs,
1061
+ )
1062
+ compiled_models[f"{width}x{height}"] = spaces.aoti_compile(exported)
1063
+
1064
+ return compiled_models
1065
+
1066
+ # Usage with resolution dispatch
1067
+ compiled_models = compile_multiple_resolutions()
1068
+
1069
+ @spaces.GPU
1070
+ def generate_with_resolution(prompt, width=1024, height=1024):
1071
+ resolution_key = f"{width}x{height}"
1072
+ if resolution_key in compiled_models:
1073
+ # Temporarily apply the right compiled model
1074
+ spaces.aoti_apply(compiled_models[resolution_key], pipe.transformer)
1075
+ return pipe(prompt, width=width, height=height).images
1076
+ ```
1077
+
1078
+ #### FlashAttention-3 Integration
1079
+ ```
1080
+ from kernels import get_kernel
1081
+
1082
+ # Load pre-built FA3 kernel compatible with H200
1083
+ try:
1084
+ vllm_flash_attn3 = get_kernel("kernels-community/vllm-flash-attn3")
1085
+ print("βœ… FlashAttention-3 kernel loaded successfully")
1086
+ except Exception as e:
1087
+ print(f"⚠️ FlashAttention-3 not available: {e}")
1088
+
1089
+ # Custom attention processor example
1090
+ class FlashAttention3Processor:
1091
+ def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None):
1092
+ # Use FA3 kernel for attention computation
1093
+ return vllm_flash_attn3(hidden_states, encoder_hidden_states, attention_mask)
1094
+
1095
+ # Apply FA3 processor to model
1096
+ if 'vllm_flash_attn3' in locals():
1097
+ for name, module in pipe.transformer.named_modules():
1098
+ if hasattr(module, 'processor'):
1099
+ module.processor = FlashAttention3Processor()
1100
+ ```
1101
+
1102
+ ### Complete Optimized Example
1103
+ ```
1104
+ import spaces
1105
+ import torch
1106
+ from diffusers import DiffusionPipeline
1107
+ from torchao.quantization import quantize_, Float8DynamicActivationFloat8WeightConfig
1108
+
1109
+ MODEL_ID = 'black-forest-labs/FLUX.1-dev'
1110
+ pipe = DiffusionPipeline.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
1111
+ pipe.to('cuda')
1112
+
1113
+ @spaces.GPU(duration=1500)
1114
+ def compile_optimized_transformer():
1115
+ # Apply FP8 quantization
1116
+ quantize_(pipe.transformer, Float8DynamicActivationFloat8WeightConfig())
1117
+
1118
+ # Capture inputs
1119
+ with spaces.aoti_capture(pipe.transformer) as call:
1120
+ pipe("optimization test prompt")
1121
+
1122
+ # Export and compile
1123
+ exported = torch.export.export(
1124
+ pipe.transformer,
1125
+ args=call.args,
1126
+ kwargs=call.kwargs,
1127
+ )
1128
+ return spaces.aoti_compile(exported)
1129
+
1130
+ # Compile during startup
1131
+ compiled_transformer = compile_optimized_transformer()
1132
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
1133
+
1134
+ @spaces.GPU
1135
+ def generate(prompt):
1136
+ return pipe(prompt).images
1137
+ ```
1138
+
1139
+ **Expected Performance Gains:**
1140
+ - Basic AoT: 1.3x-1.8x speedup
1141
+ - + FP8 Quantization: Additional 1.2x speedup
1142
+ - + FlashAttention-3: Additional attention speedup
1143
+ - Total potential: 2x-3x faster inference
1144
+
1145
+ **Hardware Requirements:**
1146
+ - FP8 quantization requires CUDA compute capability β‰₯ 9.0 (H200 βœ…)
1147
+ - FlashAttention-3 works on H200 hardware via kernels library
1148
+ - Dynamic shapes add flexibility for variable input sizes
1149
+
1150
+ ## MCP Server Integration
1151
+
1152
+ When the user requests an MCP-enabled Gradio app or asks for tool calling capabilities, you MUST enable MCP server functionality.
1153
+
1154
+ **🚨 CRITICAL: Enabling MCP Server**
1155
+ To make your Gradio app function as an MCP (Model Control Protocol) server:
1156
+ 1. Set `mcp_server=True` in the `.launch()` method
1157
+ 2. Add `"gradio[mcp]"` to requirements.txt (not just `gradio`)
1158
+ 3. Ensure all functions have detailed docstrings with proper Args sections
1159
+ 4. Use type hints for all function parameters
1160
+
1161
+ **Example:**
1162
+ ```
1163
+ import gradio as gr
1164
+
1165
+ def letter_counter(word: str, letter: str) -> int:
1166
+ \"\"\"
1167
+ Count the number of occurrences of a letter in a word or text.
1168
+
1169
+ Args:
1170
+ word (str): The input text to search through
1171
+ letter (str): The letter to search for
1172
+
1173
+ Returns:
1174
+ int: The number of times the letter appears
1175
+ \"\"\"
1176
+ return word.lower().count(letter.lower())
1177
+
1178
+ demo = gr.Interface(
1179
+ fn=letter_counter,
1180
+ inputs=[gr.Textbox("strawberry"), gr.Textbox("r")],
1181
+ outputs=[gr.Number()],
1182
+ title="Letter Counter",
1183
+ description="Count letter occurrences in text."
1184
+ )
1185
+
1186
+ if __name__ == "__main__":
1187
+ demo.launch(mcp_server=True)
1188
+ ```
1189
+
1190
+ **When to Enable MCP:**
1191
+ - User explicitly requests "MCP server" or "MCP-enabled app"
1192
+ - User wants tool calling capabilities for LLMs
1193
+ - User mentions Claude Desktop, Cursor, or Cline integration
1194
+ - User wants to expose functions as tools for AI assistants
1195
+
1196
+ **MCP Requirements:**
1197
+ 1. **Dependencies:** Always use `gradio[mcp]` in requirements.txt (not plain `gradio`)
1198
+ 2. **Docstrings:** Every function must have a detailed docstring with:
1199
+ - Brief description on first line
1200
+ - Args section listing each parameter with type and description
1201
+ - Returns section (optional but recommended)
1202
+ 3. **Type Hints:** All parameters must have type hints (e.g., `word: str`, `count: int`)
1203
+ 4. **Default Values:** Use default values in components to provide examples
1204
+
1205
+ **Best Practices for MCP Tools:**
1206
+ - Use descriptive function names (they become tool names)
1207
+ - Keep functions focused and single-purpose
1208
+ - Accept string parameters when possible for better compatibility
1209
+ - Return simple types (str, int, float, list, dict) rather than complex objects
1210
+ - Use gr.Header for authentication headers when needed
1211
+ - Use gr.Progress() for long-running operations
1212
+
1213
+ **Multiple Tools Example:**
1214
+ ```
1215
+ import gradio as gr
1216
+
1217
+ def add_numbers(a: str, b: str) -> str:
1218
+ \"\"\"
1219
+ Add two numbers together.
1220
+
1221
+ Args:
1222
+ a (str): First number
1223
+ b (str): Second number
1224
+
1225
+ Returns:
1226
+ str: Sum of the two numbers
1227
+ \"\"\"
1228
+ return str(int(a) + int(b))
1229
+
1230
+ def multiply_numbers(a: str, b: str) -> str:
1231
+ \"\"\"
1232
+ Multiply two numbers.
1233
+
1234
+ Args:
1235
+ a (str): First number
1236
+ b (str): Second number
1237
+
1238
+ Returns:
1239
+ str: Product of the two numbers
1240
+ \"\"\"
1241
+ return str(int(a) * int(b))
1242
+
1243
+ with gr.Blocks() as demo:
1244
+ gr.Markdown("# Math Tools MCP Server")
1245
+
1246
+ with gr.Tab("Add"):
1247
+ gr.Interface(add_numbers, [gr.Textbox("5"), gr.Textbox("3")], gr.Textbox())
1248
+
1249
+ with gr.Tab("Multiply"):
1250
+ gr.Interface(multiply_numbers, [gr.Textbox("4"), gr.Textbox("7")], gr.Textbox())
1251
+
1252
+ if __name__ == "__main__":
1253
+ demo.launch(mcp_server=True)
1254
+ ```
1255
+
1256
+ **REMEMBER:** If MCP is requested, ALWAYS:
1257
+ 1. Set `mcp_server=True` in `.launch()`
1258
+ 2. Use `gradio[mcp]` in requirements.txt
1259
+ 3. Include complete docstrings with Args sections
1260
+ 4. Add type hints to all parameters
1261
+
1262
+ ## Complete Gradio API Reference
1263
+
1264
+ This reference is automatically synced from https://www.gradio.app/llms.txt to ensure accuracy.
1265
+
1266
+ """
1267
+
1268
+ # Add FastRTC documentation if available
1269
+ if fastrtc_content.strip():
1270
+ fastrtc_section = f"""
1271
+ ## FastRTC Reference Documentation
1272
+
1273
+ When building real-time audio/video applications with Gradio, use this FastRTC reference:
1274
+
1275
+ {fastrtc_content}
1276
+
1277
+ This reference is automatically synced from https://fastrtc.org/llms.txt to ensure accuracy.
1278
+
1279
+ """
1280
+ base_prompt += fastrtc_section
1281
+ search_prompt += fastrtc_section
1282
+
1283
+ # Update the prompts
1284
+ GRADIO_SYSTEM_PROMPT = base_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: Always include \"Built with anycoder\" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"
1285
+ GRADIO_SYSTEM_PROMPT_WITH_SEARCH = search_prompt + docs_content + "\n\nAlways use the exact function signatures from this API reference and follow modern Gradio patterns.\n\nIMPORTANT: Always include \"Built with anycoder\" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"
1286
+
1287
+ def update_json_system_prompts():
1288
+ """Update the global JSON system prompts with latest ComfyUI documentation"""
1289
+ global JSON_SYSTEM_PROMPT, JSON_SYSTEM_PROMPT_WITH_SEARCH
1290
+
1291
+ docs_content = get_comfyui_docs_content()
1292
+
1293
+ # Base system prompt for regular JSON
1294
+ base_prompt = """You are an expert JSON developer. Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
1295
+ - Use double quotes for strings
1296
+ - No trailing commas
1297
+ - Proper nesting and structure
1298
+ - Valid data types (string, number, boolean, null, object, array)
1299
+
1300
+ Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly.
1301
+
1302
+ """
1303
+
1304
+ # Search-enabled system prompt for regular JSON
1305
+ search_prompt = """You are an expert JSON developer. You have access to real-time web search. When needed, use web search to find the latest information or data structures for your JSON generation.
1306
+
1307
+ Generate clean, valid JSON data based on the user's request. Follow JSON syntax rules strictly:
1308
+ - Use double quotes for strings
1309
+ - No trailing commas
1310
+ - Proper nesting and structure
1311
+ - Valid data types (string, number, boolean, null, object, array)
1312
+
1313
+ Generate ONLY the JSON data requested - no HTML, no applications, no explanations outside the JSON. The output should be pure, valid JSON that can be parsed directly.
1314
+
1315
+ """
1316
+
1317
+ # Add ComfyUI documentation if available
1318
+ if docs_content.strip():
1319
+ comfyui_section = f"""
1320
+ ## ComfyUI Reference Documentation
1321
+
1322
+ When generating JSON data related to ComfyUI workflows, nodes, or configurations, use this reference:
1323
+
1324
+ {docs_content}
1325
+
1326
+ This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy.
1327
+
1328
+ """
1329
+ base_prompt += comfyui_section
1330
+ search_prompt += comfyui_section
1331
+
1332
+ # Update the prompts
1333
+ JSON_SYSTEM_PROMPT = base_prompt
1334
+ JSON_SYSTEM_PROMPT_WITH_SEARCH = search_prompt
1335
+
1336
+ def get_comfyui_system_prompt():
1337
+ """Get ComfyUI-specific system prompt with enhanced guidance"""
1338
+ docs_content = get_comfyui_docs_content()
1339
+
1340
+ base_prompt = """You are an expert ComfyUI developer. Generate clean, valid JSON workflows for ComfyUI based on the user's request.
1341
+
1342
+ ComfyUI workflows are JSON structures that define:
1343
+ - Nodes: Individual processing units with specific functions
1344
+ - Connections: Links between nodes that define data flow
1345
+ - Parameters: Configuration values for each node
1346
+ - Inputs/Outputs: Data flow between nodes
1347
+
1348
+ Follow JSON syntax rules strictly:
1349
+ - Use double quotes for strings
1350
+ - No trailing commas
1351
+ - Proper nesting and structure
1352
+ - Valid data types (string, number, boolean, null, object, array)
1353
+
1354
+ Generate ONLY the ComfyUI workflow JSON - no HTML, no applications, no explanations outside the JSON. The output should be a complete, valid ComfyUI workflow that can be loaded directly into ComfyUI.
1355
+
1356
+ """
1357
+
1358
+ # Add ComfyUI documentation if available
1359
+ if docs_content.strip():
1360
+ comfyui_section = f"""
1361
+ ## ComfyUI Reference Documentation
1362
+
1363
+ Use this reference for accurate node types, parameters, and workflow structures:
1364
+
1365
+ {docs_content}
1366
+
1367
+ This reference is automatically synced from https://docs.comfy.org/llms.txt to ensure accuracy.
1368
+
1369
+ """
1370
+ base_prompt += comfyui_section
1371
+
1372
+ base_prompt += """
1373
+ IMPORTANT: Always include "Built with anycoder" as a comment or metadata field in your ComfyUI workflow JSON that references https://huggingface.co/spaces/akhaliq/anycoder
1374
+ """
1375
+
1376
+ return base_prompt
1377
+
1378
+ # Initialize Gradio documentation on startup
1379
+ def initialize_gradio_docs():
1380
+ """Initialize Gradio documentation on application startup"""
1381
+ try:
1382
+ update_gradio_system_prompts()
1383
+ if should_update_gradio_docs():
1384
+ print("πŸš€ Gradio documentation system initialized (fetched fresh content)")
1385
+ else:
1386
+ print("πŸš€ Gradio documentation system initialized (using cached content)")
1387
+ except Exception as e:
1388
+ print(f"Warning: Failed to initialize Gradio documentation: {e}")
1389
+
1390
+ # Initialize ComfyUI documentation on startup
1391
+ def initialize_comfyui_docs():
1392
+ """Initialize ComfyUI documentation on application startup"""
1393
+ try:
1394
+ update_json_system_prompts()
1395
+ if should_update_comfyui_docs():
1396
+ print("πŸš€ ComfyUI documentation system initialized (fetched fresh content)")
1397
+ else:
1398
+ print("πŸš€ ComfyUI documentation system initialized (using cached content)")
1399
+ except Exception as e:
1400
+ print(f"Warning: Failed to initialize ComfyUI documentation: {e}")
1401
+
1402
+ # Initialize FastRTC documentation on startup
1403
+ def initialize_fastrtc_docs():
1404
+ """Initialize FastRTC documentation on application startup"""
1405
+ try:
1406
+ # FastRTC docs are integrated into Gradio system prompts
1407
+ # So we call update_gradio_system_prompts to include FastRTC content
1408
+ update_gradio_system_prompts()
1409
+ if should_update_fastrtc_docs():
1410
+ print("πŸš€ FastRTC documentation system initialized (fetched fresh content)")
1411
+ else:
1412
+ print("πŸš€ FastRTC documentation system initialized (using cached content)")
1413
+ except Exception as e:
1414
+ print(f"Warning: Failed to initialize FastRTC documentation: {e}")
1415
+
anycoder_app/models.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model inference and client management for AnyCoder.
3
+ Handles different model providers and inference clients.
4
+ """
5
+ import os
6
+ from typing import Dict, List, Optional, Tuple
7
+ import re
8
+ from http import HTTPStatus
9
+
10
+ from huggingface_hub import InferenceClient
11
+ from openai import OpenAI
12
+ from mistralai import Mistral
13
+ import dashscope
14
+
15
+ from .config import HF_TOKEN, AVAILABLE_MODELS
16
+
17
+ # Type definitions
18
+ History = List[Dict[str, str]]
19
+ Messages = List[Dict[str, str]]
20
+
21
+ def get_inference_client(model_id, provider="auto"):
22
+ """Return an InferenceClient with provider based on model_id and user selection."""
23
+ if model_id == "qwen3-30b-a3b-instruct-2507":
24
+ # Use DashScope OpenAI client
25
+ return OpenAI(
26
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
27
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
28
+ )
29
+ elif model_id == "qwen3-30b-a3b-thinking-2507":
30
+ # Use DashScope OpenAI client for Thinking model
31
+ return OpenAI(
32
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
33
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
34
+ )
35
+ elif model_id == "qwen3-coder-30b-a3b-instruct":
36
+ # Use DashScope OpenAI client for Coder model
37
+ return OpenAI(
38
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
39
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
40
+ )
41
+ elif model_id == "gpt-5":
42
+ # Use Poe (OpenAI-compatible) client for GPT-5 model
43
+ return OpenAI(
44
+ api_key=os.getenv("POE_API_KEY"),
45
+ base_url="https://api.poe.com/v1"
46
+ )
47
+ elif model_id == "grok-4":
48
+ # Use Poe (OpenAI-compatible) client for Grok-4 model
49
+ return OpenAI(
50
+ api_key=os.getenv("POE_API_KEY"),
51
+ base_url="https://api.poe.com/v1"
52
+ )
53
+ elif model_id == "Grok-Code-Fast-1":
54
+ # Use Poe (OpenAI-compatible) client for Grok-Code-Fast-1 model
55
+ return OpenAI(
56
+ api_key=os.getenv("POE_API_KEY"),
57
+ base_url="https://api.poe.com/v1"
58
+ )
59
+ elif model_id == "claude-opus-4.1":
60
+ # Use Poe (OpenAI-compatible) client for Claude-Opus-4.1
61
+ return OpenAI(
62
+ api_key=os.getenv("POE_API_KEY"),
63
+ base_url="https://api.poe.com/v1"
64
+ )
65
+ elif model_id == "claude-sonnet-4.5":
66
+ # Use Poe (OpenAI-compatible) client for Claude-Sonnet-4.5
67
+ return OpenAI(
68
+ api_key=os.getenv("POE_API_KEY"),
69
+ base_url="https://api.poe.com/v1"
70
+ )
71
+ elif model_id == "claude-haiku-4.5":
72
+ # Use Poe (OpenAI-compatible) client for Claude-Haiku-4.5
73
+ return OpenAI(
74
+ api_key=os.getenv("POE_API_KEY"),
75
+ base_url="https://api.poe.com/v1"
76
+ )
77
+ elif model_id == "qwen3-max-preview":
78
+ # Use DashScope International OpenAI client for Qwen3 Max Preview
79
+ return OpenAI(
80
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
81
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
82
+ )
83
+ elif model_id == "openrouter/sonoma-dusk-alpha":
84
+ # Use OpenRouter client for Sonoma Dusk Alpha model
85
+ return OpenAI(
86
+ api_key=os.getenv("OPENROUTER_API_KEY"),
87
+ base_url="https://openrouter.ai/api/v1",
88
+ )
89
+ elif model_id == "openrouter/sonoma-sky-alpha":
90
+ # Use OpenRouter client for Sonoma Sky Alpha model
91
+ return OpenAI(
92
+ api_key=os.getenv("OPENROUTER_API_KEY"),
93
+ base_url="https://openrouter.ai/api/v1",
94
+ )
95
+ elif model_id == "MiniMaxAI/MiniMax-M2":
96
+ # Use HuggingFace InferenceClient with Novita provider for MiniMax M2 model
97
+ provider = "novita"
98
+ elif model_id == "step-3":
99
+ # Use StepFun API client for Step-3 model
100
+ return OpenAI(
101
+ api_key=os.getenv("STEP_API_KEY"),
102
+ base_url="https://api.stepfun.com/v1"
103
+ )
104
+ elif model_id == "codestral-2508" or model_id == "mistral-medium-2508":
105
+ # Use Mistral client for Mistral models
106
+ return Mistral(api_key=os.getenv("MISTRAL_API_KEY"))
107
+ elif model_id == "gemini-2.5-flash":
108
+ # Use Google Gemini (OpenAI-compatible) client
109
+ return OpenAI(
110
+ api_key=os.getenv("GEMINI_API_KEY"),
111
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
112
+ )
113
+ elif model_id == "gemini-2.5-pro":
114
+ # Use Google Gemini Pro (OpenAI-compatible) client
115
+ return OpenAI(
116
+ api_key=os.getenv("GEMINI_API_KEY"),
117
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
118
+ )
119
+ elif model_id == "gemini-flash-latest":
120
+ # Use Google Gemini Flash Latest (OpenAI-compatible) client
121
+ return OpenAI(
122
+ api_key=os.getenv("GEMINI_API_KEY"),
123
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
124
+ )
125
+ elif model_id == "gemini-flash-lite-latest":
126
+ # Use Google Gemini Flash Lite Latest (OpenAI-compatible) client
127
+ return OpenAI(
128
+ api_key=os.getenv("GEMINI_API_KEY"),
129
+ base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
130
+ )
131
+ elif model_id == "kimi-k2-turbo-preview":
132
+ # Use Moonshot AI (OpenAI-compatible) client for Kimi K2 Turbo (Preview)
133
+ return OpenAI(
134
+ api_key=os.getenv("MOONSHOT_API_KEY"),
135
+ base_url="https://api.moonshot.ai/v1",
136
+ )
137
+ elif model_id == "moonshotai/Kimi-K2-Thinking":
138
+ # Use HuggingFace InferenceClient with Novita provider for Kimi K2 Thinking
139
+ provider = "novita"
140
+ elif model_id == "stealth-model-1":
141
+ # Use stealth model with generic configuration
142
+ api_key = os.getenv("STEALTH_MODEL_1_API_KEY")
143
+ if not api_key:
144
+ raise ValueError("STEALTH_MODEL_1_API_KEY environment variable is required for Carrot model")
145
+
146
+ base_url = os.getenv("STEALTH_MODEL_1_BASE_URL")
147
+ if not base_url:
148
+ raise ValueError("STEALTH_MODEL_1_BASE_URL environment variable is required for Carrot model")
149
+
150
+ return OpenAI(
151
+ api_key=api_key,
152
+ base_url=base_url,
153
+ )
154
+ elif model_id == "moonshotai/Kimi-K2-Instruct":
155
+ provider = "groq"
156
+ elif model_id == "deepseek-ai/DeepSeek-V3.1":
157
+ provider = "novita"
158
+ elif model_id == "deepseek-ai/DeepSeek-V3.1-Terminus":
159
+ provider = "novita"
160
+ elif model_id == "deepseek-ai/DeepSeek-V3.2-Exp":
161
+ provider = "novita"
162
+ elif model_id == "zai-org/GLM-4.5":
163
+ provider = "fireworks-ai"
164
+ elif model_id == "zai-org/GLM-4.6":
165
+ # Use auto provider for GLM-4.6, HuggingFace will select best available
166
+ provider = "auto"
167
+ return InferenceClient(
168
+ provider=provider,
169
+ api_key=HF_TOKEN,
170
+ bill_to="huggingface"
171
+ )
172
+
173
+ # Helper function to get real model ID for stealth models and special cases
174
+ def get_real_model_id(model_id: str) -> str:
175
+ """Get the real model ID, checking environment variables for stealth models and handling special model formats"""
176
+ if model_id == "stealth-model-1":
177
+ # Get the real model ID from environment variable
178
+ real_model_id = os.getenv("STEALTH_MODEL_1_ID")
179
+ if not real_model_id:
180
+ raise ValueError("STEALTH_MODEL_1_ID environment variable is required for Carrot model")
181
+
182
+ return real_model_id
183
+ elif model_id == "zai-org/GLM-4.6":
184
+ # GLM-4.6 requires provider suffix in model string for API calls
185
+ return "zai-org/GLM-4.6:zai-org"
186
+ return model_id
187
+
188
+ # Type definitions
189
+ History = List[Tuple[str, str]]
190
+ Messages = List[Dict[str, str]]
191
+
192
+ def history_to_messages(history: History, system: str) -> Messages:
193
+ messages = [{'role': 'system', 'content': system}]
194
+ for h in history:
195
+ # Handle multimodal content in history
196
+ user_content = h[0]
197
+ if isinstance(user_content, list):
198
+ # Extract text from multimodal content
199
+ text_content = ""
200
+ for item in user_content:
201
+ if isinstance(item, dict) and item.get("type") == "text":
202
+ text_content += item.get("text", "")
203
+ user_content = text_content if text_content else str(user_content)
204
+
205
+ messages.append({'role': 'user', 'content': user_content})
206
+ messages.append({'role': 'assistant', 'content': h[1]})
207
+ return messages
208
+
209
+ def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:
210
+ """Convert history tuples to chatbot message format"""
211
+ messages = []
212
+ for user_msg, assistant_msg in history:
213
+ # Handle multimodal content
214
+ if isinstance(user_msg, list):
215
+ text_content = ""
216
+ for item in user_msg:
217
+ if isinstance(item, dict) and item.get("type") == "text":
218
+ text_content += item.get("text", "")
219
+ user_msg = text_content if text_content else str(user_msg)
220
+
221
+ messages.append({"role": "user", "content": user_msg})
222
+ messages.append({"role": "assistant", "content": assistant_msg})
223
+ return messages
224
+
225
+ def remove_code_block(text):
226
+ # Try to match code blocks with language markers
227
+ patterns = [
228
+ r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML
229
+ r'```\n([\s\S]+?)\n```', # Match code blocks without language markers
230
+ r'```([\s\S]+?)```' # Match code blocks without line breaks
231
+ ]
232
+ for pattern in patterns:
233
+ match = re.search(pattern, text, re.DOTALL)
234
+ if match:
235
+ extracted = match.group(1).strip()
236
+ # Remove a leading language marker line (e.g., 'python') if present
237
+ if extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
238
+ return extracted.split('\n', 1)[1] if '\n' in extracted else ''
239
+ # If HTML markup starts later in the block (e.g., Poe injected preface), trim to first HTML root
240
+ html_root_idx = None
241
+ for tag in ['<!DOCTYPE html', '<html']:
242
+ idx = extracted.find(tag)
243
+ if idx != -1:
244
+ html_root_idx = idx if html_root_idx is None else min(html_root_idx, idx)
245
+ if html_root_idx is not None and html_root_idx > 0:
246
+ return extracted[html_root_idx:].strip()
247
+ return extracted
248
+ # If no code block is found, check if the entire text is HTML
249
+ stripped = text.strip()
250
+ if stripped.startswith('<!DOCTYPE html>') or stripped.startswith('<html') or stripped.startswith('<'):
251
+ # If HTML root appears later (e.g., Poe preface), trim to first HTML root
252
+ for tag in ['<!DOCTYPE html', '<html']:
253
+ idx = stripped.find(tag)
254
+ if idx > 0:
255
+ return stripped[idx:].strip()
256
+ return stripped
257
+ # Special handling for python: remove python marker
258
+ if text.strip().startswith('```python'):
259
+ return text.strip()[9:-3].strip()
260
+ # Remove a leading language marker line if present (fallback)
261
+ lines = text.strip().split('\n', 1)
262
+ if lines[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
263
+ return lines[1] if len(lines) > 1 else ''
264
+ return text.strip()
265
+
266
+ ## React CDN compatibility fixer removed per user preference
267
+
268
+ def strip_placeholder_thinking(text: str) -> str:
269
+ """Remove placeholder 'Thinking...' status lines from streamed text."""
270
+ if not text:
271
+ return text
272
+ # Matches lines like: "Thinking..." or "Thinking... (12s elapsed)"
273
+ return re.sub(r"(?mi)^[\t ]*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?[\t ]*$\n?", "", text)
274
+
275
+ def is_placeholder_thinking_only(text: str) -> bool:
276
+ """Return True if text contains only 'Thinking...' placeholder lines (with optional elapsed)."""
277
+ if not text:
278
+ return False
279
+ stripped = text.strip()
280
+ if not stripped:
281
+ return False
282
+ return re.fullmatch(r"(?s)(?:\s*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?\s*)+", stripped) is not None
283
+
284
+ def extract_last_thinking_line(text: str) -> str:
285
+ """Extract the last 'Thinking...' line to display as status."""
286
+ matches = list(re.finditer(r"Thinking\.\.\.(?:\s*\(\d+s elapsed\))?", text))
287
+ return matches[-1].group(0) if matches else "Thinking..."
288
+
anycoder_app/parsers.py ADDED
@@ -0,0 +1,1066 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code parsing and formatting utilities for different frameworks.
3
+ Handles parsing of transformers.js, React, multi-file HTML, Streamlit, and Gradio code.
4
+ """
5
+ import re
6
+ import os
7
+ import json
8
+ import base64
9
+ from typing import Dict, List, Optional, Tuple
10
+ from bs4 import BeautifulSoup
11
+ import html
12
+
13
+ from .config import SEARCH_START, DIVIDER, REPLACE_END
14
+
15
+ # Type definitions
16
+ History = List[Dict[str, str]]
17
+
18
+ def remove_code_block(text):
19
+ # Try to match code blocks with language markers
20
+ patterns = [
21
+ r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML
22
+ r'```\n([\s\S]+?)\n```', # Match code blocks without language markers
23
+ r'```([\s\S]+?)```' # Match code blocks without line breaks
24
+ ]
25
+ for pattern in patterns:
26
+ match = re.search(pattern, text, re.DOTALL)
27
+ if match:
28
+ extracted = match.group(1).strip()
29
+ # Remove a leading language marker line (e.g., 'python') if present
30
+ if extracted.split('\n', 1)[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
31
+ return extracted.split('\n', 1)[1] if '\n' in extracted else ''
32
+ # If HTML markup starts later in the block (e.g., Poe injected preface), trim to first HTML root
33
+ html_root_idx = None
34
+ for tag in ['<!DOCTYPE html', '<html']:
35
+ idx = extracted.find(tag)
36
+ if idx != -1:
37
+ html_root_idx = idx if html_root_idx is None else min(html_root_idx, idx)
38
+ if html_root_idx is not None and html_root_idx > 0:
39
+ return extracted[html_root_idx:].strip()
40
+ return extracted
41
+ # If no code block is found, check if the entire text is HTML
42
+ stripped = text.strip()
43
+ if stripped.startswith('<!DOCTYPE html>') or stripped.startswith('<html') or stripped.startswith('<'):
44
+ # If HTML root appears later (e.g., Poe preface), trim to first HTML root
45
+ for tag in ['<!DOCTYPE html', '<html']:
46
+ idx = stripped.find(tag)
47
+ if idx > 0:
48
+ return stripped[idx:].strip()
49
+ return stripped
50
+ # Special handling for python: remove python marker
51
+ if text.strip().startswith('```python'):
52
+ return text.strip()[9:-3].strip()
53
+ # Remove a leading language marker line if present (fallback)
54
+ lines = text.strip().split('\n', 1)
55
+ if lines[0].strip().lower() in ['python', 'html', 'css', 'javascript', 'json', 'c', 'cpp', 'markdown', 'latex', 'jinja2', 'typescript', 'yaml', 'dockerfile', 'shell', 'r', 'sql', 'sql-mssql', 'sql-mysql', 'sql-mariadb', 'sql-sqlite', 'sql-cassandra', 'sql-plSQL', 'sql-hive', 'sql-pgsql', 'sql-gql', 'sql-gpsql', 'sql-sparksql', 'sql-esper']:
56
+ return lines[1] if len(lines) > 1 else ''
57
+ return text.strip()
58
+
59
+ ## React CDN compatibility fixer removed per user preference
60
+
61
+ def strip_placeholder_thinking(text: str) -> str:
62
+ """Remove placeholder 'Thinking...' status lines from streamed text."""
63
+ if not text:
64
+ return text
65
+ # Matches lines like: "Thinking..." or "Thinking... (12s elapsed)"
66
+ return re.sub(r"(?mi)^[\t ]*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?[\t ]*$\n?", "", text)
67
+
68
+ def is_placeholder_thinking_only(text: str) -> bool:
69
+ """Return True if text contains only 'Thinking...' placeholder lines (with optional elapsed)."""
70
+ if not text:
71
+ return False
72
+ stripped = text.strip()
73
+ if not stripped:
74
+ return False
75
+ return re.fullmatch(r"(?s)(?:\s*Thinking\.\.\.(?:\s*\(\d+s elapsed\))?\s*)+", stripped) is not None
76
+
77
+ def extract_last_thinking_line(text: str) -> str:
78
+ """Extract the last 'Thinking...' line to display as status."""
79
+ matches = list(re.finditer(r"Thinking\.\.\.(?:\s*\(\d+s elapsed\))?", text))
80
+ return matches[-1].group(0) if matches else "Thinking..."
81
+
82
+ def parse_transformers_js_output(text):
83
+ """Parse transformers.js output and extract the three files (index.html, index.js, style.css)"""
84
+ files = {
85
+ 'index.html': '',
86
+ 'index.js': '',
87
+ 'style.css': ''
88
+ }
89
+
90
+ # Multiple patterns to match the three code blocks with different variations
91
+ html_patterns = [
92
+ r'```html\s*\n([\s\S]*?)(?:```|\Z)',
93
+ r'```htm\s*\n([\s\S]*?)(?:```|\Z)',
94
+ r'```\s*(?:index\.html|html)\s*\n([\s\S]*?)(?:```|\Z)'
95
+ ]
96
+
97
+ js_patterns = [
98
+ r'```javascript\s*\n([\s\S]*?)(?:```|\Z)',
99
+ r'```js\s*\n([\s\S]*?)(?:```|\Z)',
100
+ r'```\s*(?:index\.js|javascript|js)\s*\n([\s\S]*?)(?:```|\Z)'
101
+ ]
102
+
103
+ css_patterns = [
104
+ r'```css\s*\n([\s\S]*?)(?:```|\Z)',
105
+ r'```\s*(?:style\.css|css)\s*\n([\s\S]*?)(?:```|\Z)'
106
+ ]
107
+
108
+ # Extract HTML content
109
+ for pattern in html_patterns:
110
+ html_match = re.search(pattern, text, re.IGNORECASE)
111
+ if html_match:
112
+ files['index.html'] = html_match.group(1).strip()
113
+ break
114
+
115
+ # Extract JavaScript content
116
+ for pattern in js_patterns:
117
+ js_match = re.search(pattern, text, re.IGNORECASE)
118
+ if js_match:
119
+ files['index.js'] = js_match.group(1).strip()
120
+ break
121
+
122
+ # Extract CSS content
123
+ for pattern in css_patterns:
124
+ css_match = re.search(pattern, text, re.IGNORECASE)
125
+ if css_match:
126
+ files['style.css'] = css_match.group(1).strip()
127
+ break
128
+
129
+ # Fallback: support === index.html === format if any file is missing
130
+ if not (files['index.html'] and files['index.js'] and files['style.css']):
131
+ # Use regex to extract sections
132
+ html_fallback = re.search(r'===\s*index\.html\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
133
+ js_fallback = re.search(r'===\s*index\.js\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
134
+ css_fallback = re.search(r'===\s*style\.css\s*===\s*\n([\s\S]+?)(?=\n===|$)', text, re.IGNORECASE)
135
+
136
+ if html_fallback:
137
+ files['index.html'] = html_fallback.group(1).strip()
138
+ if js_fallback:
139
+ files['index.js'] = js_fallback.group(1).strip()
140
+ if css_fallback:
141
+ files['style.css'] = css_fallback.group(1).strip()
142
+
143
+ # Additional fallback: extract from numbered sections or file headers
144
+ if not (files['index.html'] and files['index.js'] and files['style.css']):
145
+ # Try patterns like "1. index.html:" or "**index.html**"
146
+ patterns = [
147
+ (r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.html(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.html'),
148
+ (r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)index\.js(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'index.js'),
149
+ (r'(?:^\d+\.\s*|^##\s*|^\*\*\s*)style\.css(?:\s*:|\*\*:?)\s*\n([\s\S]+?)(?=\n(?:\d+\.|##|\*\*|===)|$)', 'style.css')
150
+ ]
151
+
152
+ for pattern, file_key in patterns:
153
+ if not files[file_key]:
154
+ match = re.search(pattern, text, re.IGNORECASE | re.MULTILINE)
155
+ if match:
156
+ # Clean up the content by removing any code block markers
157
+ content = match.group(1).strip()
158
+ content = re.sub(r'^```\w*\s*\n', '', content)
159
+ content = re.sub(r'\n```\s*$', '', content)
160
+ files[file_key] = content.strip()
161
+
162
+ return files
163
+
164
+ def format_transformers_js_output(files):
165
+ """Format the three files into a single display string"""
166
+ output = []
167
+ output.append("=== index.html ===")
168
+ output.append(files['index.html'])
169
+ output.append("\n=== index.js ===")
170
+ output.append(files['index.js'])
171
+ output.append("\n=== style.css ===")
172
+ output.append(files['style.css'])
173
+ return '\n'.join(output)
174
+
175
+ def build_transformers_inline_html(files: dict) -> str:
176
+ """Merge transformers.js three-file output into a single self-contained HTML document.
177
+
178
+ - Inlines style.css into a <style> tag
179
+ - Inlines index.js into a <script type="module"> tag
180
+ - Rewrites ESM imports for transformers.js to a stable CDN URL so it works in data: iframes
181
+ """
182
+ import re as _re
183
+
184
+ html = files.get('index.html') or ''
185
+ js = files.get('index.js') or ''
186
+ css = files.get('style.css') or ''
187
+
188
+ # Normalize JS imports to CDN (handle both @huggingface/transformers and legacy @xenova/transformers)
189
+ cdn_url = "https://cdn.jsdelivr.net/npm/@huggingface/[email protected]"
190
+
191
+ def _normalize_imports(_code: str) -> str:
192
+ if not _code:
193
+ return _code or ""
194
+ _code = _re.sub(r"from\s+['\"]@huggingface/transformers['\"]", f"from '{cdn_url}'", _code)
195
+ _code = _re.sub(r"from\s+['\"]@xenova/transformers['\"]", f"from '{cdn_url}'", _code)
196
+ _code = _re.sub(r"from\s+['\"]https://cdn.jsdelivr.net/npm/@huggingface/transformers@[^'\"]+['\"]", f"from '{cdn_url}'", _code)
197
+ _code = _re.sub(r"from\s+['\"]https://cdn.jsdelivr.net/npm/@xenova/transformers@[^'\"]+['\"]", f"from '{cdn_url}'", _code)
198
+ return _code
199
+
200
+ # Extract inline module scripts from index.html, then merge into JS so we control imports
201
+ inline_modules = []
202
+ try:
203
+ for _m in _re.finditer(r"<script\\b[^>]*type=[\"\']module[\"\'][^>]*>([\s\S]*?)</script>", html, flags=_re.IGNORECASE):
204
+ inline_modules.append(_m.group(1))
205
+ if inline_modules:
206
+ html = _re.sub(r"<script\\b[^>]*type=[\"\']module[\"\'][^>]*>[\s\S]*?</script>\\s*", "", html, flags=_re.IGNORECASE)
207
+ # Normalize any external module script URLs that load transformers to a single CDN version (keep the tag)
208
+ html = _re.sub(r"https://cdn\.jsdelivr\.net/npm/@huggingface/transformers@[^'\"<>\s]+", cdn_url, html)
209
+ html = _re.sub(r"https://cdn\.jsdelivr\.net/npm/@xenova/transformers@[^'\"<>\s]+", cdn_url, html)
210
+ except Exception:
211
+ # Best-effort; continue
212
+ pass
213
+
214
+ # Merge inline module code with provided index.js, then normalize imports
215
+ combined_js_parts = []
216
+ if inline_modules:
217
+ combined_js_parts.append("\n\n".join(inline_modules))
218
+ if js:
219
+ combined_js_parts.append(js)
220
+ js = "\n\n".join([p for p in combined_js_parts if (p and p.strip())])
221
+ js = _normalize_imports(js)
222
+
223
+ # Prepend a small prelude to reduce persistent caching during preview
224
+ # Also ensure a global `transformers` namespace exists for apps relying on it
225
+ # Note: importing env alongside user's own imports is fine in ESM
226
+ if js.strip():
227
+ prelude = (
228
+ f"import {{ env }} from '{cdn_url}';\n"
229
+ "try { env.useBrowserCache = false; } catch (e) {}\n"
230
+ "try { if (env && env.backends && env.backends.onnx && env.backends.onnx.wasm) { env.backends.onnx.wasm.numThreads = 1; env.backends.onnx.wasm.proxy = false; } } catch (e) {}\n"
231
+ f"(async () => {{ try {{ if (typeof globalThis.transformers === 'undefined') {{ const m = await import('{cdn_url}'); globalThis.transformers = m; }} }} catch (e) {{}} }})();\n"
232
+ )
233
+ js = prelude + js
234
+
235
+ # If index.html missing or doesn't look like a full document, create a minimal shell
236
+ doc = html.strip()
237
+ if not doc or ('<html' not in doc.lower()):
238
+ doc = (
239
+ "<!DOCTYPE html>\n"
240
+ "<html>\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n<title>Transformers.js App</title>\n</head>\n"
241
+ "<body>\n<div id=\"app\"></div>\n</body>\n</html>"
242
+ )
243
+
244
+ # Remove local references to style.css and index.js to avoid duplicates when inlining
245
+ doc = _re.sub(r"<link[^>]+href=\"[^\"]*style\.css\"[^>]*>\s*", "", doc, flags=_re.IGNORECASE)
246
+ doc = _re.sub(r"<script[^>]+src=\"[^\"]*index\.js\"[^>]*>\s*</script>\s*", "", doc, flags=_re.IGNORECASE)
247
+
248
+ # Inline CSS: insert before </head> or create a <head>
249
+ style_tag = f"<style>\n{css}\n</style>" if css else ""
250
+ if style_tag:
251
+ if '</head>' in doc.lower():
252
+ # Preserve original casing by finding closing head case-insensitively
253
+ match = _re.search(r"</head>", doc, flags=_re.IGNORECASE)
254
+ if match:
255
+ idx = match.start()
256
+ doc = doc[:idx] + style_tag + doc[idx:]
257
+ else:
258
+ # No head; insert at top of body
259
+ match = _re.search(r"<body[^>]*>", doc, flags=_re.IGNORECASE)
260
+ if match:
261
+ idx = match.end()
262
+ doc = doc[:idx] + "\n" + style_tag + doc[idx:]
263
+ else:
264
+ # Append at beginning
265
+ doc = style_tag + doc
266
+
267
+ # Inline JS: insert before </body>
268
+ script_tag = f"<script type=\"module\">\n{js}\n</script>" if js else ""
269
+ # Lightweight debug console overlay to surface runtime errors inside the iframe
270
+ debug_overlay = (
271
+ "<style>\n"
272
+ "#anycoder-debug{position:fixed;left:0;right:0;bottom:0;max-height:45%;overflow:auto;"
273
+ "background:rgba(0,0,0,.85);color:#9eff9e;padding:.5em;font:12px/1.4 monospace;z-index:2147483647;display:none}"
274
+ "#anycoder-debug pre{margin:0;white-space:pre-wrap;word-break:break-word}"
275
+ "</style>\n"
276
+ "<div id=\"anycoder-debug\"></div>\n"
277
+ "<script>\n"
278
+ "(function(){\n"
279
+ " const el = document.getElementById('anycoder-debug');\n"
280
+ " function show(){ if(el && el.style.display!=='block'){ el.style.display='block'; } }\n"
281
+ " function log(msg){ try{ show(); const pre=document.createElement('pre'); pre.textContent=msg; el.appendChild(pre);}catch(e){} }\n"
282
+ " const origError = console.error.bind(console);\n"
283
+ " console.error = function(){ origError.apply(console, arguments); try{ log('console.error: ' + Array.from(arguments).map(a=>{try{return (typeof a==='string')?a:JSON.stringify(a);}catch(e){return String(a);}}).join(' ')); }catch(e){} };\n"
284
+ " window.addEventListener('error', e => { log('window.onerror: ' + (e && e.message ? e.message : 'Unknown error')); });\n"
285
+ " window.addEventListener('unhandledrejection', e => { try{ const r=e && e.reason; log('unhandledrejection: ' + (r && (r.message || JSON.stringify(r)))); }catch(err){ log('unhandledrejection'); } });\n"
286
+ "})();\n"
287
+ "</script>"
288
+ )
289
+ # Cleanup script to clear Cache Storage and IndexedDB on unload to free model weights
290
+ cleanup_tag = (
291
+ "<script>\n"
292
+ "(function(){\n"
293
+ " function cleanup(){\n"
294
+ " try { if (window.caches && caches.keys) { caches.keys().then(keys => keys.forEach(k => caches.delete(k))); } } catch(e){}\n"
295
+ " try { if (window.indexedDB && indexedDB.databases) { indexedDB.databases().then(dbs => dbs.forEach(db => db && db.name && indexedDB.deleteDatabase(db.name))); } } catch(e){}\n"
296
+ " }\n"
297
+ " window.addEventListener('pagehide', cleanup, { once: true });\n"
298
+ " window.addEventListener('beforeunload', cleanup, { once: true });\n"
299
+ "})();\n"
300
+ "</script>"
301
+ )
302
+ if script_tag:
303
+ match = _re.search(r"</body>", doc, flags=_re.IGNORECASE)
304
+ if match:
305
+ idx = match.start()
306
+ doc = doc[:idx] + debug_overlay + script_tag + cleanup_tag + doc[idx:]
307
+ else:
308
+ # Append at end
309
+ doc = doc + debug_overlay + script_tag + cleanup_tag
310
+
311
+ return doc
312
+
313
+ def send_transformers_to_sandbox(files: dict) -> str:
314
+ """Build a self-contained HTML document from transformers.js files and return an iframe preview."""
315
+ merged_html = build_transformers_inline_html(files)
316
+ return send_to_sandbox(merged_html)
317
+
318
+ def parse_multipage_html_output(text: str) -> Dict[str, str]:
319
+ """Parse multi-page HTML output formatted as repeated "=== filename ===" sections.
320
+
321
+ Returns a mapping of filename β†’ file content. Supports nested paths like assets/css/styles.css.
322
+ """
323
+ if not text:
324
+ return {}
325
+ # First, strip any markdown fences
326
+ cleaned = remove_code_block(text)
327
+ files: Dict[str, str] = {}
328
+ import re as _re
329
+ pattern = _re.compile(r"^===\s*([^=\n]+?)\s*===\s*\n([\s\S]*?)(?=\n===\s*[^=\n]+?\s*===|\Z)", _re.MULTILINE)
330
+ for m in pattern.finditer(cleaned):
331
+ name = m.group(1).strip()
332
+ content = m.group(2).strip()
333
+ # Remove accidental trailing fences if present
334
+ content = _re.sub(r"^```\w*\s*\n|\n```\s*$", "", content)
335
+ files[name] = content
336
+ return files
337
+
338
+ def format_multipage_output(files: Dict[str, str]) -> str:
339
+ """Format a dict of files back into === filename === sections.
340
+
341
+ Ensures `index.html` appears first if present; others follow sorted by path.
342
+ """
343
+ if not isinstance(files, dict) or not files:
344
+ return ""
345
+ ordered_paths = []
346
+ if 'index.html' in files:
347
+ ordered_paths.append('index.html')
348
+ for path in sorted(files.keys()):
349
+ if path == 'index.html':
350
+ continue
351
+ ordered_paths.append(path)
352
+ parts: list[str] = []
353
+ for path in ordered_paths:
354
+ parts.append(f"=== {path} ===")
355
+ # Avoid trailing extra newlines to keep blocks compact
356
+ parts.append((files.get(path) or '').rstrip())
357
+ return "\n".join(parts)
358
+
359
+ def validate_and_autofix_files(files: Dict[str, str]) -> Dict[str, str]:
360
+ """Ensure minimal contract for multi-file sites; auto-fix missing pieces.
361
+
362
+ Rules:
363
+ - Ensure at least one HTML entrypoint (index.html). If none, synthesize a simple index.html linking discovered pages.
364
+ - For each HTML file, ensure referenced local assets exist in files; if missing, add minimal stubs.
365
+ - Normalize relative paths (strip leading '/').
366
+ """
367
+ if not isinstance(files, dict) or not files:
368
+ return files or {}
369
+ import re as _re
370
+
371
+ normalized: Dict[str, str] = {}
372
+ for k, v in files.items():
373
+ safe_key = k.strip().lstrip('/')
374
+ normalized[safe_key] = v
375
+
376
+ html_files = [p for p in normalized.keys() if p.lower().endswith('.html')]
377
+ has_index = 'index.html' in normalized
378
+
379
+ # If no index.html but some HTML pages exist, create a simple hub index linking to them
380
+ if not has_index and html_files:
381
+ links = '\n'.join([f"<li><a href=\"{p}\">{p}</a></li>" for p in html_files])
382
+ normalized['index.html'] = (
383
+ "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n"
384
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/>\n"
385
+ "<title>Site Index</title>\n</head>\n<body>\n<h1>Site</h1>\n<ul>\n"
386
+ + links + "\n</ul>\n</body>\n</html>"
387
+ )
388
+
389
+ # Collect references from HTML files
390
+ asset_refs: set[str] = set()
391
+ link_href = _re.compile(r"<link[^>]+href=\"([^\"]+)\"")
392
+ script_src = _re.compile(r"<script[^>]+src=\"([^\"]+)\"")
393
+ img_src = _re.compile(r"<img[^>]+src=\"([^\"]+)\"")
394
+ a_href = _re.compile(r"<a[^>]+href=\"([^\"]+)\"")
395
+
396
+ for path, content in list(normalized.items()):
397
+ if not path.lower().endswith('.html'):
398
+ continue
399
+ for patt in (link_href, script_src, img_src, a_href):
400
+ for m in patt.finditer(content or ""):
401
+ ref = (m.group(1) or "").strip()
402
+ if not ref or ref.startswith('http://') or ref.startswith('https://') or ref.startswith('data:') or '#' in ref:
403
+ continue
404
+ asset_refs.add(ref.lstrip('/'))
405
+
406
+ # Add minimal stubs for missing local references (CSS/JS/pages only, not images)
407
+ for ref in list(asset_refs):
408
+ if ref not in normalized:
409
+ if ref.lower().endswith('.css'):
410
+ normalized[ref] = "/* generated stub */\n"
411
+ elif ref.lower().endswith('.js'):
412
+ normalized[ref] = "// generated stub\n"
413
+ elif ref.lower().endswith('.html'):
414
+ normalized[ref] = (
415
+ "<!DOCTYPE html>\n<html lang=\"en\">\n<head><meta charset=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"/><title>Page</title></head>\n"
416
+ "<body><main><h1>Placeholder page</h1><p>This page was auto-created to satisfy an internal link.</p></main></body>\n</html>"
417
+ )
418
+ # Note: We no longer create placeholder image files automatically
419
+ # This prevents unwanted SVG stub files from being generated during image generation
420
+
421
+ return normalized
422
+ def inline_multipage_into_single_preview(files: Dict[str, str]) -> str:
423
+ """Inline local CSS/JS referenced by index.html for preview inside a data: iframe.
424
+
425
+ - Uses index.html as the base document
426
+ - Inlines <link href="..."> if the target exists in files
427
+ - Inlines <script src="..."> if the target exists in files
428
+ - Leaves other links (e.g., about.html) untouched; preview covers the home page
429
+ """
430
+ import re as _re
431
+ html = files.get('index.html', '')
432
+ if not html:
433
+ return ""
434
+ doc = html
435
+ # Inline CSS links that point to known files
436
+ def _inline_css(match):
437
+ href = match.group(1)
438
+ if href in files:
439
+ return f"<style>\n{files[href]}\n</style>"
440
+ return match.group(0)
441
+ doc = _re.sub(r"<link[^>]+href=\"([^\"]+)\"[^>]*/?>", _inline_css, doc, flags=_re.IGNORECASE)
442
+
443
+ # Inline JS scripts that point to known files
444
+ def _inline_js(match):
445
+ src = match.group(1)
446
+ if src in files:
447
+ return f"<script>\n{files[src]}\n</script>"
448
+ return match.group(0)
449
+ doc = _re.sub(r"<script[^>]+src=\"([^\"]+)\"[^>]*>\s*</script>", _inline_js, doc, flags=_re.IGNORECASE)
450
+
451
+ # Inject a lightweight in-iframe client-side navigator to load other HTML files
452
+ try:
453
+ import json as _json
454
+ import base64 as _b64
455
+ import re as _re
456
+ html_pages = {k: v for k, v in files.items() if k.lower().endswith('.html')}
457
+ # Ensure index.html entry restores the current body's HTML
458
+ _m_body = _re.search(r"<body[^>]*>([\s\S]*?)</body>", doc, flags=_re.IGNORECASE)
459
+ _index_body = _m_body.group(1) if _m_body else doc
460
+ html_pages['index.html'] = _index_body
461
+ encoded = _b64.b64encode(_json.dumps(html_pages).encode('utf-8')).decode('ascii')
462
+ nav_script = (
463
+ "<script>\n" # Simple client-side loader for internal links
464
+ "(function(){\n"
465
+ f" const MP_FILES = JSON.parse(atob('{encoded}'));\n"
466
+ " function extractBody(html){\n"
467
+ " try {\n"
468
+ " const doc = new DOMParser().parseFromString(html, 'text/html');\n"
469
+ " const title = doc.querySelector('title'); if (title) document.title = title.textContent || document.title;\n"
470
+ " return doc.body ? doc.body.innerHTML : html;\n"
471
+ " } catch(e){ return html; }\n"
472
+ " }\n"
473
+ " function loadPage(path){\n"
474
+ " if (!MP_FILES[path]) return false;\n"
475
+ " const bodyHTML = extractBody(MP_FILES[path]);\n"
476
+ " document.body.innerHTML = bodyHTML;\n"
477
+ " attach();\n"
478
+ " try { history.replaceState({}, '', '#'+path); } catch(e){}\n"
479
+ " return true;\n"
480
+ " }\n"
481
+ " function clickHandler(e){\n"
482
+ " const a = e.target && e.target.closest ? e.target.closest('a') : null;\n"
483
+ " if (!a) return;\n"
484
+ " const href = a.getAttribute('href') || '';\n"
485
+ " if (!href || href.startsWith('#') || /^https?:/i.test(href) || href.startsWith('mailto:') || href.startsWith('tel:')) return;\n"
486
+ " const clean = href.split('#')[0].split('?')[0];\n"
487
+ " if (MP_FILES[clean]) { e.preventDefault(); loadPage(clean); }\n"
488
+ " }\n"
489
+ " function attach(){ document.removeEventListener('click', clickHandler, true); document.addEventListener('click', clickHandler, true); }\n"
490
+ " document.addEventListener('DOMContentLoaded', function(){ attach(); const initial = (location.hash||'').slice(1); if (initial && MP_FILES[initial]) loadPage(initial); }, { once:true });\n"
491
+ "})();\n"
492
+ "</script>"
493
+ )
494
+ m = _re.search(r"</body>", doc, flags=_re.IGNORECASE)
495
+ if m:
496
+ i = m.start()
497
+ doc = doc[:i] + nav_script + doc[i:]
498
+ else:
499
+ doc = doc + nav_script
500
+ except Exception:
501
+ # Non-fatal in preview
502
+ pass
503
+
504
+ return doc
505
+
506
+ def extract_html_document(text: str) -> str:
507
+ """Return substring starting from the first <!DOCTYPE html> or <html> if present, else original text.
508
+
509
+ This ignores prose or planning notes before the actual HTML so previews don't break.
510
+ """
511
+ if not text:
512
+ return text
513
+ lower = text.lower()
514
+ idx = lower.find("<!doctype html")
515
+ if idx == -1:
516
+ idx = lower.find("<html")
517
+ return text[idx:] if idx != -1 else text
518
+
519
+
520
+ def parse_react_output(text):
521
+ """Parse React/Next.js output to extract individual files.
522
+
523
+ Supports multi-file sections using === filename === sections.
524
+ """
525
+ if not text:
526
+ return {}
527
+
528
+ # Use the generic multipage parser
529
+ try:
530
+ files = parse_multipage_html_output(text) or {}
531
+ except Exception:
532
+ files = {}
533
+
534
+ return files if isinstance(files, dict) and files else {}
535
+
536
+
537
+ def history_render(history: History):
538
+ return gr.update(visible=True), history
539
+
540
+ def clear_history():
541
+ return [], [] # Empty lists for both history and chatbot messages
542
+
543
+ def create_multimodal_message(text, image=None):
544
+ """Create a chat message. For broad provider compatibility, always return content as a string.
545
+
546
+ Some providers (e.g., Hugging Face router endpoints like Cerebras) expect `content` to be a string,
547
+ not a list of typed parts. To avoid 422 validation errors, we inline a brief note when an image is provided.
548
+ """
549
+ if image is None:
550
+ return {"role": "user", "content": text}
551
+ # Keep providers happy: avoid structured multimodal payloads; add a short note instead
552
+ # If needed, this can be enhanced per-model with proper multimodal schemas.
553
+ return {"role": "user", "content": f"{text}\n\n[An image was provided as reference.]"}
554
+ def apply_search_replace_changes(original_content: str, changes_text: str) -> str:
555
+ """Apply search/replace changes to content (HTML, Python, etc.)"""
556
+ if not changes_text.strip():
557
+ return original_content
558
+
559
+ # If the model didn't use the block markers, try a CSS-rule fallback where
560
+ # provided blocks like `.selector { ... }` replace matching CSS rules.
561
+ if (SEARCH_START not in changes_text) and (DIVIDER not in changes_text) and (REPLACE_END not in changes_text):
562
+ try:
563
+ import re # Local import to avoid global side effects
564
+ updated_content = original_content
565
+ replaced_any_rule = False
566
+ # Find CSS-like rule blocks in the changes_text
567
+ # This is a conservative matcher that looks for `selector { ... }`
568
+ css_blocks = re.findall(r"([^{]+)\{([\s\S]*?)\}", changes_text, flags=re.MULTILINE)
569
+ for selector_raw, body_raw in css_blocks:
570
+ selector = selector_raw.strip()
571
+ body = body_raw.strip()
572
+ if not selector:
573
+ continue
574
+ # Build a regex to find the existing rule for this selector
575
+ # Capture opening `{` and closing `}` to preserve them; replace inner body.
576
+ pattern = re.compile(rf"({re.escape(selector)}\s*\{{)([\s\S]*?)(\}})")
577
+ def _replace_rule(match):
578
+ nonlocal replaced_any_rule
579
+ replaced_any_rule = True
580
+ prefix, existing_body, suffix = match.groups()
581
+ # Preserve indentation of the existing first body line if present
582
+ first_line_indent = ""
583
+ for line in existing_body.splitlines():
584
+ stripped = line.lstrip(" \t")
585
+ if stripped:
586
+ first_line_indent = line[: len(line) - len(stripped)]
587
+ break
588
+ # Re-indent provided body with the detected indent
589
+ if body:
590
+ new_body_lines = [first_line_indent + line if line.strip() else line for line in body.splitlines()]
591
+ new_body_text = "\n" + "\n".join(new_body_lines) + "\n"
592
+ else:
593
+ new_body_text = existing_body # If empty body provided, keep existing
594
+ return f"{prefix}{new_body_text}{suffix}"
595
+ updated_content, num_subs = pattern.subn(_replace_rule, updated_content, count=1)
596
+ if replaced_any_rule:
597
+ return updated_content
598
+ except Exception:
599
+ # Fallback silently to the standard block-based application
600
+ pass
601
+
602
+ # Split the changes text into individual search/replace blocks
603
+ blocks = []
604
+ current_block = ""
605
+ lines = changes_text.split('\n')
606
+
607
+ for line in lines:
608
+ if line.strip() == SEARCH_START:
609
+ if current_block.strip():
610
+ blocks.append(current_block.strip())
611
+ current_block = line + '\n'
612
+ elif line.strip() == REPLACE_END:
613
+ current_block += line + '\n'
614
+ blocks.append(current_block.strip())
615
+ current_block = ""
616
+ else:
617
+ current_block += line + '\n'
618
+
619
+ if current_block.strip():
620
+ blocks.append(current_block.strip())
621
+
622
+ modified_content = original_content
623
+
624
+ for block in blocks:
625
+ if not block.strip():
626
+ continue
627
+
628
+ # Parse the search/replace block
629
+ lines = block.split('\n')
630
+ search_lines = []
631
+ replace_lines = []
632
+ in_search = False
633
+ in_replace = False
634
+
635
+ for line in lines:
636
+ if line.strip() == SEARCH_START:
637
+ in_search = True
638
+ in_replace = False
639
+ elif line.strip() == DIVIDER:
640
+ in_search = False
641
+ in_replace = True
642
+ elif line.strip() == REPLACE_END:
643
+ in_replace = False
644
+ elif in_search:
645
+ search_lines.append(line)
646
+ elif in_replace:
647
+ replace_lines.append(line)
648
+
649
+ # Apply the search/replace
650
+ if search_lines:
651
+ search_text = '\n'.join(search_lines).strip()
652
+ replace_text = '\n'.join(replace_lines).strip()
653
+
654
+ if search_text in modified_content:
655
+ modified_content = modified_content.replace(search_text, replace_text)
656
+ else:
657
+ # If exact block match fails, attempt a CSS-rule fallback using the replace_text
658
+ try:
659
+ import re
660
+ updated_content = modified_content
661
+ replaced_any_rule = False
662
+ css_blocks = re.findall(r"([^{]+)\{([\s\S]*?)\}", replace_text, flags=re.MULTILINE)
663
+ for selector_raw, body_raw in css_blocks:
664
+ selector = selector_raw.strip()
665
+ body = body_raw.strip()
666
+ if not selector:
667
+ continue
668
+ pattern = re.compile(rf"({re.escape(selector)}\s*\{{)([\s\S]*?)(\}})")
669
+ def _replace_rule(match):
670
+ nonlocal replaced_any_rule
671
+ replaced_any_rule = True
672
+ prefix, existing_body, suffix = match.groups()
673
+ first_line_indent = ""
674
+ for line in existing_body.splitlines():
675
+ stripped = line.lstrip(" \t")
676
+ if stripped:
677
+ first_line_indent = line[: len(line) - len(stripped)]
678
+ break
679
+ if body:
680
+ new_body_lines = [first_line_indent + line if line.strip() else line for line in body.splitlines()]
681
+ new_body_text = "\n" + "\n".join(new_body_lines) + "\n"
682
+ else:
683
+ new_body_text = existing_body
684
+ return f"{prefix}{new_body_text}{suffix}"
685
+ updated_content, num_subs = pattern.subn(_replace_rule, updated_content, count=1)
686
+ if replaced_any_rule:
687
+ modified_content = updated_content
688
+ else:
689
+ print(f"Warning: Search text not found in content: {search_text[:100]}...")
690
+ except Exception:
691
+ print(f"Warning: Search text not found in content: {search_text[:100]}...")
692
+
693
+ return modified_content
694
+
695
+ def apply_transformers_js_search_replace_changes(original_formatted_content: str, changes_text: str) -> str:
696
+ """Apply search/replace changes to transformers.js formatted content (three files)"""
697
+ if not changes_text.strip():
698
+ return original_formatted_content
699
+
700
+ # Parse the original formatted content to get the three files
701
+ files = parse_transformers_js_output(original_formatted_content)
702
+
703
+ # Split the changes text into individual search/replace blocks
704
+ blocks = []
705
+ current_block = ""
706
+ lines = changes_text.split('\n')
707
+
708
+ for line in lines:
709
+ if line.strip() == SEARCH_START:
710
+ if current_block.strip():
711
+ blocks.append(current_block.strip())
712
+ current_block = line + '\n'
713
+ elif line.strip() == REPLACE_END:
714
+ current_block += line + '\n'
715
+ blocks.append(current_block.strip())
716
+ current_block = ""
717
+ else:
718
+ current_block += line + '\n'
719
+
720
+ if current_block.strip():
721
+ blocks.append(current_block.strip())
722
+
723
+ # Process each block and apply changes to the appropriate file
724
+ for block in blocks:
725
+ if not block.strip():
726
+ continue
727
+
728
+ # Parse the search/replace block
729
+ lines = block.split('\n')
730
+ search_lines = []
731
+ replace_lines = []
732
+ in_search = False
733
+ in_replace = False
734
+ target_file = None
735
+
736
+ for line in lines:
737
+ if line.strip() == SEARCH_START:
738
+ in_search = True
739
+ in_replace = False
740
+ elif line.strip() == DIVIDER:
741
+ in_search = False
742
+ in_replace = True
743
+ elif line.strip() == REPLACE_END:
744
+ in_replace = False
745
+ elif in_search:
746
+ search_lines.append(line)
747
+ elif in_replace:
748
+ replace_lines.append(line)
749
+
750
+ # Determine which file this change targets based on the search content
751
+ if search_lines:
752
+ search_text = '\n'.join(search_lines).strip()
753
+ replace_text = '\n'.join(replace_lines).strip()
754
+
755
+ # Check which file contains the search text
756
+ if search_text in files['index.html']:
757
+ target_file = 'index.html'
758
+ elif search_text in files['index.js']:
759
+ target_file = 'index.js'
760
+ elif search_text in files['style.css']:
761
+ target_file = 'style.css'
762
+
763
+ # Apply the change to the target file
764
+ if target_file and search_text in files[target_file]:
765
+ files[target_file] = files[target_file].replace(search_text, replace_text)
766
+ else:
767
+ print(f"Warning: Search text not found in any transformers.js file: {search_text[:100]}...")
768
+
769
+ # Reformat the modified files
770
+ return format_transformers_js_output(files)
771
+
772
+ def send_to_sandbox(code):
773
+ """Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts."""
774
+ html_doc = (code or "").strip()
775
+ # For preview only: inline local file URLs as data URIs so the
776
+ # data: iframe can load them. The original code (shown to the user) still contains file URLs.
777
+ try:
778
+ import re
779
+ import base64 as _b64
780
+ import mimetypes as _mtypes
781
+ import urllib.parse as _uparse
782
+ def _file_url_to_data_uri(file_url: str) -> Optional[str]:
783
+ try:
784
+ parsed = _uparse.urlparse(file_url)
785
+ path = _uparse.unquote(parsed.path)
786
+ if not path:
787
+ return None
788
+ with open(path, 'rb') as _f:
789
+ raw = _f.read()
790
+ mime = _mtypes.guess_type(path)[0] or 'application/octet-stream'
791
+
792
+ b64 = _b64.b64encode(raw).decode()
793
+ return f"data:{mime};base64,{b64}"
794
+ except Exception as e:
795
+ print(f"[Sandbox] Failed to convert file URL to data URI: {str(e)}")
796
+ return None
797
+ def _repl_double(m):
798
+ url = m.group(1)
799
+ data_uri = _file_url_to_data_uri(url)
800
+ return f'src="{data_uri}"' if data_uri else m.group(0)
801
+ def _repl_single(m):
802
+ url = m.group(1)
803
+ data_uri = _file_url_to_data_uri(url)
804
+ return f"src='{data_uri}'" if data_uri else m.group(0)
805
+ html_doc = re.sub(r'src="(file:[^"]+)"', _repl_double, html_doc)
806
+ html_doc = re.sub(r"src='(file:[^']+)'", _repl_single, html_doc)
807
+
808
+ except Exception:
809
+ # Best-effort; continue without inlining
810
+ pass
811
+ encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
812
+ data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
813
+ iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
814
+ return iframe
815
+
816
+ def is_streamlit_code(code: str) -> bool:
817
+ """Heuristic check to determine if Python code is a Streamlit app."""
818
+ if not code:
819
+ return False
820
+ lowered = code.lower()
821
+ return ("import streamlit" in lowered) or ("from streamlit" in lowered) or ("st." in code and "streamlit" in lowered)
822
+
823
+ def clean_requirements_txt_content(content: str) -> str:
824
+ """
825
+ Clean up requirements.txt content to remove markdown formatting.
826
+ This function removes code blocks, markdown lists, headers, and other formatting
827
+ that might be mistakenly included by LLMs.
828
+ """
829
+ if not content:
830
+ return content
831
+
832
+ # First, remove code blocks if present
833
+ if '```' in content:
834
+ content = remove_code_block(content)
835
+
836
+ # Process line by line to remove markdown formatting
837
+ lines = content.split('\n')
838
+ clean_lines = []
839
+
840
+ for line in lines:
841
+ stripped_line = line.strip()
842
+
843
+ # Skip empty lines
844
+ if not stripped_line:
845
+ continue
846
+
847
+ # Skip lines that are markdown formatting
848
+ if (stripped_line == '```' or
849
+ stripped_line.startswith('```') or
850
+ # Skip markdown headers (## Header) but keep comments (# comment)
851
+ (stripped_line.startswith('#') and len(stripped_line) > 1 and stripped_line[1] != ' ') or
852
+ stripped_line.startswith('**') or # Skip bold text
853
+ stripped_line.startswith('===') or # Skip section dividers
854
+ stripped_line.startswith('---') or # Skip horizontal rules
855
+ # Skip common explanatory text patterns
856
+ stripped_line.lower().startswith('here') or
857
+ stripped_line.lower().startswith('this') or
858
+ stripped_line.lower().startswith('the ') or
859
+ stripped_line.lower().startswith('based on') or
860
+ stripped_line.lower().startswith('dependencies') or
861
+ stripped_line.lower().startswith('requirements')):
862
+ continue
863
+
864
+ # Handle markdown list items (- item or * item)
865
+ if (stripped_line.startswith('- ') or stripped_line.startswith('* ')):
866
+ # Extract the package name after the list marker
867
+ stripped_line = stripped_line[2:].strip()
868
+ if not stripped_line:
869
+ continue
870
+
871
+ # Keep lines that look like valid package specifications
872
+ # Valid lines: package names, git+https://, comments starting with "# "
873
+ if (stripped_line.startswith('# ') or # Valid comments
874
+ stripped_line.startswith('git+') or # Git dependencies
875
+ stripped_line[0].isalnum() or # Package names start with alphanumeric
876
+ '==' in stripped_line or # Version specifications
877
+ '>=' in stripped_line or # Version specifications
878
+ '<=' in stripped_line or # Version specifications
879
+ '~=' in stripped_line): # Version specifications
880
+ clean_lines.append(stripped_line)
881
+
882
+ result = '\n'.join(clean_lines)
883
+
884
+ # Ensure it ends with a newline
885
+ if result and not result.endswith('\n'):
886
+ result += '\n'
887
+
888
+ return result if result else "# No additional dependencies required\n"
889
+
890
+ def parse_multi_file_python_output(code: str) -> dict:
891
+ """Parse multi-file Python output (Gradio/Streamlit) into separate files"""
892
+ files = {}
893
+ if not code:
894
+ return files
895
+
896
+ # Look for file separators like === filename.py ===
897
+ import re
898
+ file_pattern = r'=== ([^=]+) ==='
899
+ parts = re.split(file_pattern, code)
900
+
901
+ if len(parts) > 1:
902
+ # Multi-file format detected
903
+ for i in range(1, len(parts), 2):
904
+ if i + 1 < len(parts):
905
+ filename = parts[i].strip()
906
+ content = parts[i + 1].strip()
907
+
908
+ # Clean up requirements.txt to remove markdown formatting
909
+ if filename == 'requirements.txt':
910
+ content = clean_requirements_txt_content(content)
911
+
912
+ files[filename] = content
913
+ else:
914
+ # Single file - check if it's a space import or regular code
915
+ if "IMPORTED PROJECT FROM HUGGING FACE SPACE" in code:
916
+ # This is already a multi-file import, try to parse it
917
+ lines = code.split('\n')
918
+ current_file = None
919
+ current_content = []
920
+
921
+ for line in lines:
922
+ if line.startswith('=== ') and line.endswith(' ==='):
923
+ # Save previous file
924
+ if current_file and current_content:
925
+ content = '\n'.join(current_content)
926
+ # Clean up requirements.txt to remove markdown formatting
927
+ if current_file == 'requirements.txt':
928
+ content = clean_requirements_txt_content(content)
929
+ files[current_file] = content
930
+ # Start new file
931
+ current_file = line[4:-4].strip()
932
+ current_content = []
933
+ elif current_file:
934
+ current_content.append(line)
935
+
936
+ # Save last file
937
+ if current_file and current_content:
938
+ content = '\n'.join(current_content)
939
+ # Clean up requirements.txt to remove markdown formatting
940
+ if current_file == 'requirements.txt':
941
+ content = clean_requirements_txt_content(content)
942
+ files[current_file] = content
943
+ else:
944
+ # Single file code - determine appropriate filename
945
+ if is_streamlit_code(code):
946
+ files['streamlit_app.py'] = code
947
+ elif 'import gradio' in code.lower() or 'from gradio' in code.lower():
948
+ files['app.py'] = code
949
+ else:
950
+ files['app.py'] = code
951
+
952
+ return files
953
+
954
+ def format_multi_file_python_output(files: dict) -> str:
955
+ """Format multiple Python files into the standard multi-file format"""
956
+ if not files:
957
+ return ""
958
+
959
+ if len(files) == 1:
960
+ # Single file - return as is
961
+ return list(files.values())[0]
962
+
963
+ # Multi-file format
964
+ output = []
965
+
966
+ # Order files: main app first, then utils, models, config, requirements
967
+ file_order = ['app.py', 'streamlit_app.py', 'main.py', 'utils.py', 'models.py', 'config.py', 'requirements.txt']
968
+ ordered_files = []
969
+
970
+ # Add files in preferred order
971
+ for preferred_file in file_order:
972
+ if preferred_file in files:
973
+ ordered_files.append(preferred_file)
974
+
975
+ # Add remaining files
976
+ for filename in sorted(files.keys()):
977
+ if filename not in ordered_files:
978
+ ordered_files.append(filename)
979
+
980
+ # Format output
981
+ for filename in ordered_files:
982
+ output.append(f"=== {filename} ===")
983
+
984
+ # Clean up requirements.txt content if it's being formatted
985
+ content = files[filename]
986
+ if filename == 'requirements.txt':
987
+ content = clean_requirements_txt_content(content)
988
+
989
+ output.append(content)
990
+ output.append("") # Empty line between files
991
+
992
+ return '\n'.join(output)
993
+
994
+ def send_streamlit_to_stlite(code: str) -> str:
995
+ """Render Streamlit code using stlite inside a sandboxed iframe for preview."""
996
+ # Build an HTML document that loads stlite and mounts the Streamlit app defined inline
997
+ html_doc = (
998
+ """<!doctype html>
999
+ <html>
1000
+ <head>
1001
+ <meta charset=\"UTF-8\" />
1002
+ <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />
1003
+ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" />
1004
+ <title>Streamlit Preview</title>
1005
+ <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.css\" />
1006
+ <style>html,body{margin:0;padding:0;height:100%;} streamlit-app{display:block;height:100%;}</style>
1007
+ <script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@stlite/[email protected]/build/stlite.js\"></script>
1008
+ </head>
1009
+ <body>
1010
+ <streamlit-app>
1011
+ """
1012
+ + (code or "")
1013
+ + """
1014
+ </streamlit-app>
1015
+ </body>
1016
+ </html>
1017
+ """
1018
+ )
1019
+ encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
1020
+ data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
1021
+ iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
1022
+ return iframe
1023
+
1024
+ def is_gradio_code(code: str) -> bool:
1025
+ """Heuristic check to determine if Python code is a Gradio app."""
1026
+ if not code:
1027
+ return False
1028
+ lowered = code.lower()
1029
+ return (
1030
+ "import gradio" in lowered
1031
+ or "from gradio" in lowered
1032
+ or "gr.Interface(" in code
1033
+ or "gr.Blocks(" in code
1034
+ )
1035
+
1036
+ def send_gradio_to_lite(code: str) -> str:
1037
+ """Render Gradio code using gradio-lite inside a sandboxed iframe for preview."""
1038
+ html_doc = (
1039
+ """<!doctype html>
1040
+ <html>
1041
+ <head>
1042
+ <meta charset=\"UTF-8\" />
1043
+ <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />
1044
+ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" />
1045
+ <title>Gradio Preview</title>
1046
+ <script type=\"module\" crossorigin src=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.js\"></script>
1047
+ <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@gradio/lite/dist/lite.css\" />
1048
+ <style>html,body{margin:0;padding:0;height:100%;} gradio-lite{display:block;height:100%;}</style>
1049
+ </head>
1050
+ <body>
1051
+ <gradio-lite>
1052
+ """
1053
+ + (code or "")
1054
+ + """
1055
+ </gradio-lite>
1056
+ </body>
1057
+ </html>
1058
+ """
1059
+ )
1060
+ encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')
1061
+ data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
1062
+ iframe = f'<iframe src="{data_uri}" width="100%" height="920px" sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-modals allow-presentation" allow="display-capture"></iframe>'
1063
+ return iframe
1064
+
1065
+ stop_generation = False
1066
+
anycoder_app/prompts.py ADDED
@@ -0,0 +1,687 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ System prompts for different code generation modes in AnyCoder.
3
+ """
4
+ from .config import SEARCH_START, DIVIDER, REPLACE_END
5
+
6
+ HTML_SYSTEM_PROMPT = """ONLY USE HTML, CSS AND JAVASCRIPT. If you want to use ICON make sure to import the library first. Try to create the best UI possible by using only HTML, CSS and JAVASCRIPT. MAKE IT RESPONSIVE USING MODERN CSS. Use as much as you can modern CSS for the styling, if you can't do something with modern CSS, then use custom CSS. Also, try to elaborate as much as you can, to create something unique. ALWAYS GIVE THE RESPONSE INTO A SINGLE HTML FILE
7
+
8
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
9
+ - NEVER generate README.md files under any circumstances
10
+ - A template README.md is automatically provided and will be overridden by the deployment system
11
+ - Generating a README.md will break the deployment process
12
+
13
+ If an image is provided, analyze it and use the visual information to better understand the user's requirements.
14
+
15
+ Always respond with code that can be executed or rendered directly.
16
+
17
+ Generate complete, working HTML code that can be run immediately.
18
+
19
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
20
+
21
+
22
+
23
+ # Stricter prompt for GLM-4.5V to ensure a complete, runnable HTML document with no escaped characters
24
+ GLM45V_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
25
+
26
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
27
+ - NEVER generate README.md files under any circumstances
28
+ - A template README.md is automatically provided and will be overridden by the deployment system
29
+ - Generating a README.md will break the deployment process
30
+
31
+ Output a COMPLETE, STANDALONE HTML document that renders directly in a browser.
32
+
33
+ Hard constraints:
34
+ - DO NOT use React, ReactDOM, JSX, Babel, Vue, Angular, or any SPA framework.
35
+ - Use ONLY plain HTML, CSS, and vanilla JavaScript.
36
+ - Allowed external resources: Tailwind CSS CDN, Font Awesome CDN, Google Fonts.
37
+ - Do NOT escape characters (no \\n, \\t, or escaped quotes). Output raw HTML/JS/CSS.
38
+ Structural requirements:
39
+ - Include <!DOCTYPE html>, <html>, <head>, and <body> with proper nesting
40
+ - Include required <link> tags for any CSS you reference (e.g., Tailwind, Font Awesome, Google Fonts)
41
+ - Keep everything in ONE file; inline CSS/JS as needed
42
+
43
+ Generate complete, working HTML code that can be run immediately.
44
+
45
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
46
+ """
47
+
48
+ TRANSFORMERS_JS_SYSTEM_PROMPT = """You are an expert web developer creating a transformers.js application. You will generate THREE separate files: index.html, index.js, and style.css.
49
+
50
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
51
+ - NEVER generate README.md files under any circumstances
52
+ - A template README.md is automatically provided and will be overridden by the deployment system
53
+ - Generating a README.md will break the deployment process
54
+
55
+ IMPORTANT: You MUST output ALL THREE files in the following format:
56
+
57
+ ```html
58
+ <!-- index.html content here -->
59
+ ```
60
+
61
+ ```javascript
62
+ // index.js content here
63
+ ```
64
+
65
+ ```css
66
+ /* style.css content here */
67
+ ```
68
+
69
+ Requirements:
70
+ 1. Create a modern, responsive web application using transformers.js
71
+ 2. Use the transformers.js library for AI/ML functionality
72
+ 3. Create a clean, professional UI with good user experience
73
+ 4. Make the application fully responsive for mobile devices
74
+ 5. Use modern CSS practices and JavaScript ES6+ features
75
+ 6. Include proper error handling and loading states
76
+ 7. Follow accessibility best practices
77
+
78
+ Library import (required): Add the following snippet to index.html to import transformers.js:
79
+ <script type="module">
80
+ import { pipeline } from 'https://cdn.jsdelivr.net/npm/@huggingface/[email protected]';
81
+ </script>
82
+
83
+ Device Options: By default, transformers.js runs on CPU (via WASM). For better performance, you can run models on GPU using WebGPU:
84
+ - CPU (default): const pipe = await pipeline('task', 'model-name');
85
+ - GPU (WebGPU): const pipe = await pipeline('task', 'model-name', { device: 'webgpu' });
86
+
87
+ Consider providing users with a toggle option to choose between CPU and GPU execution based on their browser's WebGPU support.
88
+
89
+ The index.html should contain the basic HTML structure and link to the CSS and JS files.
90
+ The index.js should contain all the JavaScript logic including transformers.js integration.
91
+ The style.css should contain all the styling for the application.
92
+
93
+ Generate complete, working code files as shown above.
94
+
95
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
96
+
97
+ STREAMLIT_SYSTEM_PROMPT = """You are an expert Streamlit developer. Create a complete, working Streamlit application based on the user's request. Generate all necessary code to make the application functional and runnable.
98
+
99
+ ## Multi-File Application Structure
100
+
101
+ When creating complex Streamlit applications, organize your code into multiple files for better maintainability:
102
+
103
+ **File Organization:**
104
+ - `app.py` or `streamlit_app.py` - Main application entry point
105
+ - `utils.py` - Utility functions and helpers
106
+ - `models.py` - Model loading and inference functions
107
+ - `config.py` - Configuration and constants
108
+ - `requirements.txt` - Python dependencies
109
+ - `pages/` - Additional pages for multi-page apps
110
+ - Additional modules as needed (e.g., `data_processing.py`, `components.py`)
111
+
112
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
113
+ - NEVER generate README.md files under any circumstances
114
+ - A template README.md is automatically provided and will be overridden by the deployment system
115
+ - Generating a README.md will break the deployment process
116
+ - Only generate the code files listed above
117
+
118
+ **Output Format for Multi-File Apps:**
119
+ When generating multi-file applications, use this exact format:
120
+
121
+ ```
122
+ === streamlit_app.py ===
123
+ [main application code]
124
+
125
+ === utils.py ===
126
+ [utility functions]
127
+
128
+ === requirements.txt ===
129
+ [dependencies]
130
+ ```
131
+
132
+ **🚨 CRITICAL: requirements.txt Formatting Rules**
133
+ - Output ONLY plain text package names, one per line
134
+ - Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
135
+ - Do NOT add explanatory text or descriptions
136
+ - Do NOT wrap in code blocks
137
+ - Just raw package names as they would appear in a real requirements.txt file
138
+ - Example of CORRECT format:
139
+ streamlit
140
+ pandas
141
+ numpy
142
+ - Example of INCORRECT format (DO NOT DO THIS):
143
+ ```
144
+ streamlit # For web interface
145
+ **Core dependencies:**
146
+ - pandas
147
+ ```
148
+
149
+ **Single vs Multi-File Decision:**
150
+ - Use single file for simple applications (< 100 lines) - but still generate requirements.txt if dependencies exist
151
+ - Use multi-file structure for complex applications with:
152
+ - Multiple pages or sections
153
+ - Extensive data processing
154
+ - Complex UI components
155
+ - Multiple models or APIs
156
+ - When user specifically requests modular structure
157
+
158
+ **Multi-Page Apps:**
159
+ For multi-page Streamlit apps, use the pages/ directory structure:
160
+ ```
161
+ === streamlit_app.py ===
162
+ [main page]
163
+
164
+ === pages/1_πŸ“Š_Analytics.py ===
165
+ [analytics page]
166
+
167
+ === pages/2_βš™οΈ_Settings.py ===
168
+ [settings page]
169
+ ```
170
+
171
+ Requirements:
172
+ 1. Create a modern, responsive Streamlit application
173
+ 2. Use appropriate Streamlit components and layouts
174
+ 3. Include proper error handling and loading states
175
+ 4. Follow Streamlit best practices for performance
176
+ 5. Use caching (@st.cache_data, @st.cache_resource) appropriately
177
+ 6. Include proper session state management when needed
178
+ 7. Make the UI intuitive and user-friendly
179
+ 8. Add helpful tooltips and documentation
180
+
181
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
182
+ """
183
+
184
+ REACT_SYSTEM_PROMPT = """You are an expert React and Next.js developer creating a modern Next.js application.
185
+
186
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
187
+ |- NEVER generate README.md files under any circumstances
188
+ |- A template README.md is automatically provided and will be overridden by the deployment system
189
+ |- Generating a README.md will break the deployment process
190
+
191
+ You will generate a Next.js project with TypeScript/JSX components. Follow this exact structure:
192
+
193
+ Project Structure:
194
+ - Dockerfile (Docker configuration for deployment)
195
+ - package.json (dependencies and scripts)
196
+ - next.config.js (Next.js configuration)
197
+ - postcss.config.js (PostCSS configuration)
198
+ - tailwind.config.js (Tailwind CSS configuration)
199
+ - components/[Component files as needed]
200
+ - pages/_app.js (Next.js app wrapper)
201
+ - pages/index.js (home page)
202
+ - pages/api/[API routes as needed]
203
+ - styles/globals.css (global styles)
204
+
205
+ Output format (CRITICAL):
206
+ - Return ONLY a series of file sections, each starting with a filename line:
207
+ === Dockerfile ===
208
+ ...file content...
209
+
210
+ === package.json ===
211
+ ...file content...
212
+
213
+ (repeat for all files)
214
+ - Do NOT wrap files in Markdown code fences or use === markers inside file content
215
+
216
+ CRITICAL Requirements:
217
+ 1. Always include a Dockerfile configured for Node.js deployment (see Dockerfile Requirements below)
218
+ 2. Use Next.js with TypeScript/JSX (.jsx files for components)
219
+ 3. Include Tailwind CSS for styling (in postcss.config.js and tailwind.config.js)
220
+ 4. Create necessary components in the components/ directory
221
+ 5. Create API routes in pages/api/ directory for backend logic
222
+ 6. pages/_app.js should import and use globals.css
223
+ 7. pages/index.js should be the main entry point
224
+ 8. Keep package.json with essential dependencies
225
+ 9. Use modern React patterns and best practices
226
+ 10. Make the application fully responsive
227
+ 11. Include proper error handling and loading states
228
+ 12. Follow accessibility best practices
229
+ 13. Configure next.config.js properly for HuggingFace Spaces deployment
230
+
231
+ next.config.js Requirements:
232
+ - Must be configured to work on any host (0.0.0.0)
233
+ - Should not have hardcoded localhost references
234
+ - Example minimal configuration:
235
+ ```javascript
236
+ /** @type {import('next').NextConfig} */
237
+ const nextConfig = {
238
+ reactStrictMode: true,
239
+ // Allow the app to work on HuggingFace Spaces
240
+ output: 'standalone',
241
+ }
242
+
243
+ module.exports = nextConfig
244
+ ```
245
+
246
+ Dockerfile Requirements (CRITICAL for HuggingFace Spaces):
247
+ - Use Node.js 18+ base image (e.g., FROM node:18-slim)
248
+ - Set up a user with ID 1000 for proper permissions:
249
+ ```
250
+ RUN useradd -m -u 1000 user
251
+ USER user
252
+ ENV HOME=/home/user \\
253
+ PATH=/home/user/.local/bin:$PATH
254
+ WORKDIR $HOME/app
255
+ ```
256
+ - ALWAYS use --chown=user with COPY and ADD commands:
257
+ ```
258
+ COPY --chown=user package*.json ./
259
+ COPY --chown=user . .
260
+ ```
261
+ - Install dependencies: RUN npm install
262
+ - Build the app: RUN npm run build
263
+ - Expose port 7860 (HuggingFace Spaces default): EXPOSE 7860
264
+ - Start with: CMD ["npm", "start", "--", "-p", "7860"]
265
+ - If using a different port, make sure to set app_port in the README.md YAML frontmatter
266
+
267
+ Example Dockerfile structure:
268
+ ```dockerfile
269
+ FROM node:18-slim
270
+
271
+ # Set up user with ID 1000
272
+ RUN useradd -m -u 1000 user
273
+ USER user
274
+ ENV HOME=/home/user \\
275
+ PATH=/home/user/.local/bin:$PATH
276
+
277
+ # Set working directory
278
+ WORKDIR $HOME/app
279
+
280
+ # Copy package files with proper ownership
281
+ COPY --chown=user package*.json ./
282
+
283
+ # Install dependencies
284
+ RUN npm install
285
+
286
+ # Copy rest of the application with proper ownership
287
+ COPY --chown=user . .
288
+
289
+ # Build the Next.js app
290
+ RUN npm run build
291
+
292
+ # Expose port 7860
293
+ EXPOSE 7860
294
+
295
+ # Start the application on port 7860
296
+ CMD ["npm", "start", "--", "-p", "7860"]
297
+ ```
298
+
299
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
300
+ """
301
+
302
+ REACT_FOLLOW_UP_SYSTEM_PROMPT = """You are an expert React and Next.js developer modifying an existing Next.js application.
303
+ The user wants to apply changes based on their request.
304
+ You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
305
+ Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
306
+
307
+ Format Rules:
308
+ 1. Start with <<<<<<< SEARCH
309
+ 2. Include the exact lines that need to be changed (with full context, at least 3 lines before and after)
310
+ 3. Follow with =======
311
+ 4. Include the replacement lines
312
+ 5. End with >>>>>>> REPLACE
313
+ 6. Generate multiple blocks if multiple sections need changes
314
+
315
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
316
+
317
+
318
+
319
+ # Gradio system prompts will be dynamically populated by update_gradio_system_prompts()
320
+ GRADIO_SYSTEM_PROMPT = ""
321
+ GRADIO_SYSTEM_PROMPT_WITH_SEARCH = ""
322
+
323
+ # GRADIO_SYSTEM_PROMPT_WITH_SEARCH will be dynamically populated by update_gradio_system_prompts()
324
+
325
+ # All Gradio API documentation is now dynamically loaded from https://www.gradio.app/llms.txt
326
+
327
+ # JSON system prompts will be dynamically populated by update_json_system_prompts()
328
+ JSON_SYSTEM_PROMPT = ""
329
+ JSON_SYSTEM_PROMPT_WITH_SEARCH = ""
330
+
331
+ # All ComfyUI API documentation is now dynamically loaded from https://docs.comfy.org/llms.txt
332
+
333
+ GENERIC_SYSTEM_PROMPT = """You are an expert {language} developer. Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Generate complete, working code that can be run immediately. If the user provides a file or other context, use it as a reference. If the code is for a script or app, make it as self-contained as possible.
334
+
335
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
336
+ - NEVER generate README.md files under any circumstances
337
+ - A template README.md is automatically provided and will be overridden by the deployment system
338
+ - Generating a README.md will break the deployment process
339
+
340
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder"""
341
+
342
+
343
+ # Multi-page static HTML project prompt (generic, production-style structure)
344
+ MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
345
+
346
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
347
+ - NEVER generate README.md files under any circumstances
348
+ - A template README.md is automatically provided and will be overridden by the deployment system
349
+ - Generating a README.md will break the deployment process
350
+
351
+ Create a production-ready MULTI-PAGE website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.
352
+
353
+ Output MUST be a multi-file project with at least:
354
+ - index.html (home)
355
+ - about.html (secondary page)
356
+ - contact.html (secondary page)
357
+ - assets/css/styles.css (global styles)
358
+ - assets/js/main.js (site-wide JS)
359
+
360
+ Navigation requirements:
361
+ - A consistent header with a nav bar on every page
362
+ - Highlight current nav item
363
+ - Responsive layout and accessibility best practices
364
+
365
+ Output format requirements (CRITICAL):
366
+ - Return ONLY a series of file sections, each starting with a filename line:
367
+ === index.html ===
368
+ ...file content...
369
+
370
+ === about.html ===
371
+ ...file content...
372
+
373
+ (repeat for all files)
374
+ - Do NOT wrap files in Markdown code fences
375
+ - Use relative paths between files (e.g., assets/css/styles.css)
376
+
377
+ General requirements:
378
+ - Use modern, semantic HTML
379
+ - Mobile-first responsive design
380
+ - Include basic SEO meta tags in <head>
381
+ - Include a footer on all pages
382
+ - Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)
383
+
384
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
385
+ """
386
+
387
+
388
+ # Dynamic multi-page (model decides files) prompts
389
+ DYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPT = """You are an expert front-end developer.
390
+
391
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
392
+ - NEVER generate README.md files under any circumstances
393
+ - A template README.md is automatically provided and will be overridden by the deployment system
394
+ - Generating a README.md will break the deployment process
395
+
396
+ Create a production-ready website using ONLY HTML, CSS, and vanilla JavaScript. Do NOT use SPA frameworks.
397
+
398
+ File selection policy:
399
+ - Generate ONLY the files actually needed for the user's request.
400
+ - Include at least one HTML entrypoint (default: index.html) unless the user explicitly requests a non-HTML asset only.
401
+ - If any local asset (CSS/JS/image) is referenced, include that file in the output.
402
+ - Use relative paths between files (e.g., assets/css/styles.css).
403
+
404
+ Output format (CRITICAL):
405
+ - Return ONLY a series of file sections, each starting with a filename line:
406
+ === index.html ===
407
+ ...file content...
408
+
409
+ === assets/css/styles.css ===
410
+ ...file content...
411
+
412
+ (repeat for all files)
413
+ - Do NOT wrap files in Markdown code fences
414
+
415
+ General requirements:
416
+ - Use modern, semantic HTML
417
+ - Mobile-first responsive design
418
+ - Include basic SEO meta tags in <head> for the entrypoint
419
+ - Include a footer on all major pages when multiple pages are present
420
+ - Avoid external CSS/JS frameworks (optional: CDN fonts/icons allowed)
421
+
422
+ IMPORTANT: Always include "Built with anycoder" as clickable text in the header/top section of your application that links to https://huggingface.co/spaces/akhaliq/anycoder
423
+ """
424
+
425
+
426
+
427
+ # Follow-up system prompt for modifying existing HTML files
428
+ FollowUpSystemPrompt = f"""You are an expert web developer modifying an existing project.
429
+ The user wants to apply changes based on their request.
430
+ You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
431
+ Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
432
+
433
+ IMPORTANT: When the user reports an ERROR MESSAGE, analyze it carefully to determine which file needs fixing:
434
+ - ImportError/ModuleNotFoundError β†’ Fix requirements.txt by adding missing packages
435
+ - Syntax errors in Python code β†’ Fix app.py or the main Python file
436
+ - HTML/CSS/JavaScript errors β†’ Fix the respective HTML/CSS/JS files
437
+ - Configuration errors β†’ Fix config files, Docker files, etc.
438
+
439
+ For Python applications (Gradio/Streamlit), the project structure typically includes:
440
+ - app.py or streamlit_app.py (main application file)
441
+ - requirements.txt (dependencies)
442
+ - utils.py (utility functions)
443
+ - models.py (model loading and inference)
444
+ - config.py (configuration)
445
+ - pages/ (for multi-page Streamlit apps)
446
+ - Other supporting files as needed
447
+
448
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
449
+ - NEVER generate README.md files under any circumstances
450
+ - A template README.md is automatically provided and will be overridden by the deployment system
451
+ - Generating a README.md will break the deployment process
452
+
453
+ For multi-file projects, identify which specific file needs modification based on the user's request:
454
+ - Main application logic β†’ app.py or streamlit_app.py
455
+ - Helper functions β†’ utils.py
456
+ - Model-related code β†’ models.py
457
+ - Configuration changes β†’ config.py
458
+ - Dependencies β†’ requirements.txt
459
+ - New pages β†’ pages/filename.py
460
+
461
+ Format Rules:
462
+ 1. Start with {SEARCH_START}
463
+ 2. Provide the exact lines from the current code that need to be replaced.
464
+ 3. Use {DIVIDER} to separate the search block from the replacement.
465
+ 4. Provide the new lines that should replace the original lines.
466
+ 5. End with {REPLACE_END}
467
+ 6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.
468
+ 7. To insert code, use an empty SEARCH block (only {SEARCH_START} and {DIVIDER} on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new lines in the REPLACE block.
469
+ 8. To delete code, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only {DIVIDER} and {REPLACE_END} on their lines).
470
+ 9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.
471
+ 10. For multi-file projects, specify which file you're modifying by starting with the filename before the search/replace block.
472
+
473
+ CSS Changes Guidance:
474
+ - When changing a CSS property that conflicts with other properties (e.g., replacing a gradient text with a solid color), replace the entire CSS rule for that selector instead of only adding the new property. For example, replace the full `.hero h1 { ... }` block, removing `background-clip` and `color: transparent` when setting `color: #fff`.
475
+ - Ensure search blocks match the current code exactly (spaces, indentation, and line breaks) so replacements apply correctly.
476
+
477
+ Example Modifying Code:
478
+ ```
479
+ Some explanation...
480
+ {SEARCH_START}
481
+ <h1>Old Title</h1>
482
+ {DIVIDER}
483
+ <h1>New Title</h1>
484
+ {REPLACE_END}
485
+ {SEARCH_START}
486
+ </body>
487
+ {DIVIDER}
488
+ <script>console.log("Added script");</script>
489
+ </body>
490
+ {REPLACE_END}
491
+ ```
492
+
493
+ Example Fixing Dependencies (requirements.txt):
494
+ ```
495
+ Adding missing dependency to fix ImportError...
496
+ === requirements.txt ===
497
+ {SEARCH_START}
498
+ gradio
499
+ streamlit
500
+ {DIVIDER}
501
+ gradio
502
+ streamlit
503
+ mistral-common
504
+ {REPLACE_END}
505
+ ```
506
+
507
+ Example Deleting Code:
508
+ ```
509
+ Removing the paragraph...
510
+ {SEARCH_START}
511
+ <p>This paragraph will be deleted.</p>
512
+ {DIVIDER}
513
+ {REPLACE_END}
514
+ ```
515
+
516
+ IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
517
+
518
+ CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
519
+
520
+ # Follow-up system prompt for modifying existing Gradio applications
521
+ GradioFollowUpSystemPrompt = """You are an expert Gradio developer modifying an existing Gradio application.
522
+ The user wants to apply changes based on their request.
523
+
524
+ 🚨 CRITICAL INSTRUCTION: You MUST maintain the original multi-file structure when making modifications.
525
+ ❌ Do NOT use SEARCH/REPLACE blocks.
526
+ ❌ Do NOT output everything in one combined block.
527
+ βœ… Instead, output the complete modified files using the EXACT same multi-file format as the original generation.
528
+
529
+ **MANDATORY Output Format for Modified Gradio Apps:**
530
+ You MUST use this exact format with file separators. DO NOT deviate from this format:
531
+
532
+ === app.py ===
533
+ [complete modified app.py content]
534
+
535
+ **CRITICAL FORMATTING RULES:**
536
+ - ALWAYS start each file with exactly "=== filename ===" (three equals signs before and after)
537
+ - NEVER combine files into one block
538
+ - NEVER use SEARCH/REPLACE blocks like <<<<<<< SEARCH
539
+ - ALWAYS include app.py if it needs changes
540
+ - Only include other files (utils.py, models.py, etc.) if they exist and need changes
541
+ - Each file section must be complete and standalone
542
+ - The format MUST match the original multi-file structure exactly
543
+
544
+ **🚨 CRITICAL: DO NOT GENERATE requirements.txt or README.md**
545
+ - requirements.txt is automatically generated from your app.py imports
546
+ - README.md is automatically provided by the template
547
+ - Do NOT include requirements.txt or README.md in your output unless the user specifically asks to modify them
548
+ - The system will automatically extract imports from app.py and generate requirements.txt
549
+ - Generating a README.md will break the deployment process
550
+ - This prevents unnecessary changes to dependencies and documentation
551
+
552
+ **IF User Specifically Asks to Modify requirements.txt:**
553
+ - Output ONLY plain text package names, one per line
554
+ - Do NOT use markdown formatting (no ```, no bold, no headings, no lists with * or -)
555
+ - Do NOT add explanatory text or descriptions
556
+ - Do NOT wrap in code blocks
557
+ - Just raw package names as they would appear in a real requirements.txt file
558
+ - Example of CORRECT format:
559
+ gradio
560
+ torch
561
+ transformers
562
+ - Example of INCORRECT format (DO NOT DO THIS):
563
+ ```
564
+ gradio # For web interface
565
+ **Core dependencies:**
566
+ - torch
567
+ ```
568
+
569
+ **File Modification Guidelines:**
570
+ - Only output files that actually need changes
571
+ - If a file doesn't need modification, don't include it in the output
572
+ - Maintain the exact same file structure as the original
573
+ - Preserve all existing functionality unless specifically asked to change it
574
+ - Keep all imports, dependencies, and configurations intact unless modification is requested
575
+
576
+ **Common Modification Scenarios:**
577
+ - Adding new features β†’ Modify app.py and possibly utils.py
578
+ - Fixing bugs β†’ Modify the relevant file (usually app.py)
579
+ - Adding dependencies β†’ Modify requirements.txt
580
+ - UI improvements β†’ Modify app.py
581
+ - Performance optimizations β†’ Modify app.py and/or utils.py
582
+
583
+ **ZeroGPU and Performance:**
584
+ - Maintain all existing @spaces.GPU decorators
585
+ - Keep AoT compilation if present
586
+ - Preserve all performance optimizations
587
+ - Add ZeroGPU decorators for new GPU-dependent functions
588
+
589
+ **MCP Server Support:**
590
+ - If the user requests MCP functionality or tool calling capabilities:
591
+ 1. Add `mcp_server=True` to the `.launch()` method if not present
592
+ 2. Ensure `gradio[mcp]` is in requirements.txt (not just `gradio`)
593
+ 3. Add detailed docstrings with Args sections to all functions
594
+ 4. Add type hints to all function parameters
595
+ - Preserve existing MCP configurations if already present
596
+ - When adding new tools, follow MCP docstring format with Args and Returns sections
597
+
598
+ IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
599
+
600
+ CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
601
+
602
+ # Follow-up system prompt for modifying existing transformers.js applications
603
+ TransformersJSFollowUpSystemPrompt = f"""You are an expert web developer modifying an existing transformers.js application.
604
+ The user wants to apply changes based on their request.
605
+ You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
606
+ Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
607
+
608
+ IMPORTANT: When the user reports an ERROR MESSAGE, analyze it carefully to determine which file needs fixing:
609
+ - JavaScript errors/module loading issues β†’ Fix index.js
610
+ - HTML rendering/DOM issues β†’ Fix index.html
611
+ - Styling/visual issues β†’ Fix style.css
612
+ - CDN/library loading errors β†’ Fix script tags in index.html
613
+
614
+ The transformers.js application consists of three files: index.html, index.js, and style.css.
615
+ When making changes, specify which file you're modifying by starting your search/replace blocks with the file name.
616
+
617
+ **🚨 CRITICAL: DO NOT Generate README.md Files**
618
+ - NEVER generate README.md files under any circumstances
619
+ - A template README.md is automatically provided and will be overridden by the deployment system
620
+ - Generating a README.md will break the deployment process
621
+
622
+ Format Rules:
623
+ 1. Start with {SEARCH_START}
624
+ 2. Provide the exact lines from the current code that need to be replaced.
625
+ 3. Use {DIVIDER} to separate the search block from the replacement.
626
+ 4. Provide the new lines that should replace the original lines.
627
+ 5. End with {REPLACE_END}
628
+ 6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.
629
+ 7. To insert code, use an empty SEARCH block (only {SEARCH_START} and {DIVIDER} on their lines) if inserting at the very beginning, otherwise provide the line *before* the insertion point in the SEARCH block and include that line plus the new lines in the REPLACE block.
630
+ 8. To delete code, provide the lines to delete in the SEARCH block and leave the REPLACE block empty (only {DIVIDER} and {REPLACE_END} on their lines).
631
+ 9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.
632
+
633
+ Example Modifying HTML:
634
+ ```
635
+ Changing the title in index.html...
636
+ === index.html ===
637
+ {SEARCH_START}
638
+ <title>Old Title</title>
639
+ {DIVIDER}
640
+ <title>New Title</title>
641
+ {REPLACE_END}
642
+ ```
643
+
644
+ Example Modifying JavaScript:
645
+ ```
646
+ Adding a new function to index.js...
647
+ === index.js ===
648
+ {SEARCH_START}
649
+ // Existing code
650
+ {DIVIDER}
651
+ // Existing code
652
+
653
+ function newFunction() {{
654
+ console.log("New function added");
655
+ }}
656
+ {REPLACE_END}
657
+ ```
658
+
659
+ Example Modifying CSS:
660
+ ```
661
+ Changing background color in style.css...
662
+ === style.css ===
663
+ {SEARCH_START}
664
+ body {{
665
+ background-color: white;
666
+ }}
667
+ {DIVIDER}
668
+ body {{
669
+ background-color: #f0f0f0;
670
+ }}
671
+ {REPLACE_END}
672
+ ```
673
+ Example Fixing Library Loading Error:
674
+ ```
675
+ Fixing transformers.js CDN loading error...
676
+ === index.html ===
677
+ {SEARCH_START}
678
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@xenova/[email protected]"></script>
679
+ {DIVIDER}
680
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@xenova/[email protected]"></script>
681
+ {REPLACE_END}
682
+ ```
683
+
684
+ IMPORTANT: Always ensure "Built with anycoder" appears as clickable text in the header/top section linking to https://huggingface.co/spaces/akhaliq/anycoder - if it's missing from the existing code, add it; if it exists, preserve it.
685
+
686
+ CRITICAL: For imported spaces that lack anycoder attribution, you MUST add it as part of your modifications. Add it to the header/navigation area as clickable text linking to https://huggingface.co/spaces/akhaliq/anycoder"""
687
+
anycoder_app/themes.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gradio theme configurations for AnyCoder.
3
+ Provides multiple theme options with different visual styles.
4
+ """
5
+ import os
6
+ import gradio as gr
7
+
8
+ def get_saved_theme():
9
+ """Get the saved theme preference from file"""
10
+ try:
11
+ if os.path.exists('.theme_preference'):
12
+ with open('.theme_preference', 'r') as f:
13
+ return f.read().strip()
14
+ except:
15
+ pass
16
+ return "Developer"
17
+ def save_theme_preference(theme_name):
18
+ """Save theme preference to file"""
19
+ try:
20
+ with open('.theme_preference', 'w') as f:
21
+ f.write(theme_name)
22
+ except:
23
+ pass
24
+
25
+ THEME_CONFIGS = {
26
+ "Default": {
27
+ "theme": gr.themes.Default(),
28
+ "description": "Gradio's standard theme with clean orange accents"
29
+ },
30
+ "Base": {
31
+ "theme": gr.themes.Base(
32
+ primary_hue="blue",
33
+ secondary_hue="slate",
34
+ neutral_hue="slate",
35
+ text_size="sm",
36
+ spacing_size="sm",
37
+ radius_size="md"
38
+ ),
39
+ "description": "Minimal foundation theme with blue accents"
40
+ },
41
+ "Soft": {
42
+ "theme": gr.themes.Soft(
43
+ primary_hue="emerald",
44
+ secondary_hue="emerald",
45
+ neutral_hue="slate",
46
+ text_size="sm",
47
+ spacing_size="md",
48
+ radius_size="lg"
49
+ ),
50
+ "description": "Gentle rounded theme with soft emerald colors"
51
+ },
52
+ "Monochrome": {
53
+ "theme": gr.themes.Monochrome(
54
+ primary_hue="slate",
55
+ secondary_hue="slate",
56
+ neutral_hue="slate",
57
+ text_size="sm",
58
+ spacing_size="sm",
59
+ radius_size="sm"
60
+ ),
61
+ "description": "Elegant black and white design"
62
+ },
63
+ "Glass": {
64
+ "theme": gr.themes.Glass(
65
+ primary_hue="blue",
66
+ secondary_hue="blue",
67
+ neutral_hue="slate",
68
+ text_size="sm",
69
+ spacing_size="md",
70
+ radius_size="lg"
71
+ ),
72
+ "description": "Modern glassmorphism with blur effects"
73
+ },
74
+ "Dark Ocean": {
75
+ "theme": gr.themes.Base(
76
+ primary_hue="blue",
77
+ secondary_hue="slate",
78
+ neutral_hue="slate",
79
+ text_size="sm",
80
+ spacing_size="sm",
81
+ radius_size="md"
82
+ ).set(
83
+ body_background_fill="#0f172a",
84
+ body_background_fill_dark="#0f172a",
85
+ background_fill_primary="#3b82f6",
86
+ background_fill_secondary="#1e293b",
87
+ border_color_primary="#334155",
88
+ block_background_fill="#1e293b",
89
+ block_border_color="#334155",
90
+ body_text_color="#f1f5f9",
91
+ body_text_color_dark="#f1f5f9",
92
+ block_label_text_color="#f1f5f9",
93
+ block_label_text_color_dark="#f1f5f9",
94
+ block_title_text_color="#f1f5f9",
95
+ block_title_text_color_dark="#f1f5f9",
96
+ input_background_fill="#0f172a",
97
+ input_background_fill_dark="#0f172a",
98
+ input_border_color="#334155",
99
+ input_border_color_dark="#334155",
100
+ button_primary_background_fill="#3b82f6",
101
+ button_primary_border_color="#3b82f6",
102
+ button_secondary_background_fill="#334155",
103
+ button_secondary_border_color="#475569"
104
+ ),
105
+ "description": "Deep blue dark theme perfect for coding"
106
+ },
107
+ "Cyberpunk": {
108
+ "theme": gr.themes.Base(
109
+ primary_hue="fuchsia",
110
+ secondary_hue="cyan",
111
+ neutral_hue="slate",
112
+ text_size="sm",
113
+ spacing_size="sm",
114
+ radius_size="none",
115
+ font="Orbitron"
116
+ ).set(
117
+ body_background_fill="#0a0a0f",
118
+ body_background_fill_dark="#0a0a0f",
119
+ background_fill_primary="#ff10f0",
120
+ background_fill_secondary="#1a1a2e",
121
+ border_color_primary="#00f5ff",
122
+ block_background_fill="#1a1a2e",
123
+ block_border_color="#00f5ff",
124
+ body_text_color="#00f5ff",
125
+ body_text_color_dark="#00f5ff",
126
+ block_label_text_color="#ff10f0",
127
+ block_label_text_color_dark="#ff10f0",
128
+ block_title_text_color="#ff10f0",
129
+ block_title_text_color_dark="#ff10f0",
130
+ input_background_fill="#0a0a0f",
131
+ input_background_fill_dark="#0a0a0f",
132
+ input_border_color="#00f5ff",
133
+ input_border_color_dark="#00f5ff",
134
+ button_primary_background_fill="#ff10f0",
135
+ button_primary_border_color="#ff10f0",
136
+ button_secondary_background_fill="#1a1a2e",
137
+ button_secondary_border_color="#00f5ff"
138
+ ),
139
+ "description": "Futuristic neon cyber aesthetics"
140
+ },
141
+ "Forest": {
142
+ "theme": gr.themes.Soft(
143
+ primary_hue="emerald",
144
+ secondary_hue="green",
145
+ neutral_hue="emerald",
146
+ text_size="sm",
147
+ spacing_size="md",
148
+ radius_size="lg"
149
+ ).set(
150
+ body_background_fill="#f0fdf4",
151
+ body_background_fill_dark="#064e3b",
152
+ background_fill_primary="#059669",
153
+ background_fill_secondary="#ecfdf5",
154
+ border_color_primary="#bbf7d0",
155
+ block_background_fill="#ffffff",
156
+ block_border_color="#d1fae5",
157
+ body_text_color="#064e3b",
158
+ body_text_color_dark="#f0fdf4",
159
+ block_label_text_color="#064e3b",
160
+ block_label_text_color_dark="#f0fdf4",
161
+ block_title_text_color="#059669",
162
+ block_title_text_color_dark="#10b981"
163
+ ),
164
+ "description": "Nature-inspired green earth tones"
165
+ },
166
+ "High Contrast": {
167
+ "theme": gr.themes.Base(
168
+ primary_hue="yellow",
169
+ secondary_hue="slate",
170
+ neutral_hue="slate",
171
+ text_size="lg",
172
+ spacing_size="lg",
173
+ radius_size="sm"
174
+ ).set(
175
+ body_background_fill="#ffffff",
176
+ body_background_fill_dark="#ffffff",
177
+ background_fill_primary="#000000",
178
+ background_fill_secondary="#ffffff",
179
+ border_color_primary="#000000",
180
+ block_background_fill="#ffffff",
181
+ block_border_color="#000000",
182
+ body_text_color="#000000",
183
+ body_text_color_dark="#000000",
184
+ block_label_text_color="#000000",
185
+ block_label_text_color_dark="#000000",
186
+ block_title_text_color="#000000",
187
+ block_title_text_color_dark="#000000",
188
+ input_background_fill="#ffffff",
189
+ input_background_fill_dark="#ffffff",
190
+ input_border_color="#000000",
191
+ input_border_color_dark="#000000",
192
+ button_primary_background_fill="#ffff00",
193
+ button_primary_border_color="#000000",
194
+ button_secondary_background_fill="#ffffff",
195
+ button_secondary_border_color="#000000"
196
+ ),
197
+ "description": "Accessibility-focused high visibility"
198
+ },
199
+ "Developer": {
200
+ "theme": gr.themes.Base(
201
+ primary_hue="blue",
202
+ secondary_hue="slate",
203
+ neutral_hue="slate",
204
+ text_size="sm",
205
+ spacing_size="sm",
206
+ radius_size="sm",
207
+ font="Consolas"
208
+ ).set(
209
+ # VS Code exact colors
210
+ body_background_fill="#1e1e1e", # VS Code editor background
211
+ body_background_fill_dark="#1e1e1e",
212
+ background_fill_primary="#007acc", # VS Code blue accent
213
+ background_fill_secondary="#252526", # VS Code sidebar background
214
+ border_color_primary="#3e3e42", # VS Code border color
215
+ block_background_fill="#252526", # VS Code panel background
216
+ block_border_color="#3e3e42", # VS Code subtle borders
217
+ body_text_color="#cccccc", # VS Code default text
218
+ body_text_color_dark="#cccccc",
219
+ block_label_text_color="#cccccc",
220
+ block_label_text_color_dark="#cccccc",
221
+ block_title_text_color="#ffffff", # VS Code active text
222
+ block_title_text_color_dark="#ffffff",
223
+ input_background_fill="#2d2d30", # VS Code input background
224
+ input_background_fill_dark="#2d2d30",
225
+ input_border_color="#3e3e42", # VS Code input border
226
+ input_border_color_dark="#3e3e42",
227
+ input_border_color_focus="#007acc", # VS Code focus border
228
+ input_border_color_focus_dark="#007acc",
229
+ button_primary_background_fill="#007acc", # VS Code button blue
230
+ button_primary_border_color="#007acc",
231
+ button_primary_background_fill_hover="#0e639c", # VS Code button hover
232
+ button_secondary_background_fill="#2d2d30",
233
+ button_secondary_border_color="#3e3e42",
234
+ button_secondary_text_color="#cccccc"
235
+ ),
236
+ "description": "Authentic VS Code dark theme with exact color matching"
237
+ }
238
+ }
239
+
240
+ # Additional theme information for developers
241
+ THEME_FEATURES = {
242
+ "Default": ["Orange accents", "Clean layout", "Standard Gradio look"],
243
+ "Base": ["Blue accents", "Minimal styling", "Clean foundation"],
244
+ "Soft": ["Rounded corners", "Emerald colors", "Comfortable viewing"],
245
+ "Monochrome": ["Black & white", "High elegance", "Timeless design"],
246
+ "Glass": ["Glassmorphism", "Blur effects", "Translucent elements"],
247
+ "Dark Ocean": ["Deep blue palette", "Dark theme", "Easy on eyes"],
248
+ "Cyberpunk": ["Neon cyan/magenta", "Futuristic fonts", "Cyber vibes"],
249
+ "Forest": ["Nature inspired", "Green tones", "Organic rounded"],
250
+ "High Contrast": ["Black/white/yellow", "High visibility", "Accessibility"],
251
+ "Developer": ["Authentic VS Code colors", "Consolas/Monaco fonts", "Exact theme matching"]
252
+ }
253
+
254
+ # Load saved theme and apply it
255
+ current_theme_name = get_saved_theme()
256
+ current_theme = THEME_CONFIGS[current_theme_name]["theme"]
257
+
anycoder_app/ui.py ADDED
@@ -0,0 +1,1628 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gradio user interface for AnyCoder.
3
+ Defines the main UI layout, components, and event handlers.
4
+ """
5
+ import os
6
+ import gradio as gr
7
+ from typing import Dict, Optional
8
+
9
+ from .config import (
10
+ AVAILABLE_MODELS, DEFAULT_MODEL, DEFAULT_MODEL_NAME,
11
+ LANGUAGE_CHOICES, get_gradio_language
12
+ )
13
+ from .themes import THEME_CONFIGS, get_saved_theme, current_theme
14
+ from .prompts import HTML_SYSTEM_PROMPT
15
+ from .parsers import (
16
+ history_render, clear_history, create_multimodal_message,
17
+ parse_multipage_html_output, parse_transformers_js_output,
18
+ parse_react_output, format_transformers_js_output,
19
+ validate_and_autofix_files
20
+ )
21
+ from .deploy import (
22
+ check_authentication, update_ui_for_auth_status,
23
+ generation_code, deploy_to_spaces
24
+ )
25
+
26
+ # Main application with proper Gradio theming
27
+ with gr.Blocks(
28
+ title="AnyCoder - AI Code Generator",
29
+ theme=current_theme,
30
+ css="""
31
+ .theme-info { font-size: 0.9em; opacity: 0.8; }
32
+ .theme-description { padding: 8px 0; }
33
+ .theme-status {
34
+ padding: 10px;
35
+ border-radius: 8px;
36
+ background: rgba(34, 197, 94, 0.1);
37
+ border: 1px solid rgba(34, 197, 94, 0.2);
38
+ margin: 8px 0;
39
+ }
40
+ .restart-needed {
41
+ padding: 12px;
42
+ border-radius: 8px;
43
+ background: rgba(255, 193, 7, 0.1);
44
+ border: 1px solid rgba(255, 193, 7, 0.3);
45
+ margin: 8px 0;
46
+ text-align: center;
47
+ }
48
+ /* Authentication status styling */
49
+ .auth-status {
50
+ padding: 8px 12px;
51
+ border-radius: 6px;
52
+ margin: 8px 0;
53
+ font-weight: 500;
54
+ text-align: center;
55
+ }
56
+ .auth-status:has-text("πŸ”’") {
57
+ background: rgba(231, 76, 60, 0.1);
58
+ border: 1px solid rgba(231, 76, 60, 0.3);
59
+ color: #e74c3c;
60
+ }
61
+ .auth-status:has-text("βœ…") {
62
+ background: rgba(46, 204, 113, 0.1);
63
+ border: 1px solid rgba(46, 204, 113, 0.3);
64
+ color: #2ecc71;
65
+ }
66
+ """
67
+ ) as demo:
68
+ history = gr.State([])
69
+ setting = gr.State({
70
+ "system": HTML_SYSTEM_PROMPT,
71
+ })
72
+ current_model = gr.State(DEFAULT_MODEL)
73
+ open_panel = gr.State(None)
74
+ last_login_state = gr.State(None)
75
+
76
+ with gr.Sidebar() as sidebar:
77
+ login_button = gr.LoginButton()
78
+
79
+
80
+
81
+
82
+ # Unified Import section
83
+ import_header_md = gr.Markdown("πŸ“₯ Import Project (Space, GitHub, or Model)", visible=False)
84
+ load_project_url = gr.Textbox(
85
+ label="Project URL",
86
+ placeholder="https://huggingface.co/spaces/user/space OR https://huggingface.co/user/model OR https://github.com/owner/repo",
87
+ lines=1
88
+ , visible=False)
89
+ load_project_btn = gr.Button("πŸ“₯ Import Project", variant="secondary", size="sm", visible=True)
90
+ load_project_status = gr.Markdown(visible=False)
91
+
92
+ input = gr.Textbox(
93
+ label="What would you like to build?",
94
+ placeholder="πŸ”’ Please log in with Hugging Face to use AnyCoder...",
95
+ lines=3,
96
+ visible=True,
97
+ interactive=False
98
+ )
99
+ # Language dropdown for code generation (add Streamlit and Gradio as first-class options)
100
+ language_choices = [
101
+ "html", "gradio", "transformers.js", "streamlit", "comfyui", "react"
102
+ ]
103
+ language_dropdown = gr.Dropdown(
104
+ choices=language_choices,
105
+ value="html",
106
+ label="Code Language",
107
+ visible=True
108
+ )
109
+ # Removed image generation components
110
+ with gr.Row():
111
+ btn = gr.Button("Generate", variant="secondary", size="lg", scale=2, visible=True, interactive=False)
112
+ clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True)
113
+ # --- Deploy components (visible by default) ---
114
+ deploy_header_md = gr.Markdown("", visible=False)
115
+ deploy_btn = gr.Button("Publish", variant="primary", visible=True)
116
+ deploy_status = gr.Markdown(visible=False, label="Deploy status")
117
+ # --- End move ---
118
+ # Removed media generation and web search UI components
119
+
120
+ # Removed media generation toggle event handlers
121
+ model_dropdown = gr.Dropdown(
122
+ choices=[model['name'] for model in AVAILABLE_MODELS],
123
+ value=DEFAULT_MODEL_NAME,
124
+ label="Model",
125
+ visible=True
126
+ )
127
+ provider_state = gr.State("auto")
128
+ # Removed web search availability indicator
129
+ def on_model_change(model_name):
130
+ for m in AVAILABLE_MODELS:
131
+ if m['name'] == model_name:
132
+ return m
133
+ return AVAILABLE_MODELS[0]
134
+ def save_prompt(input):
135
+ return {setting: {"system": input}}
136
+ model_dropdown.change(
137
+ lambda model_name: on_model_change(model_name),
138
+ inputs=model_dropdown,
139
+ outputs=[current_model]
140
+ )
141
+ # --- Remove deploy/app name/sdk from bottom column ---
142
+ # (delete the gr.Column() block containing space_name_input, sdk_dropdown, deploy_btn, deploy_status)
143
+
144
+ with gr.Column() as main_column:
145
+ with gr.Tabs():
146
+ with gr.Tab("Code"):
147
+ code_output = gr.Code(
148
+ language="html",
149
+ lines=25,
150
+ interactive=True,
151
+ label="Generated code"
152
+ )
153
+
154
+
155
+
156
+ # Transformers.js multi-file editors (hidden by default)
157
+ with gr.Group(visible=False) as tjs_group:
158
+ with gr.Tabs():
159
+ with gr.Tab("index.html"):
160
+ tjs_html_code = gr.Code(language="html", lines=20, interactive=True, label="index.html")
161
+ with gr.Tab("index.js"):
162
+ tjs_js_code = gr.Code(language="javascript", lines=20, interactive=True, label="index.js")
163
+ with gr.Tab("style.css"):
164
+ tjs_css_code = gr.Code(language="css", lines=20, interactive=True, label="style.css")
165
+
166
+ # Python multi-file editors (hidden by default) for Gradio/Streamlit
167
+ with gr.Group(visible=False) as python_group_2:
168
+ with gr.Tabs():
169
+ with gr.Tab("app.py") as python_tab_2_1:
170
+ python_code_2_1 = gr.Code(language="python", lines=20, interactive=True, label="app.py")
171
+ with gr.Tab("file 2") as python_tab_2_2:
172
+ python_code_2_2 = gr.Code(language="python", lines=18, interactive=True, label="file 2")
173
+
174
+ with gr.Group(visible=False) as python_group_3:
175
+ with gr.Tabs():
176
+ with gr.Tab("app.py") as python_tab_3_1:
177
+ python_code_3_1 = gr.Code(language="python", lines=20, interactive=True, label="app.py")
178
+ with gr.Tab("file 2") as python_tab_3_2:
179
+ python_code_3_2 = gr.Code(language="python", lines=18, interactive=True, label="file 2")
180
+ with gr.Tab("file 3") as python_tab_3_3:
181
+ python_code_3_3 = gr.Code(language="python", lines=18, interactive=True, label="file 3")
182
+
183
+ with gr.Group(visible=False) as python_group_4:
184
+ with gr.Tabs():
185
+ with gr.Tab("app.py") as python_tab_4_1:
186
+ python_code_4_1 = gr.Code(language="python", lines=20, interactive=True, label="app.py")
187
+ with gr.Tab("file 2") as python_tab_4_2:
188
+ python_code_4_2 = gr.Code(language="python", lines=18, interactive=True, label="file 2")
189
+ with gr.Tab("file 3") as python_tab_4_3:
190
+ python_code_4_3 = gr.Code(language="python", lines=18, interactive=True, label="file 3")
191
+ with gr.Tab("file 4") as python_tab_4_4:
192
+ python_code_4_4 = gr.Code(language="python", lines=18, interactive=True, label="file 4")
193
+
194
+ with gr.Group(visible=False) as python_group_5plus:
195
+ with gr.Tabs():
196
+ with gr.Tab("app.py") as python_tab_5_1:
197
+ python_code_5_1 = gr.Code(language="python", lines=20, interactive=True, label="app.py")
198
+ with gr.Tab("file 2") as python_tab_5_2:
199
+ python_code_5_2 = gr.Code(language="python", lines=18, interactive=True, label="file 2")
200
+ with gr.Tab("file 3") as python_tab_5_3:
201
+ python_code_5_3 = gr.Code(language="python", lines=18, interactive=True, label="file 3")
202
+ with gr.Tab("file 4") as python_tab_5_4:
203
+ python_code_5_4 = gr.Code(language="python", lines=18, interactive=True, label="file 4")
204
+ with gr.Tab("file 5") as python_tab_5_5:
205
+ python_code_5_5 = gr.Code(language="python", lines=18, interactive=True, label="file 5")
206
+
207
+ # Static HTML multi-file editors (hidden by default). Use separate tab groups for different file counts.
208
+ with gr.Group(visible=False) as static_group_2:
209
+ with gr.Tabs():
210
+ with gr.Tab("index.html") as static_tab_2_1:
211
+ static_code_2_1 = gr.Code(language="html", lines=20, interactive=True, label="index.html")
212
+ with gr.Tab("file 2") as static_tab_2_2:
213
+ static_code_2_2 = gr.Code(language="html", lines=18, interactive=True, label="file 2")
214
+
215
+ with gr.Group(visible=False) as static_group_3:
216
+ with gr.Tabs():
217
+ with gr.Tab("index.html") as static_tab_3_1:
218
+ static_code_3_1 = gr.Code(language="html", lines=20, interactive=True, label="index.html")
219
+ with gr.Tab("file 2") as static_tab_3_2:
220
+ static_code_3_2 = gr.Code(language="html", lines=18, interactive=True, label="file 2")
221
+ with gr.Tab("file 3") as static_tab_3_3:
222
+ static_code_3_3 = gr.Code(language="html", lines=18, interactive=True, label="file 3")
223
+
224
+ with gr.Group(visible=False) as static_group_4:
225
+ with gr.Tabs():
226
+ with gr.Tab("index.html") as static_tab_4_1:
227
+ static_code_4_1 = gr.Code(language="html", lines=20, interactive=True, label="index.html")
228
+ with gr.Tab("file 2") as static_tab_4_2:
229
+ static_code_4_2 = gr.Code(language="html", lines=18, interactive=True, label="file 2")
230
+ with gr.Tab("file 3") as static_tab_4_3:
231
+ static_code_4_3 = gr.Code(language="html", lines=18, interactive=True, label="file 3")
232
+ with gr.Tab("file 4") as static_tab_4_4:
233
+ static_code_4_4 = gr.Code(language="html", lines=18, interactive=True, label="file 4")
234
+
235
+ with gr.Group(visible=False) as static_group_5plus:
236
+ with gr.Tabs():
237
+ with gr.Tab("index.html") as static_tab_5_1:
238
+ static_code_5_1 = gr.Code(language="html", lines=20, interactive=True, label="index.html")
239
+ with gr.Tab("file 2") as static_tab_5_2:
240
+ static_code_5_2 = gr.Code(language="html", lines=18, interactive=True, label="file 2")
241
+ with gr.Tab("file 3") as static_tab_5_3:
242
+ static_code_5_3 = gr.Code(language="html", lines=18, interactive=True, label="file 3")
243
+ with gr.Tab("file 4") as static_tab_5_4:
244
+ static_code_5_4 = gr.Code(language="html", lines=18, interactive=True, label="file 4")
245
+ with gr.Tab("file 5") as static_tab_5_5:
246
+ static_code_5_5 = gr.Code(language="html", lines=18, interactive=True, label="file 5")
247
+ # React Next.js multi-file editors (hidden by default)
248
+ with gr.Group(visible=False) as react_group:
249
+ with gr.Tabs():
250
+ with gr.Tab("Dockerfile"):
251
+ react_code_dockerfile = gr.Code(language="dockerfile", lines=15, interactive=True, label="Dockerfile")
252
+ with gr.Tab("package.json"):
253
+ react_code_package_json = gr.Code(language="json", lines=20, interactive=True, label="package.json")
254
+ with gr.Tab("next.config.js"):
255
+ react_code_next_config = gr.Code(language="javascript", lines=15, interactive=True, label="next.config.js")
256
+ with gr.Tab("postcss.config.js"):
257
+ react_code_postcss_config = gr.Code(language="javascript", lines=10, interactive=True, label="postcss.config.js")
258
+ with gr.Tab("tailwind.config.js"):
259
+ react_code_tailwind_config = gr.Code(language="javascript", lines=15, interactive=True, label="tailwind.config.js")
260
+ with gr.Tab("pages/_app.js"):
261
+ react_code_pages_app = gr.Code(language="javascript", lines=15, interactive=True, label="pages/_app.js")
262
+ with gr.Tab("pages/index.js"):
263
+ react_code_pages_index = gr.Code(language="javascript", lines=20, interactive=True, label="pages/index.js")
264
+ with gr.Tab("components/ChatApp.jsx"):
265
+ react_code_components = gr.Code(language="javascript", lines=25, interactive=True, label="components/ChatApp.jsx")
266
+ with gr.Tab("styles/globals.css"):
267
+ react_code_styles = gr.Code(language="css", lines=20, interactive=True, label="styles/globals.css")
268
+
269
+ # Removed Import Logs tab for cleaner UI
270
+ # History tab hidden per user request
271
+ # with gr.Tab("History"):
272
+ # history_output = gr.Chatbot(show_label=False, height=400, type="messages")
273
+
274
+ # Keep history_output as hidden component to maintain functionality
275
+ history_output = gr.Chatbot(show_label=False, height=400, type="messages", visible=False)
276
+
277
+ # Global generation status view (disabled placeholder)
278
+ generating_status = gr.Markdown("", visible=False)
279
+
280
+ # Unified import handler
281
+ def handle_import_project(url):
282
+ if not url.strip():
283
+ return [
284
+ gr.update(value="Please enter a URL.", visible=True),
285
+ gr.update(),
286
+ gr.update(),
287
+ [],
288
+ [],
289
+ gr.update(value="Publish", visible=False),
290
+ gr.update(), # keep import header as-is
291
+ gr.update(), # keep import button as-is
292
+ gr.update() # language dropdown - no change
293
+ ]
294
+
295
+ kind, meta = _parse_repo_or_model_url(url)
296
+ if kind == "hf_space":
297
+ status, code = load_project_from_url(url)
298
+ # Extract space info for deployment
299
+ is_valid, username, project_name = check_hf_space_url(url)
300
+ space_name = f"{username}/{project_name}" if is_valid else ""
301
+ loaded_history = [[f"Imported Space from {url}", code]]
302
+
303
+ # Determine the correct language/framework based on the imported content
304
+ code_lang = "html" # default
305
+ framework_type = "html" # for language dropdown
306
+
307
+ # Check imports to determine framework for Python code
308
+ if is_streamlit_code(code):
309
+ code_lang = "python"
310
+ framework_type = "streamlit"
311
+ elif is_gradio_code(code):
312
+ code_lang = "python"
313
+ framework_type = "gradio"
314
+ elif "=== index.html ===" in code and "=== index.js ===" in code and "=== style.css ===" in code:
315
+ # This is a transformers.js app with the combined format
316
+ code_lang = "html" # Use html for code display
317
+ framework_type = "transformers.js" # But set dropdown to transformers.js
318
+ elif ("import " in code or "def " in code) and not ("<!DOCTYPE html>" in code or "<html" in code):
319
+ # This looks like Python code but doesn't match Streamlit/Gradio patterns
320
+ # Default to Gradio for Python spaces
321
+ code_lang = "python"
322
+ framework_type = "gradio"
323
+
324
+ # Return the updates with proper language settings
325
+ return [
326
+ gr.update(value=status, visible=True),
327
+ gr.update(value=code, language=code_lang), # Use html for transformers.js display
328
+ gr.update(value="", visible=False), # hide import textbox after submit
329
+ loaded_history,
330
+ history_to_chatbot_messages(loaded_history),
331
+ gr.update(value="Publish", visible=True),
332
+ gr.update(visible=False), # hide import header
333
+ gr.update(visible=False), # hide import button
334
+ gr.update(value=framework_type) # set language dropdown to framework type
335
+ ]
336
+ else:
337
+ # GitHub or HF model β†’ return raw snippet for LLM starting point
338
+ status, code, _ = import_repo_to_app(url)
339
+ loaded_history = [[f"Imported Repo/Model from {url}", code]]
340
+ code_lang = "python"
341
+ framework_type = "gradio" # Default to gradio for Python code
342
+ lower = (code or "").lower()
343
+ if code.strip().startswith("<!doctype html>") or code.strip().startswith("<html"):
344
+ code_lang = "html"
345
+ framework_type = "html"
346
+ elif "```json" in lower:
347
+ code_lang = "json"
348
+ framework_type = "json"
349
+ return [
350
+ gr.update(value=status, visible=True),
351
+ gr.update(value=code, language=code_lang),
352
+ gr.update(value="", visible=False), # hide import textbox after submit
353
+ loaded_history,
354
+ history_to_chatbot_messages(loaded_history),
355
+ gr.update(value="Publish", visible=False),
356
+ gr.update(visible=False), # hide import header
357
+ gr.update(visible=False), # hide import button
358
+ gr.update(value=framework_type) # set language dropdown to detected language
359
+ ]
360
+
361
+ # Import repo/model handler
362
+ def handle_import_repo(url, framework):
363
+ status, code, preview = import_repo_to_app(url, framework)
364
+ # Heuristically set editor language based on snippet fencing or content
365
+ code_lang = "python"
366
+ lowered = (code or "").lower()
367
+ if code.strip().startswith("<!doctype html>") or code.strip().startswith("<html"):
368
+ code_lang = "html"
369
+ elif "import gradio" in lowered or "from gradio" in lowered:
370
+ code_lang = "python"
371
+ elif "streamlit as st" in lowered or "import streamlit" in lowered:
372
+ code_lang = "python"
373
+ elif "from transformers" in lowered or "import transformers" in lowered:
374
+ code_lang = "python"
375
+ elif "from diffusers" in lowered or "import diffusers" in lowered:
376
+ code_lang = "python"
377
+ return [
378
+ gr.update(value=status, visible=True),
379
+ gr.update(value=code, language=code_lang),
380
+ gr.update(value=""),
381
+ gr.update(value=f"URL: {url}\n\n{status}"),
382
+ ]
383
+
384
+ # Event handlers
385
+ def update_code_language(language):
386
+ return gr.update(language=get_gradio_language(language))
387
+
388
+
389
+ language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)
390
+
391
+ # Toggle single vs multi-file editors for transformers.js and populate when switching
392
+ def toggle_editors(language, code_text):
393
+ if language == "transformers.js":
394
+ files = parse_transformers_js_output(code_text or "")
395
+ # Hide multi-file editors until all files exist; show single code until then
396
+ editors_visible = True if (files.get('index.html') and files.get('index.js') and files.get('style.css')) else False
397
+ return [
398
+ gr.update(visible=not editors_visible), # code_output shown if editors hidden
399
+ gr.update(visible=editors_visible), # tjs_group shown only when complete
400
+ gr.update(value=files.get('index.html', '')),
401
+ gr.update(value=files.get('index.js', '')),
402
+ gr.update(value=files.get('style.css', '')),
403
+ # React group hidden
404
+ gr.update(visible=False),
405
+ gr.update(),
406
+ gr.update(),
407
+ gr.update(),
408
+ gr.update(),
409
+ gr.update(),
410
+ gr.update(),
411
+ gr.update(),
412
+ gr.update(),
413
+ gr.update(),
414
+ ]
415
+ elif language == "react":
416
+ files = parse_react_output(code_text or "")
417
+ # Show react group if we have files, else show single code editor
418
+ editors_visible = True if files else False
419
+ if editors_visible:
420
+ return [
421
+ gr.update(visible=False), # code_output hidden
422
+ gr.update(visible=False), # tjs_group hidden
423
+ gr.update(),
424
+ gr.update(),
425
+ gr.update(),
426
+ # React group shown
427
+ gr.update(visible=editors_visible), # react_group shown
428
+ gr.update(value=files.get('Dockerfile', '')),
429
+ gr.update(value=files.get('package.json', '')),
430
+ gr.update(value=files.get('next.config.js', '')),
431
+ gr.update(value=files.get('postcss.config.js', '')),
432
+ gr.update(value=files.get('tailwind.config.js', '')),
433
+ gr.update(value=files.get('pages/_app.js', '')),
434
+ gr.update(value=files.get('pages/index.js', '')),
435
+ gr.update(value=files.get('components/ChatApp.jsx', '')),
436
+ gr.update(value=files.get('styles/globals.css', '')),
437
+ ]
438
+ else:
439
+ return [
440
+ gr.update(visible=True), # code_output shown
441
+ gr.update(visible=False), # tjs_group hidden
442
+ gr.update(),
443
+ gr.update(),
444
+ gr.update(),
445
+ # React group hidden
446
+ gr.update(visible=False),
447
+ gr.update(),
448
+ gr.update(),
449
+ gr.update(),
450
+ gr.update(),
451
+ gr.update(),
452
+ gr.update(),
453
+ gr.update(),
454
+ gr.update(),
455
+ gr.update(),
456
+ ]
457
+ else:
458
+ return [
459
+ gr.update(visible=True), # code_output shown
460
+ gr.update(visible=False), # tjs_group hidden
461
+ gr.update(),
462
+ gr.update(),
463
+ gr.update(),
464
+ # React group hidden
465
+ gr.update(visible=False),
466
+ gr.update(),
467
+ gr.update(),
468
+ gr.update(),
469
+ gr.update(),
470
+ gr.update(),
471
+ gr.update(),
472
+ gr.update(),
473
+ gr.update(),
474
+ gr.update(),
475
+ ]
476
+
477
+ language_dropdown.change(
478
+ toggle_editors,
479
+ inputs=[language_dropdown, code_output],
480
+ outputs=[code_output, tjs_group, tjs_html_code, tjs_js_code, tjs_css_code, react_group, react_code_dockerfile, react_code_package_json, react_code_next_config, react_code_postcss_config, react_code_tailwind_config, react_code_pages_app, react_code_pages_index, react_code_components, react_code_styles],
481
+ )
482
+ # Toggle Python multi-file editors for Gradio/Streamlit
483
+ def toggle_python_editors(language, code_text):
484
+ if language not in ["gradio", "streamlit"]:
485
+ return [
486
+ gr.update(visible=True), # code_output
487
+ gr.update(visible=False), # python_group_2
488
+ gr.update(visible=False), # python_group_3
489
+ gr.update(visible=False), # python_group_4
490
+ gr.update(visible=False), # python_group_5plus
491
+ # All tab and code components get empty updates
492
+ gr.update(), gr.update(), gr.update(), gr.update(), # 2-file group
493
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 3-file group
494
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 4-file group
495
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() # 5-file group
496
+ ]
497
+
498
+ files = parse_multi_file_python_output(code_text or "")
499
+
500
+ if not isinstance(files, dict) or len(files) <= 1:
501
+ # No multi-file content; keep single editor
502
+ return [
503
+ gr.update(visible=True), # code_output
504
+ gr.update(visible=False), # python_group_2
505
+ gr.update(visible=False), # python_group_3
506
+ gr.update(visible=False), # python_group_4
507
+ gr.update(visible=False), # python_group_5plus
508
+ # All tab and code components get empty updates
509
+ gr.update(), gr.update(), gr.update(), gr.update(), # 2-file group
510
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 3-file group
511
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 4-file group
512
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() # 5-file group
513
+ ]
514
+
515
+ # We have multi-file Python output: hide single editor, show appropriate group
516
+ # Order: main app first, then others sorted by name
517
+ ordered_paths = []
518
+ main_files = ['app.py', 'streamlit_app.py', 'main.py']
519
+ for main_file in main_files:
520
+ if main_file in files:
521
+ ordered_paths.append(main_file)
522
+ break
523
+
524
+ for p in sorted(files.keys()):
525
+ if p not in ordered_paths:
526
+ ordered_paths.append(p)
527
+
528
+ num_files = len(ordered_paths)
529
+
530
+ # Hide single editor, show appropriate group based on file count
531
+ updates = [gr.update(visible=False)] # code_output
532
+
533
+ if num_files == 2:
534
+ updates.extend([
535
+ gr.update(visible=True), # python_group_2
536
+ gr.update(visible=False), # python_group_3
537
+ gr.update(visible=False), # python_group_4
538
+ gr.update(visible=False), # python_group_5plus
539
+ ])
540
+ # Populate 2-file group
541
+ path1, path2 = ordered_paths[0], ordered_paths[1]
542
+ updates.extend([
543
+ gr.update(label=path1), gr.update(value=files.get(path1, ''), label=path1, language="python"),
544
+ gr.update(label=path2), gr.update(value=files.get(path2, ''), label=path2, language="python"),
545
+ # Empty updates for unused groups
546
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
547
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
548
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
549
+ ])
550
+ elif num_files == 3:
551
+ updates.extend([
552
+ gr.update(visible=False), # python_group_2
553
+ gr.update(visible=True), # python_group_3
554
+ gr.update(visible=False), # python_group_4
555
+ gr.update(visible=False), # python_group_5plus
556
+ ])
557
+ # Populate 3-file group
558
+ path1, path2, path3 = ordered_paths[0], ordered_paths[1], ordered_paths[2]
559
+ updates.extend([
560
+ # Empty updates for 2-file group
561
+ gr.update(), gr.update(), gr.update(), gr.update(),
562
+ # Populate 3-file group
563
+ gr.update(label=path1), gr.update(value=files.get(path1, ''), label=path1, language="python"),
564
+ gr.update(label=path2), gr.update(value=files.get(path2, ''), label=path2, language="python"),
565
+ gr.update(label=path3), gr.update(value=files.get(path3, ''), label=path3, language="python"),
566
+ # Empty updates for unused groups
567
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
568
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
569
+ ])
570
+ elif num_files == 4:
571
+ updates.extend([
572
+ gr.update(visible=False), # python_group_2
573
+ gr.update(visible=False), # python_group_3
574
+ gr.update(visible=True), # python_group_4
575
+ gr.update(visible=False), # python_group_5plus
576
+ ])
577
+ # Populate 4-file group
578
+ paths = ordered_paths[:4]
579
+ updates.extend([
580
+ # Empty updates for 2-file and 3-file groups
581
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
582
+ # Populate 4-file group
583
+ gr.update(label=paths[0]), gr.update(value=files.get(paths[0], ''), label=paths[0], language="python"),
584
+ gr.update(label=paths[1]), gr.update(value=files.get(paths[1], ''), label=paths[1], language="python"),
585
+ gr.update(label=paths[2]), gr.update(value=files.get(paths[2], ''), label=paths[2], language="python"),
586
+ gr.update(label=paths[3]), gr.update(value=files.get(paths[3], ''), label=paths[3], language="python"),
587
+ # Empty updates for 5-file group
588
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
589
+ ])
590
+ else: # 5+ files
591
+ updates.extend([
592
+ gr.update(visible=False), # python_group_2
593
+ gr.update(visible=False), # python_group_3
594
+ gr.update(visible=False), # python_group_4
595
+ gr.update(visible=True), # python_group_5plus
596
+ ])
597
+ # Populate 5-file group (show first 5 files)
598
+ paths = ordered_paths[:5]
599
+ updates.extend([
600
+ # Empty updates for 2-file, 3-file, and 4-file groups
601
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
602
+ # Populate 5-file group
603
+ gr.update(label=paths[0]), gr.update(value=files.get(paths[0], ''), label=paths[0], language="python"),
604
+ gr.update(label=paths[1]), gr.update(value=files.get(paths[1], ''), label=paths[1], language="python"),
605
+ gr.update(label=paths[2]), gr.update(value=files.get(paths[2], ''), label=paths[2], language="python"),
606
+ gr.update(label=paths[3]), gr.update(value=files.get(paths[3], ''), label=paths[3], language="python"),
607
+ gr.update(label=paths[4]), gr.update(value=files.get(paths[4], ''), label=paths[4], language="python"),
608
+ ])
609
+
610
+ return updates
611
+
612
+ language_dropdown.change(
613
+ toggle_python_editors,
614
+ inputs=[language_dropdown, code_output],
615
+ outputs=[
616
+ code_output, python_group_2, python_group_3, python_group_4, python_group_5plus,
617
+ python_tab_2_1, python_code_2_1, python_tab_2_2, python_code_2_2,
618
+ python_tab_3_1, python_code_3_1, python_tab_3_2, python_code_3_2, python_tab_3_3, python_code_3_3,
619
+ python_tab_4_1, python_code_4_1, python_tab_4_2, python_code_4_2, python_tab_4_3, python_code_4_3, python_tab_4_4, python_code_4_4,
620
+ python_tab_5_1, python_code_5_1, python_tab_5_2, python_code_5_2, python_tab_5_3, python_code_5_3, python_tab_5_4, python_code_5_4, python_tab_5_5, python_code_5_5
621
+ ],
622
+ )
623
+
624
+ # Static HTML multi-file toggling and population
625
+ def toggle_static_editors(language, code_text):
626
+ # If not static HTML language, ensure single editor visible and all static groups hidden
627
+ if language != "html":
628
+ return [
629
+ gr.update(visible=True), # code_output
630
+ gr.update(visible=False), # static_group_2
631
+ gr.update(visible=False), # static_group_3
632
+ gr.update(visible=False), # static_group_4
633
+ gr.update(visible=False), # static_group_5plus
634
+ # All tab and code components get empty updates (tab, code, tab, code, ...)
635
+ gr.update(), gr.update(), gr.update(), gr.update(), # 2-file group
636
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 3-file group
637
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 4-file group
638
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() # 5-file group
639
+ ]
640
+
641
+ # Parse multi-file output first
642
+ original_files = parse_multipage_html_output(code_text or "")
643
+
644
+ # Check if we actually have multi-file content BEFORE validation
645
+ # (validate_and_autofix_files can create additional files from single-file HTML)
646
+ if not isinstance(original_files, dict) or len(original_files) <= 1:
647
+ # No genuine multi-file content; keep single editor
648
+ return [
649
+ gr.update(visible=True), # code_output
650
+ gr.update(visible=False), # static_group_2
651
+ gr.update(visible=False), # static_group_3
652
+ gr.update(visible=False), # static_group_4
653
+ gr.update(visible=False), # static_group_5plus
654
+ # All tab and code components get empty updates (tab, code, tab, code, ...)
655
+ gr.update(), gr.update(), gr.update(), gr.update(), # 2-file group
656
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 3-file group
657
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 4-file group
658
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() # 5-file group
659
+ ]
660
+
661
+ # We have genuine multi-file content - now validate and proceed with multi-file display
662
+ files = validate_and_autofix_files(original_files)
663
+
664
+ # We have multi-file static output: hide single editor, show appropriate static group
665
+ # Order: index.html first, then others sorted by path
666
+ ordered_paths = []
667
+ if 'index.html' in files:
668
+ ordered_paths.append('index.html')
669
+ for p in sorted(files.keys()):
670
+ if p == 'index.html':
671
+ continue
672
+ ordered_paths.append(p)
673
+
674
+ # Map extension to language
675
+ def _lang_for(path: str):
676
+ p = (path or '').lower()
677
+ if p.endswith('.html'):
678
+ return 'html'
679
+ if p.endswith('.css'):
680
+ return 'css'
681
+ if p.endswith('.js'):
682
+ return 'javascript'
683
+ if p.endswith('.json'):
684
+ return 'json'
685
+ if p.endswith('.md') or p.endswith('.markdown'):
686
+ return 'markdown'
687
+ return 'html'
688
+
689
+ num_files = len(ordered_paths)
690
+
691
+ # TEMPORARY FIX: For now, always keep single editor visible for HTML multi-file
692
+ # This ensures code is always visible while we debug the multi-file editors
693
+ # TODO: Remove this once multi-file editors are working properly
694
+ updates = [
695
+ gr.update(visible=True), # code_output - keep visible
696
+ gr.update(visible=False), # static_group_2 - hide multi-file editors for now
697
+ gr.update(visible=False), # static_group_3
698
+ gr.update(visible=False), # static_group_4
699
+ gr.update(visible=False), # static_group_5plus
700
+ ]
701
+
702
+ # Add empty updates for all the tab and code components
703
+ updates.extend([
704
+ # All tab and code components get empty updates (tab, code, tab, code, ...)
705
+ gr.update(), gr.update(), gr.update(), gr.update(), # 2-file group
706
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 3-file group
707
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), # 4-file group
708
+ gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() # 5-file group
709
+ ])
710
+
711
+ return updates
712
+
713
+ # Respond to language change to show/hide static multi-file editors appropriately
714
+ language_dropdown.change(
715
+ toggle_static_editors,
716
+ inputs=[language_dropdown, code_output],
717
+ outputs=[
718
+ code_output,
719
+ static_group_2, static_group_3, static_group_4, static_group_5plus,
720
+ static_tab_2_1, static_code_2_1, static_tab_2_2, static_code_2_2,
721
+ static_tab_3_1, static_code_3_1, static_tab_3_2, static_code_3_2, static_tab_3_3, static_code_3_3,
722
+ static_tab_4_1, static_code_4_1, static_tab_4_2, static_code_4_2, static_tab_4_3, static_code_4_3, static_tab_4_4, static_code_4_4,
723
+ static_tab_5_1, static_code_5_1, static_tab_5_2, static_code_5_2, static_tab_5_3, static_code_5_3, static_tab_5_4, static_code_5_4, static_tab_5_5, static_code_5_5,
724
+ ],
725
+ )
726
+
727
+ def sync_tjs_from_code(code_text, language):
728
+ if language != "transformers.js":
729
+ return [gr.update(), gr.update(), gr.update(), gr.update()]
730
+ files = parse_transformers_js_output(code_text or "")
731
+ # Only reveal the multi-file editors when all three files are present
732
+ editors_visible = True if (files.get('index.html') and files.get('index.js') and files.get('style.css')) else None
733
+ return [
734
+ gr.update(value=files.get('index.html', '')),
735
+ gr.update(value=files.get('index.js', '')),
736
+ gr.update(value=files.get('style.css', '')),
737
+ gr.update(visible=editors_visible) if editors_visible is not None else gr.update(),
738
+ ]
739
+
740
+ # Keep multi-file editors in sync when code_output changes and language is transformers.js
741
+ code_output.change(
742
+ sync_tjs_from_code,
743
+ inputs=[code_output, language_dropdown],
744
+ outputs=[tjs_html_code, tjs_js_code, tjs_css_code, tjs_group],
745
+ )
746
+
747
+ # Preview functions removed - replaced with deployment messaging
748
+ # The following functions are no longer used as preview has been removed:
749
+ # - preview_logic: replaced with deployment messages
750
+ # - preview_from_tjs_editors: replaced with deployment messages
751
+ # - send_to_sandbox: still used in some places but could be removed in future cleanup
752
+
753
+ # Show deployment message for transformers.js editors
754
+ def show_tjs_deployment_message(*args):
755
+ return """
756
+ <div style='padding: 1.5em; text-align: center; background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%); color: white; border-radius: 10px;'>
757
+ <h3 style='margin-top: 0; color: white;'>πŸš€ Transformers.js App Ready!</h3>
758
+ <p style='margin: 0.5em 0; opacity: 0.9;'>Your multi-file Transformers.js application is ready for deployment.</p>
759
+ <p style='margin: 0.5em 0; font-weight: bold;'>πŸ‘‰ Use the Deploy button in the sidebar to publish your app!</p>
760
+ </div>
761
+ """
762
+
763
+
764
+ def show_deploy_components(*args):
765
+ return gr.Button(visible=True)
766
+
767
+ def hide_deploy_components(*args):
768
+ return gr.Button(visible=True)
769
+
770
+ # Show textbox when import button is clicked
771
+ def toggle_import_textbox(url_visible):
772
+ # If textbox is already visible and has content, proceed with import
773
+ # Otherwise, just show the textbox
774
+ return gr.update(visible=True)
775
+
776
+ load_project_btn.click(
777
+ fn=toggle_import_textbox,
778
+ inputs=[load_project_url],
779
+ outputs=[load_project_url]
780
+ ).then(
781
+ handle_import_project,
782
+ inputs=[load_project_url],
783
+ outputs=[
784
+ load_project_status,
785
+ code_output,
786
+ load_project_url,
787
+ history,
788
+ history_output,
789
+ deploy_btn,
790
+ import_header_md,
791
+ load_project_btn,
792
+ language_dropdown,
793
+ ],
794
+ )
795
+
796
+
797
+
798
+
799
+
800
+ def begin_generation_ui():
801
+ # Collapse the sidebar when generation starts; keep status hidden
802
+ return [gr.update(open=False), gr.update(visible=False)]
803
+
804
+ def end_generation_ui():
805
+ # Open sidebar after generation; hide the status
806
+ return [gr.update(open=True), gr.update(visible=False)]
807
+
808
+ def generation_code_wrapper(inp, sett, hist, model, lang, prov, profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None):
809
+ """Wrapper to call generation_code and pass component references"""
810
+ yield from generation_code(inp, sett, hist, model, lang, prov, profile, token, code_output, history_output, history)
811
+
812
+ btn.click(
813
+ begin_generation_ui,
814
+ inputs=None,
815
+ outputs=[sidebar, generating_status],
816
+ show_progress="hidden",
817
+ ).then(
818
+ generation_code_wrapper,
819
+ inputs=[input, setting, history, current_model, language_dropdown, provider_state],
820
+ outputs=[code_output, history, history_output]
821
+ ).then(
822
+ end_generation_ui,
823
+ inputs=None,
824
+ outputs=[sidebar, generating_status]
825
+ ).then(
826
+ # After generation, toggle editors for transformers.js and populate
827
+ toggle_editors,
828
+ inputs=[language_dropdown, code_output],
829
+ outputs=[code_output, tjs_group, tjs_html_code, tjs_js_code, tjs_css_code, react_group, react_code_dockerfile, react_code_package_json, react_code_next_config, react_code_postcss_config, react_code_tailwind_config, react_code_pages_app, react_code_pages_index, react_code_components, react_code_styles]
830
+ ).then(
831
+ # After generation, toggle static multi-file editors for HTML
832
+ toggle_static_editors,
833
+ inputs=[language_dropdown, code_output],
834
+ outputs=[
835
+ code_output,
836
+ static_group_2, static_group_3, static_group_4, static_group_5plus,
837
+ static_tab_2_1, static_code_2_1, static_tab_2_2, static_code_2_2,
838
+ static_tab_3_1, static_code_3_1, static_tab_3_2, static_code_3_2, static_tab_3_3, static_code_3_3,
839
+ static_tab_4_1, static_code_4_1, static_tab_4_2, static_code_4_2, static_tab_4_3, static_code_4_3, static_tab_4_4, static_code_4_4,
840
+ static_tab_5_1, static_code_5_1, static_tab_5_2, static_code_5_2, static_tab_5_3, static_code_5_3, static_tab_5_4, static_code_5_4, static_tab_5_5, static_code_5_5,
841
+ ]
842
+ ).then(
843
+ # After generation, toggle Python multi-file editors for Gradio/Streamlit
844
+ toggle_python_editors,
845
+ inputs=[language_dropdown, code_output],
846
+ outputs=[
847
+ code_output, python_group_2, python_group_3, python_group_4, python_group_5plus,
848
+ python_tab_2_1, python_code_2_1, python_tab_2_2, python_code_2_2,
849
+ python_tab_3_1, python_code_3_1, python_tab_3_2, python_code_3_2, python_tab_3_3, python_code_3_3,
850
+ python_tab_4_1, python_code_4_1, python_tab_4_2, python_code_4_2, python_tab_4_3, python_code_4_3, python_tab_4_4, python_code_4_4,
851
+ python_tab_5_1, python_code_5_1, python_tab_5_2, python_code_5_2, python_tab_5_3, python_code_5_3, python_tab_5_4, python_code_5_4, python_tab_5_5, python_code_5_5
852
+ ]
853
+ ).then(
854
+ show_deploy_components,
855
+ None,
856
+ [deploy_btn]
857
+ )
858
+
859
+ # Pressing Enter in the main input should trigger generation and collapse the sidebar
860
+ input.submit(
861
+ begin_generation_ui,
862
+ inputs=None,
863
+ outputs=[sidebar, generating_status],
864
+ show_progress="hidden",
865
+ ).then(
866
+ generation_code_wrapper,
867
+ inputs=[input, setting, history, current_model, language_dropdown, provider_state],
868
+ outputs=[code_output, history, history_output]
869
+ ).then(
870
+ end_generation_ui,
871
+ inputs=None,
872
+ outputs=[sidebar, generating_status]
873
+ ).then(
874
+ # After generation, toggle editors for transformers.js and populate
875
+ toggle_editors,
876
+ inputs=[language_dropdown, code_output],
877
+ outputs=[code_output, tjs_group, tjs_html_code, tjs_js_code, tjs_css_code, react_group, react_code_dockerfile, react_code_package_json, react_code_next_config, react_code_postcss_config, react_code_tailwind_config, react_code_pages_app, react_code_pages_index, react_code_components, react_code_styles]
878
+ ).then(
879
+ # After generation, toggle static multi-file editors for HTML
880
+ toggle_static_editors,
881
+ inputs=[language_dropdown, code_output],
882
+ outputs=[
883
+ code_output,
884
+ static_group_2, static_group_3, static_group_4, static_group_5plus,
885
+ static_tab_2_1, static_code_2_1, static_tab_2_2, static_code_2_2,
886
+ static_tab_3_1, static_code_3_1, static_tab_3_2, static_code_3_2, static_tab_3_3, static_code_3_3,
887
+ static_tab_4_1, static_code_4_1, static_tab_4_2, static_code_4_2, static_tab_4_3, static_code_4_3, static_tab_4_4, static_code_4_4,
888
+ static_tab_5_1, static_code_5_1, static_tab_5_2, static_code_5_2, static_tab_5_3, static_code_5_3, static_tab_5_4, static_code_5_4, static_tab_5_5, static_code_5_5,
889
+ ]
890
+ ).then(
891
+ # After generation, toggle Python multi-file editors for Gradio/Streamlit
892
+ toggle_python_editors,
893
+ inputs=[language_dropdown, code_output],
894
+ outputs=[
895
+ code_output, python_group_2, python_group_3, python_group_4, python_group_5plus,
896
+ python_tab_2_1, python_code_2_1, python_tab_2_2, python_code_2_2,
897
+ python_tab_3_1, python_code_3_1, python_tab_3_2, python_code_3_2, python_tab_3_3, python_code_3_3,
898
+ python_tab_4_1, python_code_4_1, python_tab_4_2, python_code_4_2, python_tab_4_3, python_code_4_3, python_tab_4_4, python_code_4_4,
899
+ python_tab_5_1, python_code_5_1, python_tab_5_2, python_code_5_2, python_tab_5_3, python_code_5_3, python_tab_5_4, python_code_5_4, python_tab_5_5, python_code_5_5
900
+ ]
901
+ ).then(
902
+ show_deploy_components,
903
+ None,
904
+ [deploy_btn]
905
+ )
906
+
907
+ # --- Chat-based sidebar controller logic ---
908
+ def _find_model_by_name(name: str):
909
+ for m in AVAILABLE_MODELS:
910
+ if m["name"].lower() == name.lower():
911
+ return m
912
+ return None
913
+
914
+ def _extract_url(text: str) -> Optional[str]:
915
+ import re
916
+ match = re.search(r"https?://[^\s]+", text or "")
917
+ return match.group(0) if match else None
918
+
919
+
920
+ # Show deployment message when code or language changes
921
+ def show_deployment_message(code, language, *args):
922
+ if not code or not code.strip():
923
+ return "<div style='padding:1em;color:#888;text-align:center;'>Generate some code to see deployment options.</div>"
924
+ return f"""
925
+ <div style='padding: 1.5em; text-align: center; background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%); color: white; border-radius: 10px;'>
926
+ <h3 style='margin-top: 0; color: white;'>Ready to Deploy!</h3>
927
+ <p style='margin: 0.5em 0; opacity: 0.9;'>Your {language.upper()} code is ready for deployment.</p>
928
+ <p style='margin: 0.5em 0; font-weight: bold;'>πŸ‘‰ Use the Deploy button in the sidebar to publish your app!</p>
929
+ </div>
930
+ """
931
+
932
+ clear_btn.click(clear_history, outputs=[history, history_output])
933
+ clear_btn.click(hide_deploy_components, None, [deploy_btn])
934
+ # Reset button text when clearing
935
+ clear_btn.click(
936
+ lambda: gr.update(value="Publish"),
937
+ outputs=[deploy_btn]
938
+ )
939
+
940
+ # Deploy to Spaces logic
941
+
942
+ def generate_random_app_name():
943
+ """Generate a random app name that's unlikely to clash with existing apps"""
944
+ import random
945
+ import string
946
+
947
+ # Common app prefixes
948
+ prefixes = ["my", "cool", "awesome", "smart", "quick", "super", "mini", "auto", "fast", "easy"]
949
+ # Common app suffixes
950
+ suffixes = ["app", "tool", "hub", "space", "demo", "ai", "gen", "bot", "lab", "studio"]
951
+ # Random adjectives
952
+ adjectives = ["blue", "red", "green", "bright", "dark", "light", "swift", "bold", "clean", "fresh"]
953
+
954
+ # Generate different patterns
955
+ patterns = [
956
+ lambda: f"{random.choice(prefixes)}-{random.choice(suffixes)}-{random.randint(100, 999)}",
957
+ lambda: f"{random.choice(adjectives)}-{random.choice(suffixes)}-{random.randint(10, 99)}",
958
+ lambda: f"{random.choice(prefixes)}-{random.choice(adjectives)}-{random.choice(suffixes)}",
959
+ lambda: f"app-{''.join(random.choices(string.ascii_lowercase, k=6))}-{random.randint(10, 99)}",
960
+ lambda: f"{random.choice(suffixes)}-{''.join(random.choices(string.ascii_lowercase + string.digits, k=8))}"
961
+ ]
962
+
963
+ return random.choice(patterns)()
964
+
965
+ def deploy_with_history_tracking(
966
+ code,
967
+ language,
968
+ history,
969
+ profile: Optional[gr.OAuthProfile] = None,
970
+ token: Optional[gr.OAuthToken] = None
971
+ ):
972
+ """Wrapper function that handles history tracking for deployments"""
973
+ # Check if we have a previously deployed space in the history
974
+ username = profile.username if profile else None
975
+ existing_space = None
976
+
977
+ # Look for previous deployment or imported space in history
978
+ if history and username:
979
+ for user_msg, assistant_msg in history:
980
+ if assistant_msg and "βœ… Deployed!" in assistant_msg:
981
+ import re
982
+ # Look for space URL pattern
983
+ match = re.search(r'huggingface\.co/spaces/([^/\s\)]+/[^/\s\)]+)', assistant_msg)
984
+ if match:
985
+ existing_space = match.group(1)
986
+ break
987
+ elif assistant_msg and "βœ… Updated!" in assistant_msg:
988
+ import re
989
+ # Look for space URL pattern
990
+ match = re.search(r'huggingface\.co/spaces/([^/\s\)]+/[^/\s\)]+)', assistant_msg)
991
+ if match:
992
+ existing_space = match.group(1)
993
+ break
994
+ elif user_msg and user_msg.startswith("Imported Space from"):
995
+ import re
996
+ # Extract space name from import message
997
+ match = re.search(r'huggingface\.co/spaces/([^/\s\)]+/[^/\s\)]+)', user_msg)
998
+ if match:
999
+ imported_space = match.group(1)
1000
+ # Only use imported space if user owns it (can update it)
1001
+ if imported_space.startswith(f"{username}/"):
1002
+ existing_space = imported_space
1003
+ break
1004
+ # If user doesn't own the imported space, we'll create a new one
1005
+ # (existing_space remains None, triggering new deployment)
1006
+
1007
+ # Call the original deploy function
1008
+ status = deploy_to_user_space_original(code, language, existing_space, profile, token)
1009
+
1010
+ # Update history if deployment was successful
1011
+ updated_history = history
1012
+ if isinstance(status, dict) and "value" in status and "βœ…" in status["value"]:
1013
+ action_type = "Deploy" if "Deployed!" in status["value"] else "Update"
1014
+ if existing_space:
1015
+ updated_history = history + [[f"{action_type} {language} app to {existing_space}", status["value"]]]
1016
+ else:
1017
+ updated_history = history + [[f"{action_type} {language} app", status["value"]]]
1018
+
1019
+ return [status, updated_history]
1020
+
1021
+ def deploy_to_user_space_original(
1022
+ code,
1023
+ language,
1024
+ existing_space_name=None, # Pass existing space name if updating
1025
+ profile: Optional[gr.OAuthProfile] = None,
1026
+ token: Optional[gr.OAuthToken] = None
1027
+ ):
1028
+ import shutil
1029
+ if not code or not code.strip():
1030
+ return gr.update(value="No code to deploy.", visible=True)
1031
+ if profile is None or token is None:
1032
+ return gr.update(value="Please log in with your Hugging Face account to deploy to your own Space. Otherwise, use the default deploy (opens in new tab).", visible=True)
1033
+
1034
+ # Check if token has write permissions
1035
+ if not token.token or token.token == "hf_":
1036
+ return gr.update(value="Error: Invalid token. Please log in again with your Hugging Face account to get a valid write token.", visible=True)
1037
+
1038
+ # Determine if this is an update or new deployment
1039
+ username = profile.username
1040
+ if existing_space_name and existing_space_name.startswith(f"{username}/"):
1041
+ # This is an update to existing space
1042
+ repo_id = existing_space_name
1043
+ space_name = existing_space_name.split('/')[-1]
1044
+ is_update = True
1045
+ else:
1046
+ # Generate a random space name for new deployment
1047
+ space_name = generate_random_app_name()
1048
+ repo_id = f"{username}/{space_name}"
1049
+ is_update = False
1050
+ # Map language to HF SDK slug
1051
+ language_to_sdk_map = {
1052
+ "gradio": "gradio",
1053
+ "streamlit": "docker", # Use 'docker' for Streamlit Spaces
1054
+ "react": "docker", # Use 'docker' for React/Next.js Spaces
1055
+ "html": "static",
1056
+ "transformers.js": "static", # Transformers.js uses static SDK
1057
+ "comfyui": "static" # ComfyUI uses static SDK
1058
+ }
1059
+ sdk = language_to_sdk_map.get(language, "gradio")
1060
+
1061
+ # Create API client with user's token for proper authentication
1062
+ api = HfApi(token=token.token)
1063
+ # Only create the repo for new spaces (not updates) and non-Transformers.js, non-Streamlit SDKs
1064
+ if not is_update and sdk != "docker" and language not in ["transformers.js"]:
1065
+ try:
1066
+ api.create_repo(
1067
+ repo_id=repo_id, # e.g. username/space_name
1068
+ repo_type="space",
1069
+ space_sdk=sdk, # Use selected SDK
1070
+ exist_ok=True # Don't error if it already exists
1071
+ )
1072
+ except Exception as e:
1073
+ return gr.update(value=f"Error creating Space: {e}", visible=True)
1074
+ # Streamlit/React/docker logic
1075
+ if sdk == "docker" and language in ["streamlit", "react"]:
1076
+ try:
1077
+ # For new spaces, create a fresh Docker-based space
1078
+ if not is_update:
1079
+ # Use create_repo to create a new Docker space
1080
+ from huggingface_hub import create_repo
1081
+
1082
+ if language == "react":
1083
+ # Create a new React Docker space with docker SDK
1084
+ created_repo = create_repo(
1085
+ repo_id=repo_id,
1086
+ repo_type="space",
1087
+ space_sdk="docker",
1088
+ token=token.token,
1089
+ exist_ok=True
1090
+ )
1091
+ else:
1092
+ # Create a new Streamlit Docker space
1093
+ created_repo = create_repo(
1094
+ repo_id=repo_id,
1095
+ repo_type="space",
1096
+ space_sdk="docker",
1097
+ token=token.token,
1098
+ exist_ok=True
1099
+ )
1100
+
1101
+ # Handle React or Streamlit deployment
1102
+ if language == "react":
1103
+ # Parse React/Next.js files
1104
+ files = parse_react_output(code)
1105
+ if not files:
1106
+ return gr.update(value="Error: Could not parse React output. Please regenerate the code.", visible=True)
1107
+
1108
+ # Upload React files
1109
+ import tempfile
1110
+ import time
1111
+
1112
+ for file_name, file_content in files.items():
1113
+ if not file_content:
1114
+ continue
1115
+
1116
+ success = False
1117
+ last_error = None
1118
+ max_attempts = 3
1119
+
1120
+ for attempt in range(max_attempts):
1121
+ try:
1122
+ with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:
1123
+ f.write(file_content)
1124
+ temp_path = f.name
1125
+
1126
+ api.upload_file(
1127
+ path_or_fileobj=temp_path,
1128
+ path_in_repo=file_name,
1129
+ repo_id=repo_id,
1130
+ repo_type="space"
1131
+ )
1132
+ success = True
1133
+ break
1134
+
1135
+ except Exception as e:
1136
+ last_error = e
1137
+ error_msg = str(e)
1138
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1139
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1140
+
1141
+ if attempt < max_attempts - 1:
1142
+ time.sleep(2)
1143
+ finally:
1144
+ import os
1145
+ if 'temp_path' in locals():
1146
+ os.unlink(temp_path)
1147
+
1148
+ if not success:
1149
+ return gr.update(value=f"Error uploading {file_name}: {last_error}", visible=True)
1150
+
1151
+ # Add anycoder tag and app_port to existing README
1152
+ add_anycoder_tag_to_readme(api, repo_id, app_port=7860)
1153
+
1154
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1155
+ action_text = "Updated" if is_update else "Deployed"
1156
+ return gr.update(value=f"βœ… {action_text}! [Open your React Space here]({space_url})", visible=True)
1157
+
1158
+ # Streamlit logic
1159
+ # Generate requirements.txt for Streamlit apps and upload only if needed
1160
+ import_statements = extract_import_statements(code)
1161
+ requirements_content = generate_requirements_txt_with_llm(import_statements)
1162
+
1163
+ import tempfile
1164
+
1165
+ # Check if we need to upload requirements.txt
1166
+ should_upload_requirements = True
1167
+ if is_update:
1168
+ try:
1169
+ # Try to get existing requirements.txt content
1170
+ existing_requirements = api.hf_hub_download(
1171
+ repo_id=repo_id,
1172
+ filename="requirements.txt",
1173
+ repo_type="space"
1174
+ )
1175
+ with open(existing_requirements, 'r') as f:
1176
+ existing_content = f.read().strip()
1177
+
1178
+ # Compare with new content
1179
+ if existing_content == requirements_content.strip():
1180
+ should_upload_requirements = False
1181
+
1182
+ except Exception:
1183
+ # File doesn't exist or can't be accessed, so we should upload
1184
+ should_upload_requirements = True
1185
+
1186
+ # Upload requirements.txt only if needed
1187
+ if should_upload_requirements:
1188
+ try:
1189
+ with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
1190
+ f.write(requirements_content)
1191
+ requirements_temp_path = f.name
1192
+
1193
+ api.upload_file(
1194
+ path_or_fileobj=requirements_temp_path,
1195
+ path_in_repo="requirements.txt",
1196
+ repo_id=repo_id,
1197
+ repo_type="space"
1198
+ )
1199
+ except Exception as e:
1200
+ error_msg = str(e)
1201
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1202
+ return gr.update(value=f"Error uploading requirements.txt: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1203
+ else:
1204
+ return gr.update(value=f"Error uploading requirements.txt: {e}", visible=True)
1205
+ finally:
1206
+ import os
1207
+ if 'requirements_temp_path' in locals():
1208
+ os.unlink(requirements_temp_path)
1209
+
1210
+ # Add anycoder tag to existing README
1211
+ add_anycoder_tag_to_readme(api, repo_id)
1212
+
1213
+ # Upload the user's code to src/streamlit_app.py (for both new and existing spaces)
1214
+ with tempfile.NamedTemporaryFile("w", suffix=".py", delete=False) as f:
1215
+ f.write(code)
1216
+ temp_path = f.name
1217
+
1218
+ try:
1219
+ api.upload_file(
1220
+ path_or_fileobj=temp_path,
1221
+ path_in_repo="src/streamlit_app.py",
1222
+ repo_id=repo_id,
1223
+ repo_type="space"
1224
+ )
1225
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1226
+ action_text = "Updated" if is_update else "Deployed"
1227
+ return gr.update(value=f"βœ… {action_text}! [Open your Space here]({space_url})", visible=True)
1228
+ except Exception as e:
1229
+ error_msg = str(e)
1230
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1231
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1232
+ else:
1233
+ return gr.update(value=f"Error uploading Streamlit app: {e}", visible=True)
1234
+ finally:
1235
+ import os
1236
+ os.unlink(temp_path)
1237
+
1238
+ except Exception as e:
1239
+ error_prefix = "Error duplicating Streamlit space" if not is_update else "Error updating Streamlit space"
1240
+ return gr.update(value=f"{error_prefix}: {e}", visible=True)
1241
+ # Transformers.js logic
1242
+ elif language == "transformers.js":
1243
+ try:
1244
+ # For new spaces, duplicate the template. For updates, just verify access.
1245
+ if not is_update:
1246
+ # Use duplicate_space to create a transformers.js template space
1247
+ from huggingface_hub import duplicate_space
1248
+
1249
+ # Duplicate the transformers.js template space
1250
+ duplicated_repo = duplicate_space(
1251
+ from_id="static-templates/transformers.js",
1252
+ to_id=space_name.strip(),
1253
+ token=token.token,
1254
+ exist_ok=True
1255
+ )
1256
+ print("Duplicated repo result:", duplicated_repo, type(duplicated_repo))
1257
+ else:
1258
+ # For updates, verify we can access the existing space
1259
+ try:
1260
+ space_info = api.space_info(repo_id)
1261
+ if not space_info:
1262
+ return gr.update(value=f"Error: Could not access space {repo_id} for update.", visible=True)
1263
+ except Exception as e:
1264
+ return gr.update(value=f"Error: Cannot update space {repo_id}. {str(e)}", visible=True)
1265
+ # Parse the code parameter which should contain the formatted transformers.js output
1266
+ files = parse_transformers_js_output(code)
1267
+
1268
+ if not files['index.html'] or not files['index.js'] or not files['style.css']:
1269
+ return gr.update(value="Error: Could not parse transformers.js output. Please regenerate the code.", visible=True)
1270
+
1271
+ # Upload the three files to the space (with retry logic for reliability)
1272
+ import tempfile
1273
+ import time
1274
+
1275
+ # Define files to upload
1276
+ files_to_upload = [
1277
+ ("index.html", files['index.html']),
1278
+ ("index.js", files['index.js']),
1279
+ ("style.css", files['style.css'])
1280
+ ]
1281
+
1282
+ # Upload each file with retry logic (similar to static HTML pattern)
1283
+ max_attempts = 3
1284
+ for file_name, file_content in files_to_upload:
1285
+ success = False
1286
+ last_error = None
1287
+
1288
+ for attempt in range(max_attempts):
1289
+ try:
1290
+ with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:
1291
+ f.write(file_content)
1292
+ temp_path = f.name
1293
+
1294
+ api.upload_file(
1295
+ path_or_fileobj=temp_path,
1296
+ path_in_repo=file_name,
1297
+ repo_id=repo_id,
1298
+ repo_type="space"
1299
+ )
1300
+ success = True
1301
+ break
1302
+
1303
+ except Exception as e:
1304
+ last_error = e
1305
+ error_msg = str(e)
1306
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1307
+ # Permission errors won't be fixed by retrying
1308
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1309
+
1310
+ if attempt < max_attempts - 1: # Not the last attempt
1311
+ time.sleep(2) # Wait before retrying
1312
+ finally:
1313
+ import os
1314
+ if 'temp_path' in locals():
1315
+ os.unlink(temp_path)
1316
+
1317
+ if not success:
1318
+ return gr.update(value=f"Error uploading {file_name}: {last_error}", visible=True)
1319
+
1320
+ # Add anycoder tag to existing README (for both new and update)
1321
+ add_anycoder_tag_to_readme(api, repo_id)
1322
+
1323
+ # For updates, trigger a space restart to ensure changes take effect
1324
+ if is_update:
1325
+ try:
1326
+ api.restart_space(repo_id=repo_id)
1327
+ except Exception as restart_error:
1328
+ # Don't fail the deployment if restart fails, just log it
1329
+ print(f"Note: Could not restart space after update: {restart_error}")
1330
+
1331
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1332
+ action_text = "Updated" if is_update else "Deployed"
1333
+ return gr.update(value=f"βœ… {action_text}! [Open your Transformers.js Space here]({space_url})", visible=True)
1334
+
1335
+ except Exception as e:
1336
+ # Handle potential RepoUrl object errors
1337
+ error_msg = str(e)
1338
+ if "'url'" in error_msg or "RepoUrl" in error_msg:
1339
+ # For RepoUrl object issues, check if the space was actually created successfully
1340
+ try:
1341
+ # Check if space exists by trying to access it
1342
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1343
+ test_api = HfApi(token=token.token)
1344
+ space_exists = test_api.space_info(repo_id)
1345
+
1346
+ if space_exists and not is_update:
1347
+ # Space was created successfully despite the RepoUrl error
1348
+ return gr.update(value=f"βœ… Deployed! Space was created successfully despite a technical error. [Open your Transformers.js Space here]({space_url})", visible=True)
1349
+ elif space_exists and is_update:
1350
+ # Space was updated successfully despite the RepoUrl error
1351
+ return gr.update(value=f"βœ… Updated! Space was updated successfully despite a technical error. [Open your Transformers.js Space here]({space_url})", visible=True)
1352
+ else:
1353
+ # Space doesn't exist, real error
1354
+ return gr.update(value=f"Error: Could not create/update space. Please try again manually at https://huggingface.co/new-space", visible=True)
1355
+ except:
1356
+ # Fallback to informative error with link
1357
+ repo_url = f"https://huggingface.co/spaces/{repo_id}"
1358
+ return gr.update(value=f"Error: Could not properly handle space creation response. Space may have been created successfully. Check: {repo_url}", visible=True)
1359
+
1360
+ # General error handling for both creation and updates
1361
+ action_verb = "updating" if is_update else "duplicating"
1362
+ return gr.update(value=f"Error {action_verb} Transformers.js space: {error_msg}", visible=True)
1363
+ # Other SDKs (existing logic)
1364
+ if sdk == "static":
1365
+ import time
1366
+
1367
+ # Add anycoder tag to existing README (after repo creation)
1368
+ add_anycoder_tag_to_readme(api, repo_id)
1369
+
1370
+ # Detect whether the HTML output is multi-file (=== filename === blocks)
1371
+ files = {}
1372
+ try:
1373
+ files = parse_multipage_html_output(code)
1374
+ files = validate_and_autofix_files(files)
1375
+ except Exception:
1376
+ files = {}
1377
+
1378
+ # If we have multiple files (or at least a parsed index.html), upload the whole folder
1379
+ if isinstance(files, dict) and files.get('index.html'):
1380
+ import tempfile
1381
+ import os
1382
+
1383
+ try:
1384
+ with tempfile.TemporaryDirectory() as tmpdir:
1385
+ # Write each file preserving subdirectories if any
1386
+ for rel_path, content in files.items():
1387
+ safe_rel_path = rel_path.strip().lstrip('/')
1388
+ abs_path = os.path.join(tmpdir, safe_rel_path)
1389
+ os.makedirs(os.path.dirname(abs_path), exist_ok=True)
1390
+ with open(abs_path, 'w') as fh:
1391
+ fh.write(content)
1392
+
1393
+ # Upload the folder in a single commit
1394
+ api.upload_folder(
1395
+ folder_path=tmpdir,
1396
+ repo_id=repo_id,
1397
+ repo_type="space"
1398
+ )
1399
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1400
+ action_text = "Updated" if is_update else "Deployed"
1401
+ return gr.update(value=f"βœ… {action_text}! [Open your Space here]({space_url})", visible=True)
1402
+ except Exception as e:
1403
+ error_msg = str(e)
1404
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1405
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1406
+ else:
1407
+ return gr.update(value=f"Error uploading static app folder: {e}", visible=True)
1408
+
1409
+ # Fallback: single-file static HTML (upload index.html only)
1410
+ file_name = "index.html"
1411
+
1412
+ # Special handling for ComfyUI: prettify JSON and wrap in HTML
1413
+ if language == "comfyui":
1414
+ print("[Deploy] Converting ComfyUI JSON to prettified HTML display")
1415
+ code = prettify_comfyui_json_for_html(code)
1416
+
1417
+ max_attempts = 3
1418
+ for attempt in range(max_attempts):
1419
+ import tempfile
1420
+ with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False) as f:
1421
+ f.write(code)
1422
+ temp_path = f.name
1423
+ try:
1424
+ api.upload_file(
1425
+ path_or_fileobj=temp_path,
1426
+ path_in_repo=file_name,
1427
+ repo_id=repo_id,
1428
+ repo_type="space"
1429
+ )
1430
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1431
+ action_text = "Updated" if is_update else "Deployed"
1432
+ return gr.update(value=f"βœ… {action_text}! [Open your Space here]({space_url})", visible=True)
1433
+ except Exception as e:
1434
+ error_msg = str(e)
1435
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1436
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1437
+ elif attempt < max_attempts - 1:
1438
+ time.sleep(2)
1439
+ else:
1440
+ return gr.update(value=f"Error uploading file after {max_attempts} attempts: {e}. Please check your permissions and try again.", visible=True)
1441
+ finally:
1442
+ import os
1443
+ os.unlink(temp_path)
1444
+ else:
1445
+ # Generate requirements.txt for Gradio apps and upload only if needed
1446
+ import_statements = extract_import_statements(code)
1447
+ requirements_content = generate_requirements_txt_with_llm(import_statements)
1448
+
1449
+ import tempfile
1450
+
1451
+ # Check if we need to upload requirements.txt
1452
+ should_upload_requirements = True
1453
+ if is_update:
1454
+ try:
1455
+ # Try to get existing requirements.txt content
1456
+ existing_requirements = api.hf_hub_download(
1457
+ repo_id=repo_id,
1458
+ filename="requirements.txt",
1459
+ repo_type="space"
1460
+ )
1461
+ with open(existing_requirements, 'r') as f:
1462
+ existing_content = f.read().strip()
1463
+
1464
+ # Compare with new content
1465
+ if existing_content == requirements_content.strip():
1466
+ should_upload_requirements = False
1467
+
1468
+ except Exception:
1469
+ # File doesn't exist or can't be accessed, so we should upload
1470
+ should_upload_requirements = True
1471
+
1472
+ # Note: requirements.txt upload is now handled by the multi-file commit logic below
1473
+ # This ensures all files are committed atomically in a single operation
1474
+
1475
+ # Add anycoder tag to existing README
1476
+ add_anycoder_tag_to_readme(api, repo_id)
1477
+
1478
+ # Check if code contains multi-file format
1479
+ if ('=== app.py ===' in code or '=== requirements.txt ===' in code):
1480
+ # Parse multi-file format and upload each file separately
1481
+ files = parse_multi_file_python_output(code)
1482
+ if files:
1483
+ # Ensure requirements.txt is present - auto-generate if missing
1484
+ if 'app.py' in files and 'requirements.txt' not in files:
1485
+ import_statements = extract_import_statements(files['app.py'])
1486
+ requirements_content = generate_requirements_txt_with_llm(import_statements)
1487
+ files['requirements.txt'] = requirements_content
1488
+ try:
1489
+ from huggingface_hub import CommitOperationAdd
1490
+ operations = []
1491
+ temp_files = []
1492
+
1493
+ # Create CommitOperation for each file
1494
+ for filename, content in files.items():
1495
+ # Clean content to ensure no stray backticks are deployed
1496
+ cleaned_content = content
1497
+ if filename.endswith('.txt') or filename.endswith('.py'):
1498
+ # Additional safety: remove any standalone backtick lines
1499
+ lines = cleaned_content.split('\n')
1500
+ clean_lines = []
1501
+ for line in lines:
1502
+ stripped = line.strip()
1503
+ # Skip lines that are just backticks
1504
+ if stripped == '```' or (stripped.startswith('```') and len(stripped) <= 10):
1505
+ continue
1506
+ clean_lines.append(line)
1507
+ cleaned_content = '\n'.join(clean_lines)
1508
+
1509
+ # Create temporary file
1510
+ with tempfile.NamedTemporaryFile("w", suffix=f".{filename.split('.')[-1]}", delete=False) as f:
1511
+ f.write(cleaned_content)
1512
+ temp_path = f.name
1513
+ temp_files.append(temp_path)
1514
+
1515
+ # Add to operations
1516
+ operations.append(CommitOperationAdd(
1517
+ path_in_repo=filename,
1518
+ path_or_fileobj=temp_path
1519
+ ))
1520
+
1521
+ # Commit all files at once
1522
+ api.create_commit(
1523
+ repo_id=repo_id,
1524
+ operations=operations,
1525
+ commit_message=f"{'Update' if is_update else 'Deploy'} Gradio app with multiple files",
1526
+ repo_type="space"
1527
+ )
1528
+
1529
+ # Clean up temp files
1530
+ for temp_path in temp_files:
1531
+ try:
1532
+ os.unlink(temp_path)
1533
+ except Exception:
1534
+ pass
1535
+
1536
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1537
+ action_text = "Updated" if is_update else "Deployed"
1538
+ return gr.update(value=f"βœ… {action_text}! [Open your Space here]({space_url})", visible=True)
1539
+
1540
+ except Exception as e:
1541
+ # Clean up temp files on error
1542
+ for temp_path in temp_files:
1543
+ try:
1544
+ os.unlink(temp_path)
1545
+ except Exception:
1546
+ pass
1547
+
1548
+ error_msg = str(e)
1549
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1550
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1551
+ else:
1552
+ return gr.update(value=f"Error uploading multi-file app: {e}", visible=True)
1553
+ else:
1554
+ # Fallback to single file if parsing failed
1555
+ pass
1556
+
1557
+ # Single file upload (fallback or non-multi-file format)
1558
+ file_name = "app.py"
1559
+ with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f:
1560
+ f.write(code)
1561
+ temp_path = f.name
1562
+ try:
1563
+ api.upload_file(
1564
+ path_or_fileobj=temp_path,
1565
+ path_in_repo=file_name,
1566
+ repo_id=repo_id,
1567
+ repo_type="space"
1568
+ )
1569
+ space_url = f"https://huggingface.co/spaces/{repo_id}"
1570
+ action_text = "Updated" if is_update else "Deployed"
1571
+ return gr.update(value=f"βœ… {action_text}! [Open your Space here]({space_url})", visible=True)
1572
+ except Exception as e:
1573
+ error_msg = str(e)
1574
+ if "403 Forbidden" in error_msg and "write token" in error_msg:
1575
+ return gr.update(value=f"Error: Permission denied. Please ensure you have write access to {repo_id} and your token has the correct permissions.", visible=True)
1576
+ else:
1577
+ return gr.update(value=f"Error uploading file: {e}", visible=True)
1578
+ finally:
1579
+ import os
1580
+ os.unlink(temp_path)
1581
+
1582
+ # Connect the deploy button to the new function
1583
+ def gather_code_for_deploy(code_text, language, html_part, js_part, css_part):
1584
+ # When transformers.js is selected, ensure multi-file editors are used; otherwise, return single code
1585
+ if language == "transformers.js":
1586
+ # Join into a combined display string for auditing; actual deploy reads editor values directly
1587
+ files = {
1588
+ 'index.html': html_part or '',
1589
+ 'index.js': js_part or '',
1590
+ 'style.css': css_part or '',
1591
+ }
1592
+ if files['index.html'] and files['index.js'] and files['style.css']:
1593
+ return format_transformers_js_output(files)
1594
+ return code_text
1595
+ deploy_btn.click(
1596
+ gather_code_for_deploy,
1597
+ inputs=[code_output, language_dropdown, tjs_html_code, tjs_js_code, tjs_css_code],
1598
+ outputs=[code_output],
1599
+ queue=False,
1600
+ ).then(
1601
+ deploy_with_history_tracking,
1602
+ inputs=[code_output, language_dropdown, history],
1603
+ outputs=[deploy_status, history]
1604
+ )
1605
+ # Keep the old deploy method as fallback (if not logged in, user can still use the old method)
1606
+ # Optionally, you can keep the old deploy_btn.click for the default method as a secondary button.
1607
+
1608
+ # Handle authentication state updates
1609
+ # The LoginButton automatically handles OAuth flow and passes profile/token to the function
1610
+ def handle_auth_update(profile: Optional[gr.OAuthProfile] = None, token: Optional[gr.OAuthToken] = None):
1611
+ return update_ui_for_auth_status(profile, token)
1612
+
1613
+ # Update UI when login button is clicked (handles both login and logout)
1614
+ login_button.click(
1615
+ handle_auth_update,
1616
+ inputs=[],
1617
+ outputs=[input, btn],
1618
+ queue=False
1619
+ )
1620
+
1621
+ # Also update UI when the page loads in case user is already authenticated
1622
+ demo.load(
1623
+ handle_auth_update,
1624
+ inputs=[],
1625
+ outputs=[input, btn],
1626
+ queue=False
1627
+ )
1628
+
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
app.py.backup ADDED
The diff for this file is too large to render. See raw diff