remove svelte and tavily comments
Browse files1511 unmodified lines1512151315141515151615171518143 unmodified lines1662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722755 unmodified lines24782479248024812482248324842485544 unmodified lines303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306311 unmodified lines307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176259 unmodified lines3436343734383439344034413442344334443445438 unmodified lines3884388538863887388838893890116 unmodified lines400740084009401040114012401340145 unmodified lines4020402140224023402440254026402780 unmodified lines410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131311 unmodified lines444344444445444644474448444944504451445244534454445579 unmodified lines4535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945701599 unmodified lines61706171617261736174617561766177997 unmodified lines717571767177717871797180718171827183718471857186718771887189292 unmodified lines7482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175921511 unmodified linesOutput a COMPLETE, STANDALONE HTML document that renders directly in a browser.Hard constraints:- DO NOT use React, ReactDOM, JSX, Babel, Vue, Angular, Svelte, or any SPA framework.- Use ONLY plain HTML, CSS, and vanilla JavaScript.- Allowed external resources: Tailwind CSS CDN, Font Awesome CDN, Google Fonts.- Do NOT escape characters (no \\n, \\t, or escaped quotes). Output raw HTML/JS/CSS.143 unmodified linesIMPORTANT: 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"""SVELTE_SYSTEM_PROMPT = """You are an expert Svelte developer creating a modern Svelte application.**🚨 CRITICAL: DO NOT Generate README.md Files**- NEVER generate README.md files under any circumstances- A template README.md is automatically provided and will be overridden by the deployment system- Generating a README.md will break the deployment processFile selection policy (dynamic, model-decided):- Generate ONLY the files actually needed for the user's request.- MUST include src/App.svelte (entry component) and src/main.ts (entry point).- Usually include src/app.css for global styles.- Add additional files when needed, e.g. src/lib/*.svelte, src/components/*.svelte, src/stores/*.ts, static/* assets, etc.- Other base template files (package.json, vite.config.ts, tsconfig, svelte.config.js, src/vite-env.d.ts) are provided by the template and should NOT be generated unless explicitly requested by the user.CRITICAL: Always generate src/main.ts with correct Svelte 5 syntax:```typescriptimport './app.css'import App from './App.svelte'const app = new App({target: document.getElementById('app')!,})export default app```Do NOT use the old mount syntax: `import { mount } from 'svelte'` - this will cause build errors.Output format (CRITICAL):- Return ONLY a series of file sections, each starting with a filename line:=== src/App.svelte ===...file content...=== src/app.css ===...file content...(repeat for all files you decide to create)- Do NOT wrap files in Markdown code fences.Dependency policy:- If you import any third-party npm packages (e.g., "@gradio/dataframe"), include a package.json at the project root with a "dependencies" section listing them. Keep scripts and devDependencies compatible with the default Svelte + Vite template.Requirements:1. Create a modern, responsive Svelte application based on the user's specific request2. Prefer TypeScript where applicable for better type safety3. Create a clean, professional UI with good user experience4. Make the application fully responsive for mobile devices5. Use modern CSS practices and Svelte best practices6. Include proper error handling and loading states7. Follow accessibility best practices8. Use Svelte's reactive features effectively9. Include proper component structure and organization (only what's needed)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"""REACT_SYSTEM_PROMPT = """You are an expert React and Next.js developer creating a modern Next.js application.**🚨 CRITICAL: DO NOT Generate README.md Files**755 unmodified linesHistory = List[Tuple[str, str]]Messages = List[Dict[str, str]]# Tavily Search Clientdef history_to_messages(history: History, system: str) -> Messages:messages = [{'role': 'system', 'content': system}]for h in history:544 unmodified linesidx = lower.find("<html")return text[idx:] if idx != -1 else textdef parse_svelte_output(text):"""Parse Svelte output to extract individual files.Supports dynamic multi-file using === filename === sections (preferred),and falls back to ```svelte / ```css code blocks for minimal projects."""if not text:return {}# Preferred: multi-file sections (works for any filenames)try:files = parse_multipage_html_output(text) or {}except Exception:files = {}if isinstance(files, dict) and files:return files# Fallback: code fences for minimal two-file outputimport reresults = {}svelte_match = re.search(r"```svelte\s*\n([\s\S]+?)\n```", text, re.IGNORECASE)if svelte_match:results['src/App.svelte'] = svelte_match.group(1).strip()css_match = re.search(r"```css\s*\n([\s\S]+?)\n```", text, re.IGNORECASE)if css_match:results['src/app.css'] = css_match.group(1).strip()return resultsdef parse_react_output(text):"""Parse React/Next.js output to extract individual files.11 unmodified linesreturn files if isinstance(files, dict) and files else {}def format_svelte_output(files):"""Format Svelte files into === filename === sections (generic)."""return format_multipage_output(files)def infer_svelte_dependencies(files: Dict[str, str]) -> Dict[str, str]:"""Infer npm dependencies from Svelte/TS imports across generated files.Returns mapping of package name -> semver (string). Uses conservative defaultswhen versions aren't known. Adds special-cased versions when known."""import re as _redeps: Dict[str, str] = {}import_from = _re.compile(r"import\s+[^;]*?from\s+['\"]([^'\"]+)['\"]", _re.IGNORECASE)bare_import = _re.compile(r"import\s+['\"]([^'\"]+)['\"]", _re.IGNORECASE)def maybe_add(pkg: str):if not pkg or pkg.startswith('.') or pkg.startswith('/') or pkg.startswith('http'):returnif pkg.startswith('svelte'):returnif pkg not in deps:# Default to wildcard; adjust known packages belowdeps[pkg] = "*"for path, content in (files or {}).items():if not isinstance(content, str):continuefor m in import_from.finditer(content):maybe_add(m.group(1))for m in bare_import.finditer(content):maybe_add(m.group(1))# Pin known versions when sensibleif '@gradio/dataframe' in deps:deps['@gradio/dataframe'] = '^0.19.1'return depsdef build_svelte_package_json(existing_json_text: str | None, detected_dependencies: Dict[str, str]) -> str:"""Create or merge a package.json for Svelte spaces.- If existing_json_text is provided, merge detected deps into its dependencies.- Otherwise, start from the template defaults provided by the user and add deps.- Always preserve template scripts and devDependencies."""import json as _json# Template from the user's Svelte space scaffoldtemplate = {"name": "svelte","private": True,"version": "0.0.0","type": "module","scripts": {"dev": "vite","build": "vite build","preview": "vite preview","check": "svelte-check --tsconfig ./tsconfig.app.json && tsc -p tsconfig.node.json"},"devDependencies": {"@sveltejs/vite-plugin-svelte": "^5.0.3","@tsconfig/svelte": "^5.0.4","svelte": "^5.28.1","svelte-check": "^4.1.6","typescript": "~5.8.3","vite": "^6.3.5"}}result = templateif existing_json_text:try:parsed = _json.loads(existing_json_text)# Merge with template as base, keeping template scripts/devDependencies if missing in parsedresult = {**template,**{k: v for k, v in parsed.items() if k not in ("scripts", "devDependencies")},}# If parsed contains its own scripts/devDependencies, prefer parsed to respect user's fileif isinstance(parsed.get("scripts"), dict):result["scripts"] = parsed["scripts"]if isinstance(parsed.get("devDependencies"), dict):result["devDependencies"] = parsed["devDependencies"]except Exception:# Fallback to template if parse failsresult = template# Merge dependenciesexisting_deps = result.get("dependencies", {})if not isinstance(existing_deps, dict):existing_deps = {}merged = {**existing_deps, **(detected_dependencies or {})}if merged:result["dependencies"] = mergedelse:result.pop("dependencies", None)return _json.dumps(result, indent=2, ensure_ascii=False) + "\n"def history_render(history: History):return gr.update(visible=True), history259 unmodified lines# Reformat the modified filesreturn format_transformers_js_output(files)# Updated for faster Tavily search and closer prompt usage# Uses 'advanced' search_depth and auto_parameters=True for speed and relevancedef send_to_sandbox(code):"""Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts."""html_doc = (code or "").strip()438 unmodified lines'=== index.html ===' in last_assistant_msg or'=== index.js ===' in last_assistant_msg or'=== style.css ===' in last_assistant_msg or'=== src/App.svelte ===' in last_assistant_msg or'=== app.py ===' in last_assistant_msg or'=== requirements.txt ===' in last_assistant_msg):has_existing_content = True116 unmodified linessystem_prompt = TransformersJSFollowUpSystemPromptelif language == "gradio":system_prompt = GradioFollowUpSystemPromptelif language == "svelte":system_prompt = FollowUpSystemPrompt # Use generic follow-up for Svelteelif language == "react":system_prompt = REACT_FOLLOW_UP_SYSTEM_PROMPTelse:5 unmodified linessystem_prompt = DYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPTelif language == "transformers.js":system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPTelif language == "svelte":system_prompt = SVELTE_SYSTEM_PROMPTelif language == "react":system_prompt = REACT_SYSTEM_PROMPTelif language == "gradio":80 unmodified lineshistory: _history,history_output: history_to_chatbot_messages(_history),}elif language == "svelte":files = parse_svelte_output(clean_code)if isinstance(files, dict) and files.get('src/App.svelte'):# Note: Media generation (text-to-image, image-to-image, etc.) is not supported for Svelte apps# Only static HTML apps support automatic image/video/audio generationformatted_output = format_svelte_output(files)yield {code_output: formatted_output,history: _history,history_output: history_to_chatbot_messages(_history),}else:yield {code_output: clean_code,history: _history,history_output: history_to_chatbot_messages(_history),}else:if has_existing_content and not (clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html")):last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""311 unmodified linescode_output: gr.update(value=content, language="html"),history_output: history_to_chatbot_messages(_history),}elif language == "svelte":# For Svelte, just show the content as it streams# We'll parse it properly in the final responseyield {code_output: gr.update(value=content, language="html"),history_output: history_to_chatbot_messages(_history),}else:clean_code = remove_code_block(content)if has_existing_content:79 unmodified lineshistory: _history,history_output: history_to_chatbot_messages(_history),}elif language == "svelte":# Handle Svelte outputfiles = parse_svelte_output(content)if isinstance(files, dict) and files.get('src/App.svelte'):# Model returned complete Svelte outputformatted_output = format_svelte_output(files)_history.append([query, formatted_output])yield {code_output: formatted_output,history: _history,history_output: history_to_chatbot_messages(_history),}elif has_existing_content:# Model returned search/replace changes for Svelte - apply themlast_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_content = apply_search_replace_changes(last_content, content)_history.append([query, modified_content])yield {code_output: modified_content,history: _history,history_output: history_to_chatbot_messages(_history),}else:# Fallback if parsing failed - just use the raw content_history.append([query, content])yield {code_output: content,history: _history,history_output: history_to_chatbot_messages(_history),}elif language == "gradio":# Handle Gradio output - check if it's multi-file format or single fileif ('=== app.py ===' in content or '=== requirements.txt ===' in content):1599 unmodified lines("Gradio (Python)", "gradio"),("Streamlit (Python)", "streamlit"),("Static (HTML)", "static"),("Transformers.js", "transformers.js"),("Svelte", "svelte")]sdk_dropdown = gr.Dropdown(choices=[x[0] for x in sdk_choices],997 unmodified lines"react": "docker", # Use 'docker' for React/Next.js Spaces"html": "static","transformers.js": "static", # Transformers.js uses static SDK"svelte": "static", # Svelte uses static SDK"comfyui": "static" # ComfyUI uses static SDK}sdk = language_to_sdk_map.get(language, "gradio")# Create API client with user's token for proper authenticationapi = HfApi(token=token.token)# Only create the repo for new spaces (not updates) and non-Transformers.js, non-Streamlit, and non-Svelte SDKsif not is_update and sdk != "docker" and language not in ["transformers.js", "svelte"]:try:api.create_repo(repo_id=repo_id, # e.g. username/space_name292 unmodified lines# General error handling for both creation and updatesaction_verb = "updating" if is_update else "duplicating"return gr.update(value=f"Error {action_verb} Transformers.js space: {error_msg}", visible=True)# Svelte logicelif language == "svelte":try:actual_repo_id = repo_id# For new spaces, duplicate the template firstif not is_update:from huggingface_hub import duplicate_spaceimport timeduplicated_repo = duplicate_space(from_id="static-templates/svelte",to_id=repo_id,token=token.token,exist_ok=True)print("Duplicated Svelte repo result:", duplicated_repo, type(duplicated_repo))# Extract the actual repo ID from the duplicated space (RepoUrl)try:duplicated_repo_str = str(duplicated_repo)if "/spaces/" in duplicated_repo_str:parts = duplicated_repo_str.split("/spaces/")[-1].split("/")if len(parts) >= 2:actual_repo_id = f"{parts[0]}/{parts[1]}"except Exception as e:print(f"Error extracting repo ID from duplicated_repo: {e}")actual_repo_id = repo_id# Small delay to allow the duplication to fully complete and reduce race conditionsprint("Waiting for template duplication to complete...")time.sleep(3)print("Actual repo ID for Svelte uploads:", actual_repo_id)# Parse all generated Svelte files (dynamic multi-file)files = parse_svelte_output(code) or {}if not isinstance(files, dict) or 'src/App.svelte' not in files or not files['src/App.svelte'].strip():return gr.update(value="Error: Could not parse Svelte output (missing src/App.svelte). Please regenerate the code.", visible=True)# Validate that src/main.ts is generated (should be required now)if 'src/main.ts' not in files:return gr.update(value="Error: Missing src/main.ts file. Please regenerate the code to include the main entry point.", visible=True)# Ensure package.json includes any external npm deps used; overwrite template's package.jsontry:detected = infer_svelte_dependencies(files)existing_pkg_text = files.get('package.json')pkg_text = build_svelte_package_json(existing_pkg_text, detected)# Only write if we have either detected deps or user provided a package.jsonif pkg_text and (detected or existing_pkg_text is not None):files['package.json'] = pkg_textexcept Exception as e:# Non-fatal: proceed without generating package.jsonprint(f"[Svelte Deploy] package.json synthesis skipped: {e}")# Write all files to a temp directory and upload folder in one commitimport tempfile, os, timewith tempfile.TemporaryDirectory() as tmpdir:for rel_path, content in files.items():safe_rel = (rel_path or '').strip().lstrip('/')abs_path = os.path.join(tmpdir, safe_rel)os.makedirs(os.path.dirname(abs_path), exist_ok=True)with open(abs_path, 'w') as fh:fh.write(content or '')# Retry logic for upload_folder to handle race conditionsmax_retries = 3for attempt in range(max_retries):try:api.upload_folder(folder_path=tmpdir,repo_id=actual_repo_id,repo_type="space")break # Success, exit retry loopexcept Exception as upload_error:if "commit has happened since" in str(upload_error).lower() and attempt < max_retries - 1:print(f"Svelte upload attempt {attempt + 1} failed due to race condition, retrying in 2 seconds...")time.sleep(2) # Wait before retrycontinueelse:raise upload_error # Re-raise if not a race condition or max retries reached# Add anycoder tag to existing README (with retry logic)max_retries = 3for attempt in range(max_retries):try:add_anycoder_tag_to_readme(api, actual_repo_id)break # Success, exit retry loopexcept Exception as readme_error:if "commit has happened since" in str(readme_error).lower() and attempt < max_retries - 1:print(f"README tag attempt {attempt + 1} failed due to race condition, retrying in 2 seconds...")time.sleep(2) # Wait before retrycontinueelse:# Non-fatal: README tagging is not critical, just log and continueprint(f"Failed to add anycoder tag to README after {max_retries} attempts: {readme_error}")break# Successspace_url = f"https://huggingface.co/spaces/{actual_repo_id}"action_text = "Updated" if is_update else "Deployed"return gr.update(value=f"✅ {action_text}! [Open your Svelte Space here]({space_url})", visible=True)except Exception as e:error_msg = str(e)return gr.update(value=f"Error deploying Svelte app: {error_msg}", visible=True)# Other SDKs (existing logic)if sdk == "static":import time1511 unmodified lines1512151315141515151615171518143 unmodified lines166216631664166516661667755 unmodified lines242324242425242624272428544 unmodified lines29732974297529762977297811 unmodified lines299029912992299329942995259 unmodified lines325532563257325832593260438 unmodified lines369937003701370237033704116 unmodified lines3821382238233824382538265 unmodified lines38323833383438353836383780 unmodified lines391839193920392139223923311 unmodified lines42354236423742384239424079 unmodified lines4320432143224323432443251599 unmodified lines5925592659275928592959305931997 unmodified lines69296930693169326933693469356936693769386939694069416942292 unmodified lines7235723672377238723972401511 unmodified linesOutput a COMPLETE, STANDALONE HTML document that renders directly in a browser.Hard constraints:- DO NOT use React, ReactDOM, JSX, Babel, Vue, Angular, or any SPA framework.- Use ONLY plain HTML, CSS, and vanilla JavaScript.- Allowed external resources: Tailwind CSS CDN, Font Awesome CDN, Google Fonts.- Do NOT escape characters (no \\n, \\t, or escaped quotes). Output raw HTML/JS/CSS.143 unmodified linesIMPORTANT: 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"""REACT_SYSTEM_PROMPT = """You are an expert React and Next.js developer creating a modern Next.js application.**🚨 CRITICAL: DO NOT Generate README.md Files**755 unmodified linesHistory = List[Tuple[str, str]]Messages = List[Dict[str, str]]def history_to_messages(history: History, system: str) -> Messages:messages = [{'role': 'system', 'content': system}]for h in history:544 unmodified linesidx = lower.find("<html")return text[idx:] if idx != -1 else textdef parse_react_output(text):"""Parse React/Next.js output to extract individual files.11 unmodified linesreturn files if isinstance(files, dict) and files else {}def history_render(history: History):return gr.update(visible=True), history259 unmodified lines# Reformat the modified filesreturn format_transformers_js_output(files)def send_to_sandbox(code):"""Render HTML in a sandboxed iframe. Assumes full HTML is provided by prompts."""html_doc = (code or "").strip()438 unmodified lines'=== index.html ===' in last_assistant_msg or'=== index.js ===' in last_assistant_msg or'=== style.css ===' in last_assistant_msg or'=== app.py ===' in last_assistant_msg or'=== requirements.txt ===' in last_assistant_msg):has_existing_content = True116 unmodified linessystem_prompt = TransformersJSFollowUpSystemPromptelif language == "gradio":system_prompt = GradioFollowUpSystemPromptelif language == "react":system_prompt = REACT_FOLLOW_UP_SYSTEM_PROMPTelse:5 unmodified linessystem_prompt = DYNAMIC_MULTIPAGE_HTML_SYSTEM_PROMPTelif language == "transformers.js":system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPTelif language == "react":system_prompt = REACT_SYSTEM_PROMPTelif language == "gradio":80 unmodified lineshistory: _history,history_output: history_to_chatbot_messages(_history),}else:if has_existing_content and not (clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html")):last_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""311 unmodified linescode_output: gr.update(value=content, language="html"),history_output: history_to_chatbot_messages(_history),}else:clean_code = remove_code_block(content)if has_existing_content:79 unmodified lineshistory: _history,history_output: history_to_chatbot_messages(_history),}elif language == "gradio":# Handle Gradio output - check if it's multi-file format or single fileif ('=== app.py ===' in content or '=== requirements.txt ===' in content):1599 unmodified lines("Gradio (Python)", "gradio"),("Streamlit (Python)", "streamlit"),("Static (HTML)", "static"),("Transformers.js", "transformers.js")]sdk_dropdown = gr.Dropdown(choices=[x[0] for x in sdk_choices],997 unmodified lines"react": "docker", # Use 'docker' for React/Next.js Spaces"html": "static","transformers.js": "static", # Transformers.js uses static SDK"comfyui": "static" # ComfyUI uses static SDK}sdk = language_to_sdk_map.get(language, "gradio")# Create API client with user's token for proper authenticationapi = HfApi(token=token.token)# Only create the repo for new spaces (not updates) and non-Transformers.js, non-Streamlit SDKsif not is_update and sdk != "docker" and language not in ["transformers.js"]:try:api.create_repo(repo_id=repo_id, # e.g. username/space_name292 unmodified lines# General error handling for both creation and updatesaction_verb = "updating" if is_update else "duplicating"return gr.update(value=f"Error {action_verb} Transformers.js space: {error_msg}", visible=True)# Other SDKs (existing logic)if sdk == "static":import time
app.py+4-356