broadfield-dev commited on
Commit
9fd0d3c
·
verified ·
1 Parent(s): 81145bc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import re
3
+
4
+ def update_ui(code):
5
+ try:
6
+ # Extract HTML and CSS
7
+ html_content = re.search(r'<html[^>]*>[\s\S]*?<\/html>', code, re.IGNORECASE)
8
+ if html_content:
9
+ html_content = html_content.group(0)
10
+ else:
11
+ html_content = code # If no <html> tag, assume all is HTML content
12
+
13
+ # Extract CSS if present in a <style> tag
14
+ css_content = re.search(r'<style[^>]*>[\s\S]*?<\/style>', code, re.IGNORECASE)
15
+ css_string = ''
16
+ if css_content:
17
+ css_string = css_content.group(0)
18
+
19
+ # Remove <style> tags for direct application
20
+ css_only = re.sub(r'<style>|<\/style>', '', css_string) if css_string else ''
21
+
22
+ # Extract JavaScript if present in a <script> tag
23
+ js_content = re.search(r'<script[^>]*>[\s\S]*?<\/script>', code, re.IGNORECASE)
24
+ js_string = ''
25
+ if js_content:
26
+ js_string = js_content.group(0)
27
+
28
+ # Remove <script> tags for Gradio's js= parameter
29
+ js_only = re.sub(r'<script>|<\/script>', '', js_string) if js_string else ''
30
+
31
+ # Combine HTML with CSS for preview
32
+ ui_output = f"""
33
+ <style>{css_only}</style>
34
+ {html_content}
35
+ """
36
+ return ui_output, js_only
37
+ except Exception as e:
38
+ return "", ""
39
+
40
+ def interface():
41
+ with gr.Blocks() as demo:
42
+ gr.Markdown("# Learn Frontend UI with Snake Game")
43
+ with gr.Row():
44
+ code_input = gr.Code(label="Write your HTML/CSS/JS here", language="html")
45
+ with gr.Column():
46
+ # Note: Gradio's HTML component doesn't directly support inline JS, so we use js= for interactivity
47
+ ui_preview = gr.HTML(label="UI Preview")
48
+ error_output = gr.Textbox(label="Error", interactive=False)
49
+
50
+ # Here we use the js= parameter to inject the JavaScript
51
+ code_input.change(fn=update_ui, inputs=code_input, outputs=[ui_preview, gr.HTML(js="")])
52
+ return demo
53
+
54
+ if __name__ == "__main__":
55
+ demo = interface()
56
+ demo.launch()