AiCoderv2 commited on
Commit
c7b1731
·
verified ·
1 Parent(s): 32b45b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -93
app.py CHANGED
@@ -1,5 +1,5 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
  import torch
4
  import time
5
  import warnings
@@ -7,81 +7,36 @@ import warnings
7
  # Suppress warnings
8
  warnings.filterwarnings("ignore")
9
 
10
- # Load model
11
  try:
12
- print("Loading FLAN-T5 model...")
13
- model_name = "google/flan-t5-base"
14
- tokenizer = AutoTokenizer.from_pretrained(model_name)
15
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
 
 
 
 
 
16
  model_loaded = True
17
- print("Model loaded successfully")
18
  except Exception as e:
19
- print(f"Model loading failed: {e}")
20
  model_loaded = False
21
 
22
  def generate_code_stream(prompt):
23
  """Stream HTML code generation token by token"""
24
  if not model_loaded:
25
- # Template-based fallback with streaming
26
- template = f"""<!DOCTYPE html>
27
- <html lang="en">
28
- <head>
29
- <meta charset="UTF-8">
30
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
31
- <title>{prompt or 'AI Generated Website'}</title>
32
- <style>
33
- * {{ margin: 0; padding: 0; box-sizing: border-box; }}
34
- body {{ font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; }}
35
- .container {{ max-width: 1200px; margin: 0 auto; }}
36
- header {{ background: rgba(255,255,255,0.95); padding: 2rem; border-radius: 15px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }}
37
- h1 {{ color: #2c3e50; margin-bottom: 1rem; }}
38
- .content {{ background: rgba(255,255,255,0.95); margin: 20px 0; padding: 2rem; border-radius: 15px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); }}
39
- button {{ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 25px; border-radius: 8px; cursor: pointer; font-size: 16px; transition: transform 0.2s; }}
40
- button:hover {{ transform: translateY(-2px); }}
41
- .features {{ display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin: 2rem 0; }}
42
- .feature-card {{ background: #f8f9fa; padding: 1.5rem; border-radius: 10px; border-left: 5px solid #667eea; }}
43
- </style>
44
- </head>
45
- <body>
46
- <div class="container">
47
- <header>
48
- <h1>{prompt or 'AI Generated Website'}</h1>
49
- <p>Created with artificial intelligence</p>
50
- </header>
51
- <div class="content">
52
- <h2>Welcome to Your Generated Site</h2>
53
- <p>This website was created based on your description: "{prompt}"</p>
54
-
55
- <div class="features">
56
- <div class="feature-card">
57
- <h3>Feature 1</h3>
58
- <p>Modern design with responsive layout</p>
59
- </div>
60
- <div class="feature-card">
61
- <h3>Feature 2</h3>
62
- <p>Interactive elements and animations</p>
63
- </div>
64
- <div class="feature-card">
65
- <h3>Feature 3</h3>
66
- <p>Clean and professional appearance</p>
67
- </div>
68
- </div>
69
-
70
- <button onclick="alert('Hello! Thanks for visiting!')">Click Me</button>
71
- </div>
72
- </div>
73
- </body>
74
- </html>"""
75
-
76
- # Stream character by character
77
- for i in range(len(template)):
78
- time.sleep(0.005) # Fast streaming
79
- yield template[:i+1]
80
  return
81
 
82
  try:
83
- full_prompt = f"Create a complete modern HTML file with embedded CSS for: {prompt}. Include responsive design, modern styling, and interactive elements. Return only valid HTML code."
84
- inputs = tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=512)
85
 
86
  # Generate with streaming
87
  outputs = model.generate(
@@ -93,23 +48,19 @@ def generate_code_stream(prompt):
93
 
94
  # Decode and stream character by character
95
  decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
96
-
97
- # Extract HTML if there's extra text
98
- if '<!DOCTYPE html>' in decoded:
99
- start = decoded.find('<!DOCTYPE html>')
100
- decoded = decoded[start:]
101
 
102
  # Stream character by character for smooth effect
103
- for i in range(len(decoded)):
104
  time.sleep(0.003) # Very fast streaming
105
- yield decoded[:i+1]
106
 
107
  except Exception as e:
108
- # Fallback streaming
109
- error_template = f"<!-- Generation Error: {str(e)} -->\n<!DOCTYPE html>\n<html>\n<head>\n <title>Error - {prompt or 'AI Generated Website'}</title>\n</head>\n<body>\n <h1>Generation Failed</h1>\n <p>Please try again with a different description</p>\n</body>\n</html>"
110
- for i in range(len(error_template)):
111
- time.sleep(0.005)
112
- yield error_template[:i+1]
113
 
114
  def run_code(html_code):
115
  """Run the generated code in preview"""
@@ -118,28 +69,21 @@ def run_code(html_code):
118
  def improve_code(description, current_code):
119
  """Improve existing code"""
120
  if not model_loaded:
121
- return current_code
122
 
123
  try:
124
  prompt = f"Improve this HTML code based on: {description}\n\nCurrent code:\n{current_code}\n\nReturn only the improved HTML code."
125
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512)
126
- outputs = model.generate(**inputs, max_new_tokens=800, temperature=0.7)
127
- result = tokenizer.decode(outputs[0], skip_special_tokens=True)
128
-
129
- # Extract HTML if there's extra text
130
- if '<!DOCTYPE html>' in result:
131
- start = result.find('<!DOCTYPE html>')
132
- result = result[start:]
133
  return result
