update transformers js
Browse files57 unmodified lines585960616263158 unmodified lines222223224225226227103 unmodified lines331332333334335336643 unmodified lines98098198298398498554 unmodified lines10401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074111 unmodified lines118611871188118911901191119229 unmodified lines122212231224122512261227122864 unmodified lines1293129412951296129712981299130013011302130338 unmodified lines134213431344134513461347134845 unmodified lines13941395139613971398139957 unmodified linesAlways output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text. Do NOT add the language name at the top of the code output."""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 ``` 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. Do NOT add the language name at the top of the code output."""# System prompt with search capability158 unmodified lines{"title": "Search/Replace Example","description": "Generate HTML first, then ask: 'Change the title to My New Title' or 'Add a blue background to the body'"}]103 unmodified linesreturn lines[1] if len(lines) > 1 else ''return text.strip()def history_render(history: History):return gr.update(visible=True), history643 unmodified lines# Use language-specific promptif language == "html":system_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPTelse:system_prompt = GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language) if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)54 unmodified lineschunk.choices[0].delta.content is not None):content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)search_status = " (with web search)" if enable_search and tavily_client else ""if has_existing_html:# Fallback: If the model returns a full HTML file, use it directlyif clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),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>",}else:last_html = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {code_output: gr.update(value=clean_html, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),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>",}else:yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),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>",}# Skip chunks with empty choices (end of stream)# Do not treat as error# Handle response based on whether this is a modification or new generationif has_existing_html:# Fallback: If the model returns a full HTML file, use it directlyfinal_code = remove_code_block(content)if final_code.strip().startswith("<!DOCTYPE html>") or final_code.strip().startswith("<html"):111 unmodified lines)# Language dropdown for code generationlanguage_choices = ["html", "python", "c", "cpp", "markdown", "latex", "json", "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"]language_dropdown = gr.Dropdown(choices=language_choices,29 unmodified linessdk_choices = [("Gradio (Python)", "gradio"),("Streamlit (Python)", "streamlit"),("Static (HTML)", "static")]sdk_dropdown = gr.Dropdown(choices=[x[0] for x in sdk_choices],64 unmodified linesdef update_code_language(language):return gr.update(language=get_gradio_language(language))language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)def preview_logic(code, language):if language == "html":return send_to_sandbox(code)else: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>"38 unmodified linessdk_map = {"Gradio (Python)": "gradio","Streamlit (Python)": "docker", # Use 'docker' for Streamlit Spaces"Static (HTML)": "static"}sdk = sdk_map.get(sdk_name, "gradio")api = HfApi(token=token.token)45 unmodified linesexcept Exception as e:return gr.update(value=f"Error duplicating Streamlit space: {e}", visible=True)# Other SDKs (existing logic)if sdk == "static":file_name = "index.html"57 unmodified lines585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128158 unmodified lines287288289290291292293294295296103 unmodified lines400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446643 unmodified lines1090109110921093109410951096109754 unmodified lines115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226111 unmodified lines133813391340134113421343134429 unmodified lines1374137513761377137813791380138164 unmodified lines14461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147238 unmodified lines1511151215131514151515161517151845 unmodified lines15641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165057 unmodified linesAlways output only the HTML code inside a ```html ... ``` code block, and do not include any explanations or extra text. Do NOT add the language name at the top of the code output."""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.IMPORTANT: You MUST output ALL THREE files in the following format:```html<!-- index.html content here -->``````javascript// index.js content here``````css/* style.css content here */```Requirements:1. Create a modern, responsive web application using transformers.js2. Use the transformers.js library for AI/ML functionality3. Create a clean, professional UI with good user experience4. Make the application fully responsive for mobile devices5. Use modern CSS practices and JavaScript ES6+ features6. Include proper error handling and loading states7. Follow accessibility best practicesThe index.html should contain the basic HTML structure and link to the CSS and JS files.The index.js should contain all the JavaScript logic including transformers.js integration.The style.css should contain all the styling for the application.Always output only the three code blocks as shown above, and do not include any explanations or extra text."""TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH = """You are an expert web developer creating a transformers.js application. You have access to real-time web search. When needed, use web search to find the latest information, best practices, or specific technologies for transformers.js.You will generate THREE separate files: index.html, index.js, and style.css.IMPORTANT: You MUST output ALL THREE files in the following format:```html<!-- index.html content here -->``````javascript// index.js content here``````css/* style.css content here */```Requirements:1. Create a modern, responsive web application using transformers.js2. Use the transformers.js library for AI/ML functionality3. Use web search to find current best practices and latest transformers.js features4. Create a clean, professional UI with good user experience5. Make the application fully responsive for mobile devices6. Use modern CSS practices and JavaScript ES6+ features7. Include proper error handling and loading states8. Follow accessibility best practicesThe index.html should contain the basic HTML structure and link to the CSS and JS files.The index.js should contain all the JavaScript logic including transformers.js integration.The style.css should contain all the styling for the application.Always output only the three code blocks as shown above, and do not include any explanations or extra text."""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 ``` 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. Do NOT add the language name at the top of the code output."""# System prompt with search capability158 unmodified lines{"title": "Search/Replace Example","description": "Generate HTML first, then ask: 'Change the title to My New Title' or 'Add a blue background to the body'"},{"title": "Transformers.js App","description": "Create a transformers.js application with AI/ML functionality using the transformers.js library"}]103 unmodified linesreturn lines[1] if len(lines) > 1 else ''return text.strip()def parse_transformers_js_output(text):"""Parse transformers.js output and extract the three files (index.html, index.js, style.css)"""files = {'index.html': '','index.js': '','style.css': ''}# Patterns to match the three code blockshtml_pattern = r'```html\s*\n([\s\S]+?)\n```'js_pattern = r'```javascript\s*\n([\s\S]+?)\n```'css_pattern = r'```css\s*\n([\s\S]+?)\n```'# Extract HTML contenthtml_match = re.search(html_pattern, text, re.IGNORECASE)if html_match:files['index.html'] = html_match.group(1).strip()# Extract JavaScript contentjs_match = re.search(js_pattern, text, re.IGNORECASE)if js_match:files['index.js'] = js_match.group(1).strip()# Extract CSS contentcss_match = re.search(css_pattern, text, re.IGNORECASE)if css_match:files['style.css'] = css_match.group(1).strip()return filesdef format_transformers_js_output(files):"""Format the three files into a single display string"""output = []output.append("=== index.html ===")output.append(files['index.html'])output.append("\n=== index.js ===")output.append(files['index.js'])output.append("\n=== style.css ===")output.append(files['style.css'])return '\n'.join(output)def history_render(history: History):return gr.update(visible=True), history643 unmodified lines# Use language-specific promptif language == "html":system_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPTelif language == "transformers.js":system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH if enable_search else TRANSFORMERS_JS_SYSTEM_PROMPTelse:system_prompt = GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language) if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)54 unmodified lineschunk.choices[0].delta.content is not None):content += chunk.choices[0].delta.contentsearch_status = " (with web search)" if enable_search and tavily_client else ""# Handle transformers.js output differentlyif language == "transformers.js":files = parse_transformers_js_output(content)if files['index.html'] and files['index.js'] and files['style.css']:formatted_output = format_transformers_js_output(files)yield {code_output: gr.update(value=formatted_output, language="html"),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(files['index.html']) if files['index.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>",}else:# Still streaming, show partial contentyield {code_output: gr.update(value=content, language="html"),history_output: history_to_chatbot_messages(_history),sandbox: "<div style='padding:1em;color:#888;text-align:center;'>Generating transformers.js app...</div>",}else:clean_code = remove_code_block(content)if has_existing_html:# Fallback: If the model returns a full HTML file, use it directlyif clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),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>",}else:last_html = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_html = apply_search_replace_changes(last_html, clean_code)clean_html = remove_code_block(modified_html)yield {code_output: gr.update(value=clean_html, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),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>",}else:yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),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>",}# Skip chunks with empty choices (end of stream)# Do not treat as error# Handle response based on whether this is a modification or new generationif language == "transformers.js":# Handle transformers.js outputfiles = parse_transformers_js_output(content)if files['index.html'] and files['index.js'] and files['style.css']:formatted_output = format_transformers_js_output(files)_history.append([query, formatted_output])yield {code_output: formatted_output,history: _history,sandbox: send_to_sandbox(files['index.html']),history_output: history_to_chatbot_messages(_history),}else:# Fallback if parsing failed_history.append([query, content])yield {code_output: content,history: _history,sandbox: "<div style='padding:1em;color:#888;text-align:center;'>Error parsing transformers.js output. Please try again.</div>",history_output: history_to_chatbot_messages(_history),}elif has_existing_html:# Fallback: If the model returns a full HTML file, use it directlyfinal_code = remove_code_block(content)if final_code.strip().startswith("<!DOCTYPE html>") or final_code.strip().startswith("<html"):111 unmodified lines)# Language dropdown for code generationlanguage_choices = ["html", "python", "c", "cpp", "markdown", "latex", "json", "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", "transformers.js"]language_dropdown = gr.Dropdown(choices=language_choices,29 unmodified linessdk_choices = [("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],64 unmodified linesdef update_code_language(language):return gr.update(language=get_gradio_language(language))def update_sdk_based_on_language(language):if language == "transformers.js":return gr.update(value="Transformers.js")elif language == "html":return gr.update(value="Static (HTML)")else:return gr.update(value="Gradio (Python)")language_dropdown.change(update_code_language, inputs=language_dropdown, outputs=code_output)language_dropdown.change(update_sdk_based_on_language, inputs=language_dropdown, outputs=sdk_dropdown)def preview_logic(code, language):if language == "html":return send_to_sandbox(code)elif language == "transformers.js":# For transformers.js, extract the HTML part for previewfiles = parse_transformers_js_output(code)if files['index.html']:return send_to_sandbox(files['index.html'])else: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>"else: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>"38 unmodified linessdk_map = {"Gradio (Python)": "gradio","Streamlit (Python)": "docker", # Use 'docker' for Streamlit Spaces"Static (HTML)": "static","Transformers.js": "static" # Transformers.js uses static SDK}sdk = sdk_map.get(sdk_name, "gradio")api = HfApi(token=token.token)45 unmodified linesexcept Exception as e:return gr.update(value=f"Error duplicating Streamlit space: {e}", visible=True)# Transformers.js logicelif sdk_name == "Transformers.js":try:# Use duplicate_space to create a transformers.js template spacefrom huggingface_hub import duplicate_space# Duplicate the transformers.js template spaceduplicated_repo = duplicate_space(from_id="static-templates/transformers.js",to_id=space_name.strip(),token=token.token,exist_ok=True)# Parse the transformers.js output to get the three filesfiles = parse_transformers_js_output(code)if not files['index.html'] or not files['index.js'] or not files['style.css']:return gr.update(value="Error: Could not parse transformers.js output. Please regenerate the code.", visible=True)# Upload the three files to the duplicated spaceimport tempfile# Upload index.htmlwith tempfile.NamedTemporaryFile("w", suffix=".html", delete=False) as f:f.write(files['index.html'])temp_path = f.nametry:api.upload_file(path_or_fileobj=temp_path,path_in_repo="index.html",repo_id=repo_id,repo_type="space")except Exception as e:return gr.update(value=f"Error uploading index.html: {e}", visible=True)finally:import osos.unlink(temp_path)# Upload index.jswith tempfile.NamedTemporaryFile("w", suffix=".js", delete=False) as f:f.write(files['index.js'])temp_path = f.nametry:api.upload_file(path_or_fileobj=temp_path,path_in_repo="index.js",repo_id=repo_id,repo_type="space")except Exception as e:return gr.update(value=f"Error uploading index.js: {e}", visible=True)finally:import osos.unlink(temp_path)# Upload style.csswith tempfile.NamedTemporaryFile("w", suffix=".css", delete=False) as f:f.write(files['style.css'])temp_path = f.nametry:api.upload_file(path_or_fileobj=temp_path,path_in_repo="style.css",repo_id=repo_id,repo_type="space")space_url = f"https://huggingface.co/spaces/{repo_id}"return gr.update(value=f"✅ Deployed! [Open your Transformers.js Space here]({space_url})", visible=True)except Exception as e:return gr.update(value=f"Error uploading style.css: {e}", visible=True)finally:import osos.unlink(temp_path)except Exception as e:return gr.update(value=f"Error duplicating Transformers.js space: {e}", visible=True)# Other SDKs (existing logic)if sdk == "static":file_name = "index.html"
app.py+271-20