mgbam commited on
Commit
6bc26de
·
verified ·
1 Parent(s): ac4a3a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -52
app.py CHANGED
@@ -16,7 +16,7 @@ from utils import (
16
  parse_transformers_js_output,
17
  format_transformers_js_output
18
  )
19
- from deploy import send_to_sandbox, handle_load_project
20
 
21
  # Type aliases
22
  History = List[Tuple[str, str]]
@@ -29,107 +29,134 @@ def generation_code(
29
  website_url: Optional[str],
30
  _setting: Dict[str, str],
31
  _history: Optional[History],
32
- _current_model: Dict,
33
  enable_search: bool,
34
  language: str,
35
  provider: str
36
  ) -> Tuple[str, History, str, List[Dict[str, str]]]:
37
-
38
  if query is None:
39
  query = ''
40
  if _history is None:
41
  _history = []
42
 
 
43
  system_prompt = _setting.get('system', HTML_SYSTEM_PROMPT)
44
  messages = history_to_messages(_history, system_prompt)
45
 
 
46
  if file:
47
- file_text = extract_text_from_file(file)
48
- if file_text:
49
- query += f"\n\n[Reference file content below]\n{file_text[:5000]}"
50
 
 
51
  if website_url:
52
- website_text = extract_website_content(website_url)
53
- if not website_text.startswith("Error"):
54
- query += f"\n\n[Website content below]\n{website_text[:8000]}"
55
 
 
56
  final_query = enhance_query_with_search(query, enable_search)
57
  messages.append({'role': 'user', 'content': final_query})
58
 
59
- client = get_inference_client(_current_model['id'], provider)
60
- completion = client.chat.completions.create(
61
- model=_current_model['id'],
 
62
  messages=messages,
63
  max_tokens=10000
64
  )
65
- content = completion.choices[0].message.content
66
 
67
- has_existing = bool(_history and _history[-1][1])
 
68
  if language == 'transformers.js':
69
  files = parse_transformers_js_output(content)
70
  code_str = format_transformers_js_output(files)
71
- sandbox_html = send_to_sandbox(files['index.html'])
72
  else:
73
  clean = remove_code_block(content)
74
- if has_existing and not clean.strip().startswith('<!DOCTYPE'):
75
  clean = apply_search_replace_changes(_history[-1][1], clean)
76
  code_str = clean
77
- sandbox_html = send_to_sandbox(clean) if language == 'html' else ''
78
 
 
79
  new_history = _history + [(query, code_str)]
80
  chat_msgs = history_to_chatbot_messages(new_history)
81
 
82
- return code_str, new_history, sandbox_html, chat_msgs
83
 
84
- with gr.Blocks(
85
- theme=gr.themes.Base(),
86
- title="AnyCoder - AI Code Generator"
87
- ) as demo:
88
  history_state = gr.State([])
89
  setting_state = gr.State({'system': HTML_SYSTEM_PROMPT})
90
- current_model = gr.State(AVAILABLE_MODELS[9])
91
 
92
  with gr.Sidebar():
93
- gr.LoginButton()
94
- load_project_url = gr.Textbox(label="Hugging Face Space URL")
95
- load_project_btn = gr.Button("Import Project")
96
- load_project_status = gr.Markdown(visible=False)
97
-
98
- input_box = gr.Textbox(label="What to build?", lines=3)
99
- language_dropdown = gr.Dropdown(choices=["html", "python", "transformers.js"], value="html")
100
- website_input = gr.Textbox(label="Website URL")
101
- file_input = gr.File(label="Reference file")
102
- image_input = gr.Image(label="Design image")
103
- search_toggle = gr.Checkbox(label="Web search")
104
- model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[9]['name'])
105
-
106
- generate_btn = gr.Button("Generate")
107
- clear_btn = gr.Button("Clear")
 
 
 
 
 
 
108
 
109
  with gr.Column():
110
  with gr.Tabs():
111
  with gr.Tab("Code"):
112
- code_output = gr.Code(label="Generated code")
113
  with gr.Tab("Preview"):
114
- preview = gr.HTML(label="Live preview")
115
  with gr.Tab("History"):
116
- history_output = gr.Chatbot()
 
 
 
 
 
 
 
117
 
118
- load_project_btn.click(
119
- fn=handle_load_project,
120
- inputs=[load_project_url],
121
- outputs=[load_project_status, code_output, preview, load_project_url, history_state, history_output]
 
 
 
 
 
 
 
122
  )
123
 
124
- generate_btn.click(
125
  fn=generation_code,
126
- inputs=[input_box, image_input, file_input, website_input,
127
- setting_state, history_state, current_model,
128
- search_toggle, language_dropdown, gr.State('auto')],
129
- outputs=[code_output, history_state, preview, history_output]
130
  )
131
 
132
- clear_btn.click(lambda: ([], [], "", []), outputs=[history_state, history_output, preview, code_output])
 
133
 
134
- if __name__ == "__main__":
135
  demo.queue().launch()
 
 
16
  parse_transformers_js_output,
17
  format_transformers_js_output
18
  )
19
+ from deploy import send_to_sandbox, load_project_from_url
20
 
21
  # Type aliases
22
  History = List[Tuple[str, str]]
 
29
  website_url: Optional[str],
30
  _setting: Dict[str, str],
