add streamit and dropdown and preview support
Browse files34 unmodified lines3536373839401522 unmodified lines156315641565156615671568522 unmodified lines2091209220932094209520962097209820992100190 unmodified lines229122922293229422952296229722982299230099 unmodified lines2400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242592 unmodified lines251825192520252125222523252412 unmodified lines2537253825392540254125422543254425452546740 unmodified lines328732883289329032913292329332943295160 unmodified lines345634573458345934603461346234633464346524 unmodified lines3490349134923493349434953 unmodified lines34993500350135023503350435053506350735083509351035113512351335143515351634 unmodified lines]def get_gradio_language(language):return language if language in GRADIO_SUPPORTED_LANGUAGES else None# Search/Replace Constants1522 unmodified linesiframe = 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>'return iframedef demo_card_click(e: gr.EventData):try:# Get the index from the event data522 unmodified linesif chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)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>",}except Exception as e:190 unmodified linestext_to_image_prompt=text_to_image_prompt,)yield {code_output: final_content,history: _history,sandbox: send_to_sandbox(final_content) 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>",history_output: history_to_chatbot_messages(_history),}return99 unmodified lines# Handle modification of existing contentif clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):# Model returned a complete HTML fileyield {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:# Model returned search/replace changes - apply themlast_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_content = apply_search_replace_changes(last_content, clean_code)clean_content = remove_code_block(modified_content)yield {code_output: gr.update(value=clean_content, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: send_to_sandbox(clean_content) 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 error92 unmodified linesyield {code_output: clean_content,history: _history,sandbox: send_to_sandbox(clean_content) 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>",history_output: history_to_chatbot_messages(_history),}else:12 unmodified lines)_history.append([query, final_content])yield {code_output: final_content,history: _history,sandbox: send_to_sandbox(final_content),history_output: history_to_chatbot_messages(_history),}except Exception as e:740 unmodified lineslines=3,visible=True)# Language dropdown for code generationlanguage_choices = ["html", "python", "transformers.js", "svelte", "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,160 unmodified lines# Success - update the code output and show success message# Also update history to include the loaded projectloaded_history = [[f"Loaded project from {url}", code]]return [gr.update(value=status, visible=True),gr.update(value=code, language="html"),gr.update(value=send_to_sandbox(code) if code.strip().startswith('<!DOCTYPE html>') or code.strip().startswith('<html') else "<div style='padding:1em;color:#888;text-align:center;'>Preview not available for this file type.</div>"),gr.update(value=""),loaded_history,history_to_chatbot_messages(loaded_history),24 unmodified linesreturn gr.update(value="Svelte")elif language == "html":return gr.update(value="Static (HTML)")else:return gr.update(value="Gradio (Python)")3 unmodified linesdef 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>"elif language == "svelte":# For Svelte, we can't preview the compiled app, so show a messagereturn "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your Svelte code and deploy it to see the result.</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>"def show_deploy_components(*args):return [gr.Textbox(visible=True), gr.Dropdown(visible=True), gr.Button(visible=True)]34 unmodified lines3536373839404142431522 unmodified lines1566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608522 unmodified lines2131213221332134213521362137213821392140214121422143214421452146190 unmodified lines23372338233923402341234223432344234523462347234823492350235199 unmodified lines2451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249192 unmodified lines258425852586258725882589259012 unmodified lines260326042605260626072608260926102611261226132614261526162617740 unmodified lines335833593360336133623363336433653366160 unmodified lines35273528352935303531353235333534353535363537353835393540354135423543354435453546354724 unmodified lines357235733574357535763577357835793 unmodified lines3583358435853586358735883589359035913592359335943595359635973598359936003601360234 unmodified lines]def get_gradio_language(language):# Map composite options to a supported syntax highlightingif language == "streamlit":return "python"return language if language in GRADIO_SUPPORTED_LANGUAGES else None# Search/Replace Constants1522 unmodified linesiframe = 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>'return iframedef is_streamlit_code(code: str) -> bool:"""Heuristic check to determine if Python code is a Streamlit app."""if not code:return Falselowered = code.lower()return ("import streamlit" in lowered) or ("from streamlit" in lowered) or ("st." in code and "streamlit" in lowered)def send_streamlit_to_stlite(code: str) -> str:"""Render Streamlit code using stlite inside a sandboxed iframe for preview."""# Build an HTML document that loads stlite and mounts the Streamlit app defined inlinehtml_doc = ("""<!doctype html><html><head><meta charset=\"UTF-8\" /><meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" /><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\" /><title>Streamlit Preview</title><link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/@stlite/browser@0.86.0/build/stlite.css\" /><style>html,body{margin:0;padding:0;height:100%;} streamlit-app{display:block;height:100%;}</style><script type=\"module\" src=\"https://cdn.jsdelivr.net/npm/@stlite/browser@0.86.0/build/stlite.js\"></script></head><body><streamlit-app>"""+ (code or "")+ """</streamlit-app></body></html>""")encoded_html = base64.b64encode(html_doc.encode('utf-8')).decode('utf-8')data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"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>'return iframedef demo_card_click(e: gr.EventData):try:# Get the index from the event data522 unmodified linesif chunk.choices[0].delta.content:content += chunk.choices[0].delta.contentclean_code = remove_code_block(content)# Live streaming previewpreview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: preview_val or "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>",}except Exception as e:190 unmodified linestext_to_image_prompt=text_to_image_prompt,)preview_val = Noneif language == "html":preview_val = send_to_sandbox(final_content)elif language == "python" and is_streamlit_code(final_content):preview_val = send_streamlit_to_stlite(final_content)yield {code_output: final_content,history: _history,sandbox: preview_val or "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>",history_output: history_to_chatbot_messages(_history),}return99 unmodified lines# Handle modification of existing contentif clean_code.strip().startswith("<!DOCTYPE html>") or clean_code.strip().startswith("<html"):# Model returned a complete HTML filepreview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: preview_val or "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>",}else:# Model returned search/replace changes - apply themlast_content = _history[-1][1] if _history and len(_history[-1]) > 1 else ""modified_content = apply_search_replace_changes(last_content, clean_code)clean_content = remove_code_block(modified_content)preview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_content)elif language == "python" and is_streamlit_code(clean_content):preview_val = send_streamlit_to_stlite(clean_content)yield {code_output: gr.update(value=clean_content, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: preview_val or "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>",}else:preview_val = Noneif language == "html":preview_val = send_to_sandbox(clean_code)elif language == "python" and is_streamlit_code(clean_code):preview_val = send_streamlit_to_stlite(clean_code)yield {code_output: gr.update(value=clean_code, language=get_gradio_language(language)),history_output: history_to_chatbot_messages(_history),sandbox: preview_val or "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>",}# Skip chunks with empty choices (end of stream)# Do not treat as error92 unmodified linesyield {code_output: clean_content,history: _history,sandbox: (send_to_sandbox(clean_content) if language == "html" else (send_streamlit_to_stlite(clean_content) if (language == "python" and is_streamlit_code(clean_content)) else "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>")),history_output: history_to_chatbot_messages(_history),}else:12 unmodified lines)_history.append([query, final_content])preview_val = Noneif language == "html":preview_val = send_to_sandbox(final_content)elif language == "python" and is_streamlit_code(final_content):preview_val = send_streamlit_to_stlite(final_content)yield {code_output: final_content,history: _history,sandbox: preview_val or "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML or Streamlit-in-Python.</div>",history_output: history_to_chatbot_messages(_history),}except Exception as e:740 unmodified lineslines=3,visible=True)# Language dropdown for code generation (add Streamlit as a first-class option)language_choices = ["html", "streamlit", "python", "transformers.js", "svelte", "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,160 unmodified lines# Success - update the code output and show success message# Also update history to include the loaded projectloaded_history = [[f"Loaded project from {url}", code]]# Determine preview based on content (HTML or Streamlit)if code and (code.strip().startswith('<!DOCTYPE html>') or code.strip().startswith('<html')):preview_html = send_to_sandbox(code)code_lang = "html"elif is_streamlit_code(code):preview_html = send_streamlit_to_stlite(code)code_lang = "python"else:preview_html = "<div style='padding:1em;color:#888;text-align:center;'>Preview not available for this file type.</div>"code_lang = "html"return [gr.update(value=status, visible=True),gr.update(value=code, language=code_lang),gr.update(value=preview_html),gr.update(value=""),loaded_history,history_to_chatbot_messages(loaded_history),24 unmodified linesreturn gr.update(value="Svelte")elif language == "html":return gr.update(value="Static (HTML)")elif language == "streamlit":return gr.update(value="Streamlit (Python)")else:return gr.update(value="Gradio (Python)")3 unmodified linesdef preview_logic(code, language):if language == "html":return send_to_sandbox(code)if language == "streamlit":return send_streamlit_to_stlite(code) if is_streamlit_code(code) else "<div style='padding:1em;color:#888;text-align:center;'>Add `import streamlit as st` to enable Streamlit preview.</div>"if language == "python" or is_streamlit_code(code):if is_streamlit_code(code):return send_streamlit_to_stlite(code)return "<div style='padding:1em;color:#888;text-align:center;'>Preview available only for Streamlit apps in Python. Add `import streamlit as st`.</div>"if language == "transformers.js":files = parse_transformers_js_output(code)if files['index.html']:return send_to_sandbox(files['index.html'])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>"if language == "svelte":return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML. Please download your Svelte code and deploy it to see the result.</div>"return "<div style='padding:1em;color:#888;text-align:center;'>Preview is only available for HTML.</div>"def show_deploy_components(*args):return [gr.Textbox(visible=True), gr.Dropdown(visible=True), gr.Button(visible=True)]
app.py+105-19