mgbam commited on
Commit
1561904
·
verified ·
1 Parent(s): 9cfef05

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1357 -0
app.py ADDED
@@ -0,0 +1,1357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ from http import HTTPStatus
3
+ from typing import Dict, List, Optional, Tuple
4
+ import base64
5
+ import mimetypes
6
+ import PyPDF2
7
+ import docx
8
+ import cv2
9
+ import numpy as np
10
+ from PIL import Image
11
+ import pytesseract
12
+ import requests
13
+ from urllib.parse import urlparse, urljoin
14
+ from bs4 import BeautifulSoup
15
+ import html2text
16
+ import json
17
+ import time
18
+
19
+ import gradio as gr
20
+ from huggingface_hub import InferenceClient
21
+ from tavily import TavilyClient
22
+ import openai
23
+
24
+ # Gradio supported languages for syntax highlighting
25
+ GRADIO_SUPPORTED_LANGUAGES = [
26
+ "python", "c", "cpp", "markdown", "latex", "json", "html", "css", "javascript", "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", None
27
+ ]
28
+
29
+ def get_gradio_language(language):
30
+ return language if language in GRADIO_SUPPORTED_LANGUAGES else None
31
+
32
+ # Search/Replace Constants
33
+ SEARCH_START = "<<<<<<< SEARCH"
34
+ DIVIDER = "======="
35
+ REPLACE_END = ">>>>>>> REPLACE"
36
+
37
+ # Configuration
38
+ 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
39
+ For website redesign tasks:
40
+ - Use the provided original HTML code as the starting point for redesign
41
+ - Preserve all original content, structure, and functionality
42
+ - Keep the same semantic HTML structure but enhance the styling
43
+ - Reuse all original images and their URLs from the HTML code
44
+ - Create a modern, responsive design with improved typography and spacing
45
+ - Use modern CSS frameworks and design patterns
46
+ - Ensure accessibility and mobile responsiveness
47
+ - Maintain the same navigation and user flow
48
+ - Enhance the visual design while keeping the original layout structure
49
+ If an image is provided, analyze it and use the visual information to better understand the user's requirements.
50
+ Always respond with code that can be executed or rendered directly.
51
+ Always output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""
52
+
53
+ 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. Output ONLY the code inside a ```{language} ... ``` code block, and do not include any explanations or extra text. 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."""
54
+
55
+ # System prompt with search capability
56
+ HTML_SYSTEM_PROMPT_WITH_SEARCH = """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
57
+ You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies.
58
+ For website redesign tasks:
59
+ - Use the provided original HTML code as the starting point for redesign
60
+ - Preserve all original content, structure, and functionality
61
+ - Keep the same semantic HTML structure but enhance the styling
62
+ - Reuse all original images and their URLs from the HTML code
63
+ - Use web search to find current design trends and best practices for the specific type of website
64
+ - Create a modern, responsive design with improved typography and spacing
65
+ - Use modern CSS frameworks and design patterns
66
+ - Ensure accessibility and mobile responsiveness
67
+ - Maintain the same navigation and user flow
68
+ - Enhance the visual design while keeping the original layout structure
69
+ If an image is provided, analyze it and use the visual information to better understand the user's requirements.
70
+ Always respond with code that can be executed or rendered directly.
71
+ Always output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text."""
72
+
73
+ GENERIC_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert {language} developer. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies for {language}.
74
+ Write clean, idiomatic, and runnable {language} code for the user's request. If possible, include comments and best practices. Output ONLY the code inside a ```{language} ... ``` code block, and do not include any explanations or extra text. 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."""
75
+
76
+ # Follow-up system prompt for modifying existing HTML files
77
+ FollowUpSystemPrompt = f"""You are an expert web developer modifying an existing HTML file.
78
+ The user wants to apply changes based on their request.
79
+ You MUST output ONLY the changes required using the following SEARCH/REPLACE block format. Do NOT output the entire file.
80
+ Explain the changes briefly *before* the blocks if necessary, but the code changes THEMSELVES MUST be within the blocks.
81
+ Format Rules:
82
+ 1. Start with {SEARCH_START}
83
+ 2. Provide the exact lines from the current code that need to be replaced.
84
+ 3. Use {DIVIDER} to separate the search block from the replacement.
85
+ 4. Provide the new lines that should replace the original lines.
86
+ 5. End with {REPLACE_END}
87
+ 6. You can use multiple SEARCH/REPLACE blocks if changes are needed in different parts of the file.
88
+ 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.
89
+ 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).
90
+ 9. IMPORTANT: The SEARCH block must *exactly* match the current code, including indentation and whitespace.
91
+ Example Modifying Code:
92
+ ```
93
+ Some explanation...
94
+ {SEARCH_START}
95
+ <h1>Old Title</h1>
96
+ {DIVIDER}
97
+ <h1>New Title</h1>
98
+ {REPLACE_END}
99
+ {SEARCH_START}
100
+ </body>
101
+ {DIVIDER}
102
+ <script>console.log("Added script");</script>
103
+ </body>
104
+ {REPLACE_END}
105
+ ```
106
+ Example Deleting Code:
107
+ ```
108
+ Removing the paragraph...
109
+ {SEARCH_START}
110
+ <p>This paragraph will be deleted.</p>
111
+ {DIVIDER}
112
+ {REPLACE_END}
113
+ ```"""
114
+
115
+ # Available models
116
+ AVAILABLE_MODELS = [
117
+ {
118
+ "name": "Moonshot Kimi-K2",
119
+ "id": "moonshotai/Kimi-K2-Instruct",
120
+ "description": "Moonshot AI Kimi-K2-Instruct model for code generation and general tasks",
121
+ "provider": "groq"
122
+ },
123
+ {
124
+ "name": "DeepSeek V3",
125
+ "id": "deepseek-ai/DeepSeek-V3-0324",
126
+ "description": "DeepSeek V3 model for code generation",
127
+ "provider": "huggingface"
128
+ },
129
+ {
130
+ "name": "DeepSeek R1",
131
+ "id": "deepseek-ai/DeepSeek-R1-0528",
132
+ "description": "DeepSeek R1 model for code generation",
133
+ "provider": "huggingface"
134
+ },
135
+ {
136
+ "name": "Gemini 1.5 Pro",
137
+ "id": "gemini-1.5-pro-latest",
138
+ "description": "Google Gemini 1.5 Pro model for code generation and general tasks",
139
+ "provider": "gemini"
140
+ # }, # Commented out to avoid requiring extra setup for all users
141
+ #{
142
+ # "name": "GPT-4o",
143
+ # "id": "gpt-4o",
144
+ # "description": "OpenAI GPT-4o model for code generation and general tasks",
145
+ # "provider": "openai"
146
+ },
147
+ {
148
+ "name": "ERNIE-4.5-VL",
149
+ "id": "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT",
150
+ "description": "ERNIE-4.5-VL model for multimodal code generation with image support"
151
+ },
152
+ {
153
+ # "name": "GPT-4o-mini",
154
+ # "id": "gpt-4o-mini",
155
+ # "description": "OpenAI GPT-4o-mini model for code generation and general tasks",
156
+ # "provider": "openai"
157
+ #}, # Commented out to avoid requiring extra setup for all users
158
+ #{
159
+ # "name": "GPT-3.5-turbo",
160
+ # "id": "gpt-3.5-turbo",
161
+ # "description": "OpenAI GPT-3.5-turbo model for code generation and general tasks",
162
+ # "provider": "openai"
163
+ #}, # Commented out to avoid requiring extra setup for all users
164
+ #{
165
+ "name": "MiniMax M1",
166
+ "id": "MiniMaxAI/MiniMax-M1-80k",
167
+ "description": "MiniMax M1 model for code generation and general tasks",
168
+ "provider": "huggingface"
169
+ },
170
+ {
171
+ "name": "Qwen3-235B-A22B",
172
+ "id": "Qwen/Qwen3-235B-A22B",
173
+ "description": "Qwen3-235B-A22B model for code generation and general tasks",
174
+ "provider": "huggingface"
175
+ },
176
+ {
177
+ "name": "SmolLM3-3B",
178
+ "id": "HuggingFaceTB/SmolLM3-3B",
179
+ "description": "SmolLM3-3B model for code generation and general tasks",
180
+ "provider": "huggingface"
181
+ },
182
+ {
183
+ "name": "GLM-4.1V-9B-Thinking",
184
+ "id": "THUDM/GLM-4.1V-9B-Thinking",
185
+ "description": "GLM-4.1V-9B-Thinking model for multimodal code generation with image support",
186
+ }
187
+ ]
188
+
189
+ DEMO_LIST = [
190
+ {
191
+ "title": "Todo App",
192
+ "description": "Create a simple todo application with add, delete, and mark as complete functionality"
193
+ },
194
+ {
195
+ "title": "Calculator",
196
+ "description": "Build a basic calculator with addition, subtraction, multiplication, and division"
197
+ },
198
+ {
199
+ "title": "Weather Dashboard",
200
+ "description": "Create a weather dashboard that displays current weather information"
201
+ },
202
+ {
203
+ "title": "Chat Interface",
204
+ "description": "Build a chat interface with message history and user input"
205
+ },
206
+ {
207
+ "title": "E-commerce Product Card",
208
+ "description": "Create a product card component for an e-commerce website"
209
+ },
210
+ {
211
+ "title": "Login Form",
212
+ "description": "Build a responsive login form with validation"
213
+ },
214
+ {
215
+ "title": "Dashboard Layout",
216
+ "description": "Create a dashboard layout with sidebar navigation and main content area"
217
+ },
218
+ {
219
+ "title": "Data Table",
220
+ "description": "Build a data table with sorting and filtering capabilities"
221
+ },
222
+ {
223
+ "title": "Image Gallery",
224
+ "description": "Create an image gallery with lightbox functionality and responsive grid layout"
225
+ },
226
+ {
227
+ "title": "UI from Image",
228
+ "description": "Upload an image of a UI design and I'll generate the HTML/CSS code for it"
229
+ },
230
+ {
231
+ "title": "Extract Text from Image",
232
+ "description": "Upload an image containing text and I'll extract and process the text content"
233
+ },
234
+ {
235
+ "title": "Website Redesign",
236
+ "description": "Enter a website URL to extract its content and redesign it with a modern, responsive layout"
237
+ },
238
+ {
239
+ "title": "Modify HTML",
240
+ "description": "After generating HTML, ask me to modify it with specific changes using search/replace format"
241
+ },
242
+ {
243
+ "title": "Search/Replace Example",
244
+ "description": "Generate HTML first, then ask: 'Change the title to My New Title' or 'Add a blue background to the body'"
245
+ }
246
+ ]
247
+
248
+ # HF Inference Client
249
+ HF_TOKEN = os.getenv("HF_TOKEN")
250
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
251
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
252
+
253
+ def get_inference_client(model_id):
254
+ """Return an appropriate client based on model_id and configured provider."""
255
+ model_info = next((m for m in AVAILABLE_MODELS if m["id"] == model_id), None)
256
+ if not model_info:
257
+ raise ValueError(f"Model with id '{model_id}' not found.")
258
+
259
+ provider = model_info.get("provider", "huggingface") # Default to HF
260
+
261
+ if provider == "groq":
262
+ return InferenceClient(
263
+ provider="groq",
264
+ api_key=HF_TOKEN, # Groq uses HF token as well
265
+ bill_to="huggingface" # Assuming billing through HF for Groq
266
+ )
267
+ elif provider == "huggingface":
268
+ return InferenceClient(
269
+ provider="auto", # Use HF's auto provider for other HF models
270
+ api_key=HF_TOKEN,
271
+ bill_to="huggingface"
272
+ )
273
+ elif provider == "openai":
274
+ if not OPENAI_API_KEY:
275
+ raise ValueError("OPENAI_API_KEY environment variable not set.")
276
+ openai.api_key = OPENAI_API_KEY
277
+ return openai
278
+ elif provider == "gemini":
279
+ if not GEMINI_API_KEY:
280
+ raise ValueError("GEMINI_API_KEY environment variable not set.")
281
+ import google.generativeai as genai
282
+ genai.configure(api_key=GEMINI_API_KEY)
283
+ return genai
284
+ else:
285
+ raise ValueError(f"Unsupported provider: {provider}")
286
+
287
+ # Type definitions
288
+ History = List[Tuple[str, str]]
289
+ Messages = List[Dict[str, str]]
290
+
291
+ # Tavily Search Client
292
+ TAVILY_API_KEY = os.getenv('TAVILY_API_KEY')
293
+ tavily_client = None
294
+ if TAVILY_API_KEY:
295
+ try:
296
+ tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
297
+ except Exception as e:
298
+ print(f"Failed to initialize Tavily client: {e}")
299
+ tavily_client = None
300
+
301
+ def history_to_messages(history: History, system: str) -> Messages:
302
+ messages = [{'role': 'system', 'content': system}]
303
+ for h in history:
304
+ # Handle multimodal content in history
305
+ user_content = h[0]
306
+ if isinstance(user_content, list):
307
+ # Extract text from multimodal content
308
+ text_content = ""
309
+ for item in user_content:
310
+ if isinstance(item, dict) and item.get("type") == "text":
311
+ text_content += item.get("text", "")
312
+ user_content = text_content if text_content else str(user_content)
313
+
314
+ messages.append({'role': 'user', 'content': user_content})
315
+ messages.append({'role': 'assistant', 'content': h[1]})
316
+ return messages
317
+
318
+ def messages_to_history(messages: Messages) -> Tuple[str, History]:
319
+ assert messages[0]['role'] == 'system'
320
+ history = []
321
+ for q, r in zip(messages[1::2], messages[2::2]):
322
+ # Extract text content from multimodal messages for history
323
+ user_content = q['content']
324
+ if isinstance(user_content, list):
325
+ text_content = ""
326
+ for item in user_content:
327
+ if isinstance(item, dict) and item.get("type") == "text":
328
+ text_content += item.get("text", "")
329
+ user_content = text_content if text_content else str(user_content)
330
+
331
+ history.append([user_content, r['content']])
332
+ return history
333
+
334
+ def history_to_chatbot_messages(history: History) -> List[Dict[str, str]]:
335
+ """Convert history tuples to chatbot message format"""
336
+ messages = []
337
+ for user_msg, assistant_msg in history:
338
+ # Handle multimodal content
339
+ if isinstance(user_msg, list):
340
+ text_content = ""
341
+ for item in user_msg:
342
+ if isinstance(item, dict) and item.get("type") == "text":
343
+ text_content += item.get("text", "")
344
+ user_msg = text_content if text_content else str(user_msg)
345
+
346
+ messages.append({"role": "user", "content": user_msg})
347
+ messages.append({"role": "assistant", "content": assistant_msg})
348
+ return messages
349
+
350
+ def remove_code_block(text):
351
+ # Try to match code blocks with language markers
352
+ patterns = [
353
+ r'```(?:html|HTML)\n([\s\S]+?)\n```', # Match ```html or ```HTML
354
+ r'```\n([\s\S]+?)\n```', # Match code blocks without language markers
355
+ r'```([\s\S]+?)```' # Match code blocks without line breaks
356
+ ]
357
+ for pattern in patterns:
358
+ match = re.search(pattern, text, re.DOTALL)
359
+ if match:
360
+ extracted = match.group(1).strip()
361
+ return extracted
362
+ # If no code block is found, check if the entire text is HTML
363
+ if text.strip().startswith('<!DOCTYPE html>') or text.strip().startswith('<html') or text.strip().startswith('<'):
364
+ return text.strip()
365
+ return text.strip()
366
+
367
+ def history_render(history: History):
368
+ return gr.update(visible=True), history
369
+
370
+ def clear_history():
371
+ return [], [], None, "" # Empty lists for both tuple format and chatbot messages, None for file, empty string for website URL
372
+
373
+ def update_image_input_visibility(model):
374
+ """Update image input visibility based on selected model"""
375
+ is_ernie_vl = model.get("id") == "baidu/ERNIE-4.5-VL-424B-A47B-Base-PT"
376
+ is_glm_vl = model.get("id") == "THUDM/GLM-4.1V-9B-Thinking"
377
+ return gr.update(visible=is_ernie_vl or is_glm_vl)
378
+
379
+ def process_image_for_model(image):
380
+ """Convert image to base64 for model input"""
381
+ if image is None:
382
+ return None
383
+
384
+ # Convert numpy array to PIL Image if needed
385
+ import io
386
+ import base64
387
+ import numpy as np
388
+ from PIL import Image
389
+
390
+ # Handle numpy array from Gradio
391
+ if isinstance(image, np.ndarray):
392
+ image = Image.fromarray(image)
393
+
394
+ buffer = io.BytesIO()
395
+ image.save(buffer, format='PNG')
396
+ img_str = base64.b64encode(buffer.getvalue()).decode()
397
+ return f"data:image/png;base64,{img_str}"
398
+
399
+ def create_multimodal_message(text, image=None):
400
+ """Create a multimodal message with text and optional image"""
401
+ if image is None:
402
+ return {"role": "user", "content": text}
403
+
404
+ content = [
405
+ {
406
+ "type": "text",
407
+ "text": text
408
+ },
409
+ {
410
+ "type": "image_url",
411
+ "image_url": {
412
+ "url": process_image_for_model(image)
413
+ }
414
+ }
415
+ ]
416
+
417
+ return {"role": "user", "content": content}
418
+
419
+ def apply_search_replace_changes(original_html: str, changes_text: str) -> str:
420
+ """Apply search/replace changes to HTML content"""
421
+ if not changes_text.strip():
422
+ return original_html
423
+
424
+ # Split the changes text into individual search/replace blocks
425
+ blocks = []
426
+ current_block = ""
427
+ lines = changes_text.split('\n')
428
+
429
+ for line in lines:
430
+ if line.strip() == SEARCH_START:
431
+ if current_block.strip():
432
+ blocks.append(current_block.strip())
433
+ current_block = line + '\n'
434
+ elif line.strip() == REPLACE_END:
435
+ current_block += line + '\n'
436
+ blocks.append(current_block.strip())
437
+ current_block = ""
438
+ else:
439
+ current_block += line + '\n'
440
+
441
+ if current_block.strip():
442
+ blocks.append(current_block.strip())
443
+
444
+ modified_html = original_html
445
+
446
+ for block in blocks:
447
+ if not block.strip():
448
+ continue
449
+
450
+ # Parse the search/replace block
451
+ lines = block.split('\n')
452
+ search_lines = []
453
+ replace_lines = []
454
+ in_search = False
455
+ in_replace = False
456
+
457
+ for line in lines:
458
+ if line.strip() == SEARCH_START:
459
+ in_search = True
460
+ in_replace = False
461
+ elif line.strip() == DIVIDER:
462
+ in_search = False
463
+ in_replace = True
464
+ elif line.strip() == REPLACE_END:
465
+ in_replace = False
466
+ elif in_search:
467
+ search_lines.append(line)
468
+ elif in_replace:
469
+ replace_lines.append(line)
470
+
471
+ # Apply the search/replace
472
+ if search_lines:
473
+ search_text = '\n'.join(search_lines).strip()
474
+ replace_text = '\n'.join(replace_lines).strip()
475
+
476
+ if search_text in modified_html:
477
+ modified_html = modified_html.replace(search_text, replace_text)
478
+ else:
479
+ print(f"Warning: Search text not found in HTML: {search_text[:100]}...")
480
+
481
+ return modified_html
482
+
483
+ # Updated for faster Tavily search and closer prompt usage
484
+ # Uses 'advanced' search_depth and auto_parameters=True for speed and relevance
485
+
486
+ def perform_web_search(query: str, max_results: int = 5, include_domains=None, exclude_domains=None) -> str:
487
+ """Perform web search using Tavily with default parameters"""
488
+ if not tavily_client:
489
+ return "Web search is not available. Please set the TAVILY_API_KEY environment variable."
490
+
491
+ try:
492
+ # Use Tavily defaults with advanced search depth for better results
493
+ search_params = {
494
+ "search_depth": "advanced",
495
+ "max_results": min(max(1, max_results), 20)
496
+ }
497
+ if include_domains is not None:
498
+ search_params["include_domains"] = include_domains
499
+ if exclude_domains is not None:
500
+ search_params["exclude_domains"] = exclude_domains
501
+
502
+ response = tavily_client.search(query, **search_params)
503
+
504
+ search_results = []
505
+ for result in response.get('results', []):
506
+ title = result.get('title', 'No title')
507
+ url = result.get('url', 'No URL')
508
+ content = result.get('content', 'No content')
509
+ search_results.append(f"Title: {title}\nURL: {url}\nContent: {content}\n")
510
+
511
+ if search_results:
512
+ return "Web Search Results:\n\n" + "\n---\n".join(search_results)
513
+ else:
514
+ return "No search results found."
515
+
516
+ except Exception as e:
517
+ return f"Search error: {str(e)}"
518
+
519
+ def enhance_query_with_search(query: str, enable_search: bool) -> str:
520
+ """Enhance the query with web search results if search is enabled"""
521
+ if not enable_search or not tavily_client:
522
+ return query
523
+
524
+ # Perform search to get relevant information
525
+ search_results = perform_web_search(query)
526
+
527
+ # Combine original query with search results
528
+ enhanced_query = f"""Original Query: {query}
529
+ {search_results}
530
+ Please use the search results above to help create the requested application with the most up-to-date information and best practices."""
531
+
532
+ return enhanced_query
533
+
534
+ def send_to_sandbox(code):
535
+ # Add a wrapper to inject necessary permissions and ensure full HTML
536
+ wrapped_code = f"""
537
+ <!DOCTYPE html>
538
+ <html>
539
+ <head>
540
+ <meta charset=\"UTF-8\">
541
+ <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
542
+ <script>
543
+ // Safe localStorage polyfill
544
+ const safeStorage = {{
545
+ _data: {{}},
546
+ getItem: function(key) {{ return this._data[key] || null; }},
547
+ setItem: function(key, value) {{ this._data[key] = value; }},
548
+ removeItem: function(key) {{ delete this._data[key]; }},
549
+ clear: function() {{ this._data = {{}}; }}
550
+ }};
551
+ Object.defineProperty(window, 'localStorage', {{
552
+ value: safeStorage,
553
+ writable: false
554
+ }});
555
+ window.onerror = function(message, source, lineno, colno, error) {{
556
+ console.error('Error:', message);
557
+ }};
558
+ </script>
559
+ </head>
560
+ <body>
561
+ {code}
562
+ </body>
563
+ </html>
564
+ """
565
+ encoded_html = base64.b64encode(wrapped_code.encode('utf-8')).decode('utf-8')
566
+ data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
567
+ 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>'
568
+ return iframe
569
+
570
+ def demo_card_click(e: gr.EventData):
571
+ try:
572
+ # Get the index from the event data
573
+ if hasattr(e, '_data') and e._data:
574
+ # Try different ways to get the index
575
+ if 'index' in e._data:
576
+ index = e._data['index']
577
+ elif 'component' in e._data and 'index' in e._data['component']:
578
+ index = e._data['component']['index']
579
+ elif 'target' in e._data and 'index' in e._data['target']:
580
+ index = e._data['target']['index']
581
+ else:
582
+ # If we can't get the index, try to extract it from the card data
583
+ index = 0
584
+ else:
585
+ index = 0
586
+
587
+ # Ensure index is within bounds
588
+ if index >= len(DEMO_LIST):
589
+ index = 0
590
+
591
+ return DEMO_LIST[index]['description']
592
+ except (KeyError, IndexError, AttributeError) as e:
593
+ # Return the first demo description as fallback
594
+ return DEMO_LIST[0]['description']
595
+
596
+ def extract_text_from_image(image_path):
597
+ """Extract text from image using OCR"""
598
+ try:
599
+ # Check if tesseract is available
600
+ try:
601
+ pytesseract.get_tesseract_version()
602
+ except Exception:
603
+ return "Error: Tesseract OCR is not installed. Please install Tesseract to extract text from images. See install_tesseract.md for instructions."
604
+
605
+ # Read image using OpenCV
606
+ image = cv2.imread(image_path)
607
+ if image is None:
608
+ return "Error: Could not read image file"
609
+
610
+ # Convert to RGB (OpenCV uses BGR)
611
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
612
+
613
+ # Preprocess image for better OCR results
614
+ # Convert to grayscale
615
+ gray = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)
616
+
617
+ # Apply thresholding to get binary image
618
+ _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
619
+
620
+ # Extract text using pytesseract
621
+ text = pytesseract.image_to_string(binary, config='--psm 6')
622
+
623
+ return text.strip() if text.strip() else "No text found in image"
624
+
625
+ except Exception as e:
626
+ return f"Error extracting text from image: {e}"
627
+
628
+ def extract_text_from_file(file_path):
629
+ if not file_path:
630
+ return ""
631
+ mime, _ = mimetypes.guess_type(file_path)
632
+ ext = os.path.splitext(file_path)[1].lower()
633
+ try:
634
+ if ext == ".pdf":
635
+ with open(file_path, "rb") as f:
636
+ reader = PyPDF2.PdfReader(f)
637
+ return "\n".join(page.extract_text() or "" for page in reader.pages)
638
+ elif ext in [".txt", ".md"]:
639
+ with open(file_path, "r", encoding="utf-8") as f:
640
+ return f.read()
641
+ elif ext == ".csv":
642
+ with open(file_path, "r", encoding="utf-8") as f:
643
+ return f.read()
644
+ elif ext == ".docx":
645
+ doc = docx.Document(file_path)
646
+ return "\n".join([para.text for para in doc.paragraphs])
647
+ elif ext.lower() in [".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"]:
648
+ return extract_text_from_image(file_path)
649
+ else:
650
+ return ""
651
+ except Exception as e:
652
+ return f"Error extracting text: {e}"
653
+
654
+ def extract_website_content(url: str) -> str:
655
+ """Extract HTML code and content from a website URL"""
656
+ try:
657
+ # Validate URL
658
+ parsed_url = urlparse(url)
659
+ if not parsed_url.scheme:
660
+ url = "https://" + url
661
+ parsed_url = urlparse(url)
662
+
663
+ if not parsed_url.netloc:
664
+ return "Error: Invalid URL provided"
665
+
666
+ # Set comprehensive headers to mimic a real browser request
667
+ headers = {
668
+ 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
669
+ 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
670
+ 'Accept-Language': 'en-US,en;q=0.9',
671
+ 'Accept-Encoding': 'gzip, deflate, br',
672
+ 'DNT': '1',
673
+ 'Connection': 'keep-alive',
674
+ 'Upgrade-Insecure-Requests': '1',
675
+ 'Sec-Fetch-Dest': 'document',
676
+ 'Sec-Fetch-Mode': 'navigate',
677
+ 'Sec-Fetch-Site': 'none',
678
+ 'Sec-Fetch-User': '?1',
679
+ 'Cache-Control': 'max-age=0'
680
+ }
681
+
682
+ # Create a session to maintain cookies and handle redirects
683
+ session = requests.Session()
684
+ session.headers.update(headers)
685
+
686
+ # Make the request with retry logic
687
+ max_retries = 3
688
+ for attempt in range(max_retries):
689
+ try:
690
+ response = session.get(url, timeout=15, allow_redirects=True)
691
+ response.raise_for_status()
692
+ break
693
+ except requests.exceptions.HTTPError as e:
694
+ if e.response.status_code == 403 and attempt < max_retries - 1:
695
+ # Try with different User-Agent on 403
696
+ session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
697
+ continue
698
+ else:
699
+ raise
700
+
701
+ # Get the raw HTML content with proper encoding
702
+ try:
703
+ # Try to get the content with automatic encoding detection
704
+ response.encoding = response.apparent_encoding
705
+ raw_html = response.text
706
+ except:
707
+ # Fallback to UTF-8 if encoding detection fails
708
+ raw_html = response.content.decode('utf-8', errors='ignore')
709
+
710
+ # Debug: Check if we got valid HTML
711
+ if not raw_html.strip().startswith('<!DOCTYPE') and not raw_html.strip().startswith('<html'):
712
+ print(f"Warning: Response doesn't look like HTML. First 200 chars: {raw_html[:200]}")
713
+ print(f"Response headers: {dict(response.headers)}")
714
+ print(f"Response encoding: {response.encoding}")
715
+ print(f"Apparent encoding: {response.apparent_encoding}")
716
+
717
+ # Try alternative approaches
718
+ try:
719
+ raw_html = response.content.decode('latin-1', errors='ignore')
720
+ print("Tried latin-1 decoding")
721
+ except:
722
+ try:
723
+ raw_html = response.content.decode('utf-8', errors='ignore')
724
+ print("Tried UTF-8 decoding")
725
+ except:
726
+ raw_html = response.content.decode('cp1252', errors='ignore')
727
+ print("Tried cp1252 decoding")
728
+
729
+ # Parse HTML content for analysis
730
+ soup = BeautifulSoup(raw_html, 'html.parser')
731
+
732
+ # Check if this is a JavaScript-heavy site
733
+ script_tags = soup.find_all('script')
734
+ if len(script_tags) > 10:
735
+ print(f"Warning: This site has {len(script_tags)} script tags - it may be a JavaScript-heavy site")
736
+ print("The content might be loaded dynamically and not available in the initial HTML")
737
+
738
+ # Extract title
739
+ title = soup.find('title')
740
+ title_text = title.get_text().strip() if title else "No title found"
741
+
742
+ # Extract meta description
743
+ meta_desc = soup.find('meta', attrs={'name': 'description'})
744
+ description = meta_desc.get('content', '') if meta_desc else ""
745
+
746
+ # Extract main content areas for analysis
747
+ content_sections = []
748
+ main_selectors = [
749
+ 'main', 'article', '.content', '.main-content', '.post-content',
750
+ '#content', '#main', '.entry-content', '.post-body'
751
+ ]
752
+
753
+ for selector in main_selectors:
754
+ elements = soup.select(selector)
755
+ for element in elements:
756
+ text = element.get_text().strip()
757
+ if len(text) > 100: # Only include substantial content
758
+ content_sections.append(text)
759
+
760
+ # Extract navigation links for analysis
761
+ nav_links = []
762
+ nav_elements = soup.find_all(['nav', 'header'])
763
+ for nav in nav_elements:
764
+ links = nav.find_all('a')
765
+ for link in links:
766
+ link_text = link.get_text().strip()
767
+ link_href = link.get('href', '')
768
+ if link_text and link_href:
769
+ nav_links.append(f"{link_text}: {link_href}")
770
+
771
+ # Extract and fix image URLs in the HTML
772
+ img_elements = soup.find_all('img')
773
+ for img in img_elements:
774
+ src = img.get('src', '')
775
+ if src:
776
+ # Handle different URL formats
777
+ if src.startswith('//'):
778
+ # Protocol-relative URL
779
+ absolute_src = 'https:' + src
780
+ img['src'] = absolute_src
781
+ elif src.startswith('/'):
782
+ # Root-relative URL
783
+ absolute_src = urljoin(url, src)
784
+ img['src'] = absolute_src
785
+ elif not src.startswith(('http://', 'https://')):
786
+ # Relative URL
787
+ absolute_src = urljoin(url, src)
788
+ img['src'] = absolute_src
789
+ # If it's already absolute, keep it as is
790
+
791
+ # Also check for data-src (lazy loading) and other common attributes
792
+ data_src = img.get('data-src', '')
793
+ if data_src and not src:
794
+ # Use data-src if src is empty
795
+ if data_src.startswith('//'):
796
+ absolute_data_src = 'https:' + data_src
797
+ img['src'] = absolute_data_src
798
+ elif data_src.startswith('/'):
799
+ absolute_data_src = urljoin(url, data_src)
800
+ img['src'] = absolute_data_src
801
+ elif not data_src.startswith(('http://', 'https://')):
802
+ absolute_data_src = urljoin(url, data_src)
803
+ img['src'] = absolute_data_src
804
+ else:
805
+ img['src'] = data_src
806
+
807
+ # Also fix background image URLs in style attributes
808
+ elements_with_style = soup.find_all(attrs={'style': True})
809
+ for element in elements_with_style:
810
+ style_attr = element.get('style', '')
811
+ # Find and replace relative URLs in background-image
812
+ import re
813
+ bg_pattern = r'background-image:\s*url\(["\']?([^"\']+)["\']?\)'
814
+ matches = re.findall(bg_pattern, style_attr, re.IGNORECASE)
815
+ for match in matches:
816
+ if match:
817
+ if match.startswith('//'):
818
+ absolute_bg = 'https:' + match
819
+ style_attr = style_attr.replace(match, absolute_bg)
820
+ elif match.startswith('/'):
821
+ absolute_bg = urljoin(url, match)
822
+ style_attr = style_attr.replace(match, absolute_bg)
823
+ elif not match.startswith(('http://', 'https://')):
824
+ absolute_bg = urljoin(url, match)
825
+ style_attr = style_attr.replace(match, absolute_bg)
826
+ element['style'] = style_attr
827
+
828
+ # Fix background images in <style> tags
829
+ style_elements = soup.find_all('style')
830
+ for style in style_elements:
831
+ if style.string:
832
+ style_content = style.string
833
+ # Find and replace relative URLs in background-image
834
+ bg_pattern = r'background-image:\s*url\(["\']?([^"\']+)["\']?\)'
835
+ matches = re.findall(bg_pattern, style_content, re.IGNORECASE)
836
+ for match in matches:
837
+ if match:
838
+ if match.startswith('//'):
839
+ absolute_bg = 'https:' + match
840
+ style_content = style_content.replace(match, absolute_bg)
841
+ elif match.startswith('/'):
842
+ absolute_bg = urljoin(url, match)
843
+ style_content = style_content.replace(match, absolute_bg)
844
+ elif not match.startswith(('http://', 'https://')):
845
+ absolute_bg = urljoin(url, match)
846
+ style_content = style_content.replace(match, absolute_bg)
847
+ style.string = style_content
848
+
849
+ # Extract images for analysis (after fixing URLs)
850
+ images = []
851
+ img_elements = soup.find_all('img')
852
+ for img in img_elements:
853
+ src = img.get('src', '')
854
+ alt = img.get('alt', '')
855
+ if src:
856
+ images.append({'src': src, 'alt': alt})
857
+
858
+ # Debug: Print some image URLs to see what we're getting
859
+ print(f"Found {len(images)} images:")
860
+ for i, img in enumerate(images[:5]): # Show first 5 images
861
+ print(f" {i+1}. {img['alt'] or 'No alt'} - {img['src']}")
862
+
863
+ # Test a few image URLs to see if they're accessible
864
+ def test_image_url(img_url):
865
+ try:
866
+ test_response = requests.head(img_url, timeout=5, allow_redirects=True)
867
+ return test_response.status_code == 200
868
+ except:
869
+ return False
870
+
871
+ # Test first few images
872
+ working_images = []
873
+ for img in images[:10]: # Test first 10 images
874
+ if test_image_url(img['src']):
875
+ working_images.append(img)
876
+ else:
877
+ print(f" ❌ Broken image: {img['src']}")
878
+
879
+ print(f"Working images: {len(working_images)} out of {len(images)}")
880
+
881
+ # Get the modified HTML with absolute URLs
882
+ modified_html = str(soup)
883
+
884
+ # Clean and format the HTML for better readability
885
+ # Remove unnecessary whitespace and comments
886
+ import re
887
+ cleaned_html = re.sub(r'<!--.*?-->', '', modified_html, flags=re.DOTALL) # Remove HTML comments
888
+ cleaned_html = re.sub(r'\s+', ' ', cleaned_html) # Normalize whitespace
889
+ cleaned_html = re.sub(r'>\s+<', '><', cleaned_html) # Remove whitespace between tags
890
+
891
+ # Limit HTML size to avoid token limits (keep first 15000 chars)
892
+ if len(cleaned_html) > 15000:
893
+ cleaned_html = cleaned_html[:15000] + "\n<!-- ... HTML truncated for length ... -->"
894
+
895
+ # Check if we got any meaningful content
896
+ if not title_text or title_text == "No title found":
897
+ title_text = url.split('/')[-1] or url.split('/')[-2] or "Website"
898
+
899
+ # If we couldn't extract any meaningful content, provide a fallback
900
+ if len(cleaned_html.strip()) < 100:
901
+ website_content = f"""
902
+ WEBSITE REDESIGN - EXTRACTION FAILED
903
+ ====================================
904
+ URL: {url}
905
+ Title: {title_text}
906
+ ERROR: Could not extract meaningful HTML content from this website. This could be due to:
907
+ 1. The website uses heavy JavaScript to load content dynamically
908
+ 2. The website has anti-bot protection
909
+ 3. The website requires authentication
910
+ 4. The website is using advanced compression or encoding
911
+ FALLBACK APPROACH:
912
+ Please create a modern, responsive website design for a {title_text.lower()} website. Since I couldn't extract the original content, you can:
913
+ 1. Create a typical layout for this type of website
914
+ 2. Use placeholder content that would be appropriate
915
+ 3. Include modern design elements and responsive features
916
+ 4. Use a clean, professional design with good typography
917
+ 5. Make it mobile-friendly and accessible
918
+ The website appears to be: {title_text}
919
+ """
920
+ return website_content.strip()
921
+
922
+ # Compile the extracted content with the actual HTML code
923
+ website_content = f"""
924
+ WEBSITE REDESIGN - ORIGINAL HTML CODE
925
+ =====================================
926
+ URL: {url}
927
+ Title: {title_text}
928
+ Description: {description}
929
+ PAGE ANALYSIS:
930
+ - This appears to be a {title_text.lower()} website
931
+ - Contains {len(content_sections)} main content sections
932
+ - Has {len(nav_links)} navigation links
933
+ - Includes {len(images)} images
934
+ IMAGES FOUND (use these exact URLs in your redesign):
935
+ {chr(10).join([f"• {img['alt'] or 'Image'} - {img['src']}" for img in working_images[:20]]) if working_images else "No working images found"}
936
+ ALL IMAGES (including potentially broken ones):
937
+ {chr(10).join([f"• {img['alt'] or 'Image'} - {img['src']}" for img in images[:20]]) if images else "No images found"}
938
+ ORIGINAL HTML CODE (use this as the base for redesign):
939
+ ```html
940
+ {cleaned_html}
941
+ ```
942
+ REDESIGN INSTRUCTIONS:
943
+ Please redesign this website with a modern, responsive layout while:
944
+ 1. Preserving all the original content and structure
945
+ 2. Maintaining the same navigation and functionality
946
+ 3. Using the original images and their URLs (listed above)
947
+ 4. Creating a modern, clean design with improved typography and spacing
948
+ 5. Making it fully responsive for mobile devices
949
+ 6. Using modern CSS frameworks and best practices
950
+ 7. Keeping the same semantic structure but with enhanced styling
951
+ IMPORTANT: All image URLs in the HTML code above have been converted to absolute URLs and are ready to use. Make sure to preserve these exact image URLs in your redesigned version.
952
+ The HTML code above contains the complete original website structure with all images properly linked. Use it as your starting point and create a modernized version.
953
+ """
954
+
955
+ return website_content.strip()
956
+
957
+ except requests.exceptions.HTTPError as e:
958
+ if e.response.status_code == 403:
959
+ return f"Error: Website blocked access (403 Forbidden). This website may have anti-bot protection. Try a different website or provide a description of what you want to build instead."
960
+ elif e.response.status_code == 404:
961
+ return f"Error: Website not found (404). Please check the URL and try again."
962
+ elif e.response.status_code >= 500:
963
+ return f"Error: Website server error ({e.response.status_code}). Please try again later."
964
+ else:
965
+ return f"Error accessing website: HTTP {e.response.status_code} - {str(e)}"
966
+ except requests.exceptions.Timeout:
967
+ return "Error: Request timed out. The website may be slow or unavailable."
968
+ except requests.exceptions.ConnectionError:
969
+ return "Error: Could not connect to the website. Please check your internet connection and the URL."
970
+ except requests.exceptions.RequestException as e:
971
+ return f"Error accessing website: {str(e)}"
972
+ except Exception as e:
973
+ return f"Error extracting website content: {str(e)}"
974
+
975
+ def generation_code(query: Optional[str], image: Optional[gr.Image], file: Optional[str], website_url: Optional[str], _setting: Dict[str, str], _history: Optional[History], _current_model: Dict, enable_search: bool = False, language: str = "html"):
976
+ if query is None:
977
+ query = ''
978
+ if _history is None:
979
+ _history = []
980
+
981
+ # Check if there's existing HTML content in history to determine if this is a modification request
982
+ has_existing_html = False
983
+ if _history:
984
+ # Check the last assistant message for HTML content
985
+ last_assistant_msg = _history[-1][1] if len(_history) > 0 else ""
986
+ if '<!DOCTYPE html>' in last_assistant_msg or '<html' in last_assistant_msg:
987
+ has_existing_html = True
988
+
989
+ # Choose system prompt based on context
990
+ if has_existing_html:
991
+ # Use follow-up prompt for modifying existing HTML
992
+ system_prompt = FollowUpSystemPrompt
993
+ else:
994
+ # Use language-specific prompt
995
+ if language == "html":
996
+ system_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPT
997
+ else:
998
+ system_prompt = GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language) if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)
999
+
1000
+ messages = history_to_messages(_history, system_prompt)
1001
+
1002
+ # Extract file text and append to query if file is present
1003
+ file_text = ""
1004
+ if file:
1005
+ file_text = extract_text_from_file(file)
1006
+ if file_text:
1007
+ file_text = file_text[:5000] # Limit to 5000 chars for prompt size
1008
+ query = f"{query}\n\n[Reference file content below]\n{file_text}"
1009
+
1010
+ # Extract website content and append to query if website URL is present
1011
+ website_text = ""
1012
+ if website_url and website_url.strip():
1013
+ website_text = extract_website_content(website_url.strip())
1014
+ if website_text and not website_text.startswith("Error"):
1015
+ website_text = website_text[:8000] # Limit to 8000 chars for prompt size
1016
+ query = f"{query}\n\n[Website content to redesign below]\n{website_text}"
1017
+ elif website_text.startswith("Error"):
1018
+ # Provide helpful guidance when website extraction fails
1019
+ fallback_guidance = """
1020
+ Since I couldn't extract the website content, please provide additional details about what you'd like to build:
1021
+ 1. What type of website is this? (e.g., e-commerce, blog, portfolio, dashboard)
1022
+ 2. What are the main features you want?
1023
+ 3. What's the target audience?
1024
+ 4. Any specific design preferences? (colors, style, layout)
1025
+ This will help me create a better design for you."""
1026
+ query = f"{query}\n\n[Error extracting website: {website_text}]{fallback_guidance}"
1027
+
1028
+ # Enhance query with search if enabled
1029
+ enhanced_query = enhance_query_with_search(query, enable_search)
1030
+
1031
+ # Use dynamic client based on selected model
1032
+ client = get_inference_client(_current_model["id"])
1033
+
1034
+ if image is not None:
1035
+ messages.append(create_multimodal_message(enhanced_query, image))
1036
+ else:
1037
+ messages.append({'role': 'user', 'content': enhanced_query})
1038
+ try:
1039
+ if _current_model["provider"] == "openai":
1040
+ # Use OpenAI client
1041
+ stream = client.chat.completions.create(
1042
+ model=_current_model["id"],
1043
+ messages=[{"role": m["role"], "content": m["content"]} for m in messages],
1044
+ stream=True,
1045
+ max_tokens=5000,
1046
+ )
1047
+
1048
+ content = ""
1049
+ for chunk in stream:
1050
+ if chunk.choices[0].delta.content:
1051
+ content += chunk.choices[0].delta.content
1052
+ clean_code = remove_code_block(content)
1053
+ if has_existing_html:
1054
+ # ... (rest of the modification logic) ...
1055
+ if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):
1056
+ yield {
1057
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
1058
+ history_output: history_to_chatbot_messages(_history),
1059
+ sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1060
+ }
1061
+ else:
1062
+ last_html = _history[-1][1] if _history else ""
1063
+ modified_html = apply_search_replace_changes(last_html, clean_code)
1064
+ clean_html = remove_code_block(modified_html)
1065
+ yield {
1066
+ code_output: gr.update(value=clean_html, language=get_gradio_language(language)),
1067
+ history_output: history_to_chatbot_messages(_history),
1068
+ sandbox: send_to_sandbox(clean_html) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1069
+ }
1070
+ else:
1071
+ yield {
1072
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
1073
+ history_output: history_to_chatbot_messages(_history),
1074
+ sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1075
+ }
1076
+ elif _current_model["provider"] == "gemini":
1077
+ # Use Gemini client (assumes you've adapted the message format)
1078
+ chat = client.GenerativeModel(_current_model["id"]).start_chat(history=[]) # Assuming it uses history
1079
+ for message in messages[1:]:
1080
+ if message["role"] == "user":
1081
+ chat.send_message(message["content"])
1082
+ elif message["role"] == "assistant":
1083
+ chat.send_message(message["content"])
1084
+
1085
+ response = chat.send_message(messages[-1]["content"], stream=True)
1086
+ content = ""
1087
+ for chunk in response:
1088
+ content += chunk.text
1089
+ clean_code = remove_code_block(content)
1090
+ if has_existing_html:
1091
+ # ... (rest of the modification logic) ...
1092
+ if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):
1093
+ yield {
1094
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
1095
+ history_output: history_to_chatbot_messages(_history),
1096
+ sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1097
+ }
1098
+ else:
1099
+ last_html = _history[-1][1] if _history else ""
1100
+ modified_html = apply_search_replace_changes(last_html, clean_code)
1101
+ clean_html = remove_code_block(modified_html)
1102
+ yield {
1103
+ code_output: gr.update(value=clean_html, language=get_gradio_language(language)),
1104
+ history_output: history_to_chatbot_messages(_history),
1105
+ sandbox: send_to_sandbox(clean_html) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1106
+ }
1107
+ else:
1108
+ yield {
1109
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
1110
+ history_output: history_to_chatbot_messages(_history),
1111
+ sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1112
+ }
1113
+ else:
1114
+ # Use Hugging Face Inference Client (or Groq) for other models
1115
+ completion = client.chat.completions.create(
1116
+ model=_current_model["id"],
1117
+ messages=messages,
1118
+ stream=True,
1119
+ max_tokens=5000
1120
+ )
1121
+
1122
+ content = ""
1123
+ for chunk in completion:
1124
+ if chunk.choices[0].delta.content:
1125
+ content += chunk.choices[0].delta.content
1126
+ clean_code = remove_code_block(content)
1127
+ if has_existing_html:
1128
+ # ... (rest of the modification logic) ...
1129
+ if clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):
1130
+ yield {
1131
+ code_output: gr.update(value=clean_code, language=get_gradio_language(language)),
1132
+ history_output: history_to_chatbot_messages(_history),
1133
+ sandbox: send_to_sandbox(clean_code) if language == "html" else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>",
1134
+ }
1135
+ else:
1136
+ last_html = _history[-1][1] if _history else ""
1137
+ modified_html = apply_search_replace_changes(last_html, clean_code)
1138
+ # Handle response based on whether this is a modification or new generation
1139
+ if has_existing_html:
1140
+ # Fallback: If the model returns a full HTML file, use it directly
1141
+ final_code = remove_code_block(content)
1142
+ if final_code.strip().startswith("<!DOCTYPE html>") or final_code.strip().startswith("<html"):
1143
+ clean_html = final_code
1144
+ else:
1145
+ last_html = _history[-1][1] if _history else ""
1146
+ modified_html = apply_search_replace_changes(last_html, final_code)
1147
+ clean_html = remove_code_block(modified_html)
1148
+ # Update history with the cleaned HTML
1149
+ _history = messages_to_history(messages + [{
1150
+ 'role': 'assistant',
1151
+ 'content': clean_html
1152
+ }])
1153
+ yield {
1154
+ code_output: clean_html,
1155
+ history: _history,
1156
+ sandbox: send_to_sandbox(clean_html),
1157
+ history_output: history_to_chatbot_messages(_history),
1158
+ }
1159
+ else:
1160
+ # Regular generation - use the content as is
1161
+ _history = messages_to_history(messages + [{
1162
+ 'role': 'assistant',
1163
+ 'content': content
1164
+ }])
1165
+ yield {
1166
+ code_output: remove_code_block(content),
1167
+ history: _history,
1168
+ sandbox: send_to_sandbox(remove_code_block(content)),
1169
+ history_output: history_to_chatbot_messages(_history),
1170
+ }
1171
+ except Exception as e:
1172
+ error_message = f"Error: {str(e)}"
1173
+ yield {
1174
+ code_output: error_message,
1175
+ history_output: history_to_chatbot_messages(_history),
1176
+ }
1177
+
1178
+ # Main application
1179
+ with gr.Blocks(
1180
+ theme=gr.themes.Base(
1181
+ primary_hue="blue",
1182
+ secondary_hue="gray",
1183
+ neutral_hue="gray",
1184
+ font=gr.themes.GoogleFont("Inter"),
1185
+ font_mono=gr.themes.GoogleFont("JetBrains Mono"),
1186
+ text_size=gr.themes.sizes.text_md,
1187
+ spacing_size=gr.themes.sizes.spacing_md,
1188
+ radius_size=gr.themes.sizes.radius_md
1189
+ ),
1190
+ title="AnyCoder - AI Code Generator"
1191
+ ) as demo:
1192
+ history = gr.State([])
1193
+ setting = gr.State({
1194
+ "system": HTML_SYSTEM_PROMPT,
1195
+ })
1196
+ current_model = gr.State(AVAILABLE_MODELS[0]) # Moonshot Kimi-K2
1197
+ open_panel = gr.State(None)
1198
+ last_login_state = gr.State(None)
1199
+
1200
+ with gr.Sidebar():
1201
+ # Remove Hugging Face Login Button and login-required message
1202
+ # login_button = gr.LoginButton(
1203
+ # value="Sign in with Hugging Face",
1204
+ # variant="huggingface",
1205
+ # size="lg"
1206
+ # )
1207
+ # login_required_msg = gr.Markdown("**Please sign in with Hugging Face to use the app.**", visible=True)
1208
+ input = gr.Textbox(
1209
+ label="What would you like to build?",
1210
+ placeholder="Describe your application...",
1211
+ lines=3,
1212
+ visible=True # Always visible
1213
+ )
1214
+ # Language dropdown for code generation
1215
+ language_choices = [
1216
+ "python", "c", "cpp", "markdown", "latex", "json", "html", "css", "javascript", "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"
1217
+ ]
1218
+ language_dropdown = gr.Dropdown(
1219
+ choices=language_choices,
1220
+ value="html",
1221
+ label="Code Language",
1222
+ visible=True # Always visible
1223
+ )
1224
+ website_url_input = gr.Textbox(
1225
+ label="Website URL for redesign",
1226
+ placeholder="https://example.com",
1227
+ lines=1,
1228
+ visible=True # Always visible
1229
+ )
1230
+ file_input = gr.File(
1231
+ label="Reference file",
1232
+ file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif", ".gif", ".webp"],
1233
+ visible=True # Always visible
1234
+ )
1235
+ image_input = gr.Image(
1236
+ label="UI design image",
1237
+ visible=False # Hidden by default; shown only for ERNIE-VL or GLM-VL
1238
+ )
1239
+ with gr.Row():
1240
+ btn = gr.Button("Generate", variant="primary", size="lg", scale=2, visible=True) # Always visible
1241
+ clear_btn = gr.Button("Clear", variant="secondary", size="sm", scale=1, visible=True) # Always visible
1242
+ search_toggle = gr.Checkbox(
1243
+ label="🔍 Web search",
1244
+ value=False,
1245
+ visible=True # Always visible
1246
+ )
1247
+ model_dropdown = gr.Dropdown(
1248
+ choices=[model['name'] for model in AVAILABLE_MODELS],
1249
+ value=AVAILABLE_MODELS[0]['name'], # Moonshot Kimi-K2
1250
+ label="Model",
1251
+ visible=True # Always visible
1252
+ )
1253
+ gr.Markdown("**Quick start**", visible=True)
1254
+ with gr.Column(visible=True) as quick_examples_col:
1255
+ for i, demo_item in enumerate(DEMO_LIST[:3]):
1256
+ demo_card = gr.Button(
1257
+ value=demo_item['title'],
1258
+ variant="secondary",
1259
+ size="sm"
1260
+ )
1261
+ demo_card.click(
1262
+ fn=lambda idx=i: gr.update(value=DEMO_LIST[idx]['description']),
1263
+ outputs=input
1264
+ )
1265
+ if not tavily_client:
1266
+ gr.Markdown("⚠️ Web search unavailable", visible=True)
1267
+ else:
1268
+ gr.Markdown("✅ Web search available", visible=True)
1269
+ model_display = gr.Markdown(f"**Model:** {AVAILABLE_MODELS[0]['name']}", visible=True) # Moonshot Kimi-K2
1270
+ def on_model_change(model_name):
1271
+ for m in AVAILABLE_MODELS:
1272
+ if m['name'] == model_name:
1273
+ return m, f"**Model:** {m['name']}", update_image_input_visibility(m)
1274
+ return AVAILABLE_MODELS[0], f"**Model:** {AVAILABLE_MODELS[0]['name']}", update_image_input_visibility(AVAILABLE_MODELS[0]) # Moonshot Kimi-K2 fallback
1275
+ def save_prompt(input):
1276
+ return {setting: {"system": input}}
1277
+ model_dropdown.change(
1278
+ on_model_change,
1279
+ inputs=model_dropdown,
1280
+ outputs=[current_model, model_display, image_input]
1281
+ )
1282
+ with gr.Accordion("Advanced", open=False, visible=True) as advanced_accordion:
1283
+ systemPromptInput = gr.Textbox(
1284
+ value=HTML_SYSTEM_PROMPT,
1285
+ label="System prompt",
1286
+ lines=5
1287
+ )
1288
+ save_prompt_btn = gr.Button("Save", variant="primary", size="sm")
1289
+ save_prompt_btn.click(save_prompt, inputs=systemPromptInput, outputs=setting)
1290
+
1291
+ # Remove login state and timer logic
1292
+ # login_state = gr.State(False)
1293
+ # timer = gr.Timer(1, active=True)
1294
+ # def check_login(label, last_state):
1295
+ # logged_in = label.startswith("Logout (")
1296
+ # # Only update if state changes
1297
+ # if last_state == logged_in:
1298
+ # return [gr.skip()] * 13 # skip updating all outputs
1299
+ # return (
1300
+ # logged_in, # login_state
1301
+ # gr.update(visible=not logged_in), # login_required_msg
1302
+ # gr.update(visible=logged_in), # input
1303
+ # gr.update(visible=logged_in), # website_url_input
1304
+ # gr.update(visible=logged_in), # file_input
1305
+ # gr.update(visible=logged_in), # btn
1306
+ # gr.update(visible=logged_in), # clear_btn
1307
+ # gr.update(visible=logged_in), # search_toggle
1308
+ # gr.update(visible=logged_in), # model_dropdown
1309
+ # gr.update(visible=logged_in), # quick_examples_col
1310
+ # gr.update(visible=logged_in), # advanced_accordion
1311
+ # logged_in, # update last_login_state
1312
+ # gr.update(visible=logged_in), # language_dropdown
1313
+ # )
1314
+ # timer.tick(
1315
+ # fn=check_login,
1316
+ # inputs=[login_button, last_login_state],
1317
+ # outputs=[login_state, login_required_msg, input, website_url_input, file_input, btn, clear_btn, search_toggle, model_dropdown, quick_examples_col, advanced_accordion, last_login_state, language_dropdown]
1318
+ # )
1319
+
1320
+ with gr.Column():
1321
+ with gr.Tabs():
1322
+ with gr.Tab("Code"):
1323
+ code_output = gr.Code(
1324
+ language="html",
1325
+ lines=25,
1326
+ interactive=False,
1327
+ label="Generated code"
1328
+ )
1329
+ with gr.Tab("Preview"):
1330
+ sandbox = gr.HTML(label="Live preview")
1331
+ with gr.Tab("History"):
1332
+ history_output = gr.Chatbot(show_label=False, height=400, type="messages")
1333
+
1334
+ # Event handlers
1335
+ def update_code_language(language):
1336
+ return gr.update(language=get_gradio_language(language))
1337
+
1338
+ language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)
1339
+
1340
+ def preview_logic(code, language):
1341
+ if language == "html":
1342
+ return send_to_sandbox(code)
1343
+ else:
1344
+ return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your code using the download button above.</div>"
1345
+
1346
+ btn.click(
1347
+ generation_code,
1348
+ inputs=[input, image_input, file_input, website_url_input, setting, history, current_model, search_toggle, language_dropdown],
1349
+ outputs=[code_output, history, sandbox, history_output]
1350
+ )
1351
+ # Update preview when code or language changes
1352
+ code_output.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
1353
+ language_dropdown.change(preview_logic, inputs=[code_output, language_dropdown], outputs=sandbox)
1354
+ clear_btn.click(clear_history, outputs=[history, history_output, file_input, website_url_input])
1355
+
1356
+ if __name__ == "__main__":
1357
+ demo.queue(api_open=False, default_concurrency_limit=20).launch(ssr_mode=True, mcp_server=False, show_api=False)