31
  _history: Optional[History],
32
+ _current_model_name: str,
33
  enable_search: bool,
34
  language: str,
35
  provider: str
36
  ) -> Tuple[str, History, str, List[Dict[str, str]]]:
37
+ # Initialize
38
  if query is None:
39
  query = ''
40
  if _history is None:
41
  _history = []
42
 
43
+ # System prompt and history
44
  system_prompt = _setting.get('system', HTML_SYSTEM_PROMPT)
45
  messages = history_to_messages(_history, system_prompt)
46
 
47
+ # File input
48
  if file:
49
+ text = extract_text_from_file(file)
50
+ query += f"\n\n[File content]\n{text[:5000]}"
 
51
 
52
+ # Website input
53
  if website_url:
54
+ text = extract_website_content(website_url)
55
+ if not text.startswith('Error'):
56
+ query += f"\n\n[Website]\n{text[:8000]}"
57
 
58
+ # Web search enhancement
59
  final_query = enhance_query_with_search(query, enable_search)
60
  messages.append({'role': 'user', 'content': final_query})
61
 
62
+ # Model inference
63
+ client = get_inference_client(_current_model_name, provider)
64
+ resp = client.chat.completions.create(
65
+ model=_current_model_name,
66
  messages=messages,
67
  max_tokens=10000
68
  )
69
+ content = resp.choices[0].message.content
70
 
71
+ # Post-processing
72
+ has_existing = bool(_history)
73
  if language == 'transformers.js':
74
  files = parse_transformers_js_output(content)
75
  code_str = format_transformers_js_output(files)
76
+ preview_html = send_to_sandbox(files['index.html'])
77
  else:
78
  clean = remove_code_block(content)
79
+ if has_existing:
80
  clean = apply_search_replace_changes(_history[-1][1], clean)
81
  code_str = clean
82
+ preview_html = send_to_sandbox(clean) if language == 'html' else ''
83
 
84
+ # Update history
85
  new_history = _history + [(query, code_str)]
86
  chat_msgs = history_to_chatbot_messages(new_history)
87
 
88
+ return code_str, new_history, preview_html, chat_msgs
89
 
90
+ # Build UI
91
+ with gr.Blocks(theme=gr.themes.Base(), title="AnyCoder - AI Code Generator") as demo:
92
+ # State
 
93
  history_state = gr.State([])
94
  setting_state = gr.State({'system': HTML_SYSTEM_PROMPT})
95
+ model_state = gr.State(AVAILABLE_MODELS[0]['id'])
96
 
97
  with gr.Sidebar():
98
+ gr.Markdown("## AnyCoder AI")
99
+ # Load project
100
+ url_in = gr.Textbox(label="Load HF Space URL", placeholder="https://huggingface.co/spaces/user/project")
101
+ load_btn = gr.Button("Import Project")
102
+ load_status = gr.Markdown(visible=False)
103
+
104
+ gr.Markdown("---")
105
+ # Inputs
106
+ prompt_in = gr.Textbox(label="Prompt", lines=3)
107
+ file_in = gr.File(label="Reference file")
108
+ image_in = gr.Image(label="Design image")
109
+ url_site = gr.Textbox(label="Website URL")
110
+ search_chk = gr.Checkbox(label="Enable Web Search")
111
+ language_dd = gr.Dropdown(choices=["html","python","transformers.js"], value="html", label="Language")
112
+ model_dd = gr.Dropdown(
113
+ choices=[m['name'] for m in AVAILABLE_MODELS],
114
+ value=AVAILABLE_MODELS[0]['name'],
115
+ label="Model"
116
+ )
117
+ gen_btn = gr.Button("Generate")
118
+ clr_btn = gr.Button("Clear")
119
 
120
  with gr.Column():
121
  with gr.Tabs():
122
  with gr.Tab("Code"):
123
+ code_out = gr.Code(label="Generated Code")
124
  with gr.Tab("Preview"):
125
+ preview_out = gr.HTML(label="Live Preview")
126
  with gr.Tab("History"):
127
+ chat_out = gr.Chatbot(label="History")
128
+
129
+ # Events
130
+ load_btn.click(
131
+ fn=lambda u: load_project_from_url(u),
132
+ inputs=[url_in],
133
+ outputs=[load_status, code_out, preview_out, url_in, history_state, chat_out]
134
+ )
135
 
136
+ def on_model_change(name):
137
+ # find id by name
138
+ for m in AVAILABLE_MODELS:
139
+ if m['name'] == name:
140
+ return m['id']
141
+ return AVAILABLE_MODELS[0]['id']
142
+
143
+ model_dd.change(
144
+ fn=on_model_change,
145
+ inputs=[model_dd],
146
+ outputs=[model_state]
147
  )
148
 
149
+ gen_btn.click(
150
  fn=generation_code,
151
+ inputs=[prompt_in, image_in, file_in, url_site,
152
+ setting_state, history_state, model_state,
153
+ search_chk, language_dd, gr.State('auto')],
154
+ outputs=[code_out, history_state, preview_out, chat_out]
155
  )
156
 
157
+ clr_btn.click(lambda: ([], [], "", []),
158
+ outputs=[history_state, chat_out, preview_out, code_out])
159
 
160
+ if __name__ == '__main__':
161
  demo.queue().launch()
162
+ ```