Spaces:
Sleeping
Sleeping
import gradio as gr | |
import re | |
def update_ui(code): | |
try: | |
# Extract HTML and CSS | |
html_content = re.search(r'<html[^>]*>[\s\S]*?<\/html>', code, re.IGNORECASE) | |
if html_content: | |
html_content = html_content.group(0) | |
else: | |
html_content = code # If no <html> tag, assume all is HTML content | |
# Extract CSS if present in a <style> tag | |
css_content = re.search(r'<style[^>]*>[\s\S]*?<\/style>', code, re.IGNORECASE) | |
css_string = '' | |
if css_content: | |
css_string = css_content.group(0) | |
# Remove <style> tags for direct application | |
css_only = re.sub(r'<style>|<\/style>', '', css_string) if css_string else '' | |
# Extract JavaScript if present in a <script> tag | |
js_content = re.search(r'<script[^>]*>[\s\S]*?<\/script>', code, re.IGNORECASE) | |
js_string = '' | |
if js_content: | |
js_string = js_content.group(0) | |
# Remove <script> tags for Gradio's js= parameter | |
js_only = re.sub(r'<script>|<\/script>', '', js_string) if js_string else '' | |
# Combine HTML with CSS for preview | |
ui_output = f""" | |
<style>{css_only}</style> | |
{html_content} | |
""" | |
return ui_output, js_only | |
except Exception as e: | |
return "", "" | |
def interface(): | |
with gr.Blocks() as demo: | |
gr.Markdown("# Learn Frontend UI with Snake Game") | |
with gr.Row(): | |
code_input = gr.Code(label="Write your HTML/CSS/JS here", language="html") | |
with gr.Column(): | |
# Note: Gradio's HTML component doesn't directly support inline JS, so we use js= for interactivity | |
ui_preview = gr.HTML(label="UI Preview") | |
error_output = gr.Textbox(label="Error", interactive=False) | |
# Here we use the js= parameter to inject the JavaScript | |
code_input.change(fn=update_ui, inputs=code_input, outputs=[ui_preview, gr.HTML(js="")]) | |
return demo | |
if __name__ == "__main__": | |
demo = interface() | |
demo.launch() |