134
  except Exception as e:
135
- return current_code
136
 
137
  with gr.Blocks(theme=gr.themes.Soft()) as app:
138
  gr.Markdown("# AI Website Builder")
139
- gr.Markdown("Generate websites with AI - Streaming Edition")
140
-
141
- # State to manage current view
142
- current_view = gr.State(value="editor") # "editor" or "preview"
143
 
144
  with gr.Tab("Builder"):
145
  with gr.Row():
@@ -157,8 +101,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
157
  code_editor = gr.Code(
158
  label="HTML Code Editor",
159
  language="html",
160
- lines=30,
161
- value="<!DOCTYPE html>\n<html>\n<head>\n <title>AI Generated Website</title>\n</head>\n<body>\n <h1>Your website will appear here</h1>\n <p>Enter a description and click Generate Website</p>\n</body>\n</html>"
162
  )
163
 
164
  # Preview area (initially hidden)
 
1
  import gradio as gr
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
  import torch
4
  import time
5
  import warnings
 
7
  # Suppress warnings
8
  warnings.filterwarnings("ignore")
9
 
10
+ # Load the ERNIE model
11
  try:
12
+ print("Loading ERNIE Thinking model...")
13
+ model_name = "baidu/ERNIE-4.5-21B-A3B-Thinking"
14
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
15
+ model = AutoModelForCausalLM.from_pretrained(
16
+ model_name,
17
+ torch_dtype=torch.bfloat16,
18
+ device_map="auto",
19
+ trust_remote_code=True
20
+ )
21
  model_loaded = True
22
+ print("ERNIE Thinking model loaded successfully")
23
  except Exception as e:
24
+ print(f"ERNIE model loading failed: {e}")
25
  model_loaded = False
26
 
27
  def generate_code_stream(prompt):
28
  """Stream HTML code generation token by token"""
29
  if not model_loaded:
30
+ # Error message
31
+ error_msg = "<!-- Model not loaded -->\n<h1>Model Loading Failed</h1>\n<p>Please check the console for details</p>"
32
+ for i in range(len(error_msg)):
33
+ time.sleep(0.01)
34
+ yield error_msg[:i+1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  return
36
 
37
  try:
38
+ full_prompt = f"Create a complete HTML file with embedded CSS and JavaScript for: {prompt}. Return only valid HTML code."
39
+ inputs = tokenizer(full_prompt, return_tensors="pt", truncation=True, max_length=512).to("cuda")
40
 
41
  # Generate with streaming
42
  outputs = model.generate(
 
48
 
49
  # Decode and stream character by character
50
  decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
51
+ result = decoded[len(full_prompt):]
 
 
 
 
52
 
53
  # Stream character by character for smooth effect
54
+ for i in range(len(result)):
55
  time.sleep(0.003) # Very fast streaming
56
+ yield result[:i+1]
57
 
58
  except Exception as e:
59
+ # Error streaming
60
+ error_msg = f"<!-- Generation Error: {str(e)} -->\n<h1>Generation Failed</h1>\n<p>Please try again</p>"
61
+ for i in range(len(error_msg)):
62
+ time.sleep(0.01)
63
+ yield error_msg[:i+1]
64
 
65
  def run_code(html_code):
66
  """Run the generated code in preview"""
 
69
  def improve_code(description, current_code):
70
  """Improve existing code"""
71
  if not model_loaded:
72
+ return "<!-- Model not loaded -->\n<h1>Model Loading Failed</h1>"
73
 
74
  try:
75
  prompt = f"Improve this HTML code based on: {description}\n\nCurrent code:\n{current_code}\n\nReturn only the improved HTML code."
76
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to("cuda")
77
+ outputs = model.generate(**inputs, max_new_tokens=800, temperature=0.7, do_sample=True)
78
+ decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
79
+ result = decoded[len(prompt):]
 
 
 
 
80
  return result
81
  except Exception as e:
82
+ return f"<!-- Error: {str(e)} -->\n{current_code}"
83
 
84
  with gr.Blocks(theme=gr.themes.Soft()) as app:
85
  gr.Markdown("# AI Website Builder")
86
+ gr.Markdown("Powered by baidu/ERNIE-4.5-21B-A3B-Thinking")
 
 
 
87
 
88
  with gr.Tab("Builder"):
89
  with gr.Row():
 
101
  code_editor = gr.Code(
102
  label="HTML Code Editor",
103
  language="html",
104
+ lines=30
 
105
  )
106
 
107
  # Preview area (initially hidden)