mgbam commited on
Commit
256b0b9
·
verified ·
1 Parent(s): 2deb7a7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -92
app.py CHANGED
@@ -1,15 +1,27 @@
1
  # app.py
2
 
3
- from constants import *
4
- from hf_client import get_inference_client, tavily_client
 
 
 
5
  from tavily_search import enhance_query_with_search
6
- from utils import *
7
- from search_replace import *
8
- from web_scraper import *
9
- from deploy import *
 
 
 
 
 
 
 
10
 
11
- import gradio as gr
 
12
 
 
13
  def generation_code(
14
  query: Optional[str],
15
  image: Optional[gr.Image],
@@ -21,112 +33,103 @@ def generation_code(
21
  enable_search: bool,
22
  language: str,
23
  provider: str
24
- ):
25
- # (Exact same logic as in your monolith; omitted here for brevity)
26
- # It should handle multimodal input, web scraping, file extraction,
27
- # search/replace modifications, and stream responses via HF client.
28
- ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  with gr.Blocks(
31
- theme=gr.themes.Base(
32
- primary_hue="blue",
33
- secondary_hue="gray",
34
- neutral_hue="gray",
35
- font=gr.themes.GoogleFont("Inter"),
36
- font_mono=gr.themes.GoogleFont("JetBrains Mono"),
37
- text_size=gr.themes.sizes.text_md,
38
- spacing_size=gr.themes.sizes.spacing_md,
39
- radius_size=gr.themes.sizes.radius_md
40
- ),
41
  title="AnyCoder - AI Code Generator"
42
  ) as demo:
43
- history = gr.State([])
44
- setting = gr.State({"system": HTML_SYSTEM_PROMPT})
45
  current_model = gr.State(AVAILABLE_MODELS[9])
46
- open_panel = gr.State(None)
47
- last_login_state = gr.State(None)
48
 
49
- # Sidebar
50
  with gr.Sidebar():
51
- login_button = gr.LoginButton()
52
- gr.Markdown("📥 Load Existing Project")
53
- load_project_url = gr.Textbox(label="Hugging Face Space URL", placeholder="https://huggingface.co/spaces/username/project", lines=1)
54
- load_project_btn = gr.Button("Import Project", variant="secondary", size="sm")
55
  load_project_status = gr.Markdown(visible=False)
56
 
57
- gr.Markdown("---")
58
- input_box = gr.Textbox(label="What would you like to build?", placeholder="Describe your application...", lines=3)
59
- language_dropdown = gr.Dropdown(
60
- choices=[
61
- "html", "python", "c", "cpp", "markdown", "latex", "json",
62
- "css", "javascript", "jinja2", "typescript", "yaml", "dockerfile",
63
- "shell", "r", "sql", "transformers.js"
64
- ],
65
- value="html",
66
- label="Code Language"
67
- )
68
- website_url_input = gr.Textbox(label="Website for redesign", placeholder="https://example.com", lines=1)
69
- file_input = gr.File(
70
- label="Reference file",
71
- file_types=[".pdf", ".txt", ".md", ".csv", ".docx", ".jpg", ".png"]
72
- )
73
- image_input = gr.Image(label="UI design image", visible=False)
74
- search_toggle = gr.Checkbox(label="🔍 Web search", value=False)
75
- model_dropdown = gr.Dropdown(
76
- choices=[m["name"] for m in AVAILABLE_MODELS],
77
- value=AVAILABLE_MODELS[9]["name"],
78
- label="Model"
79
- )
80
-
81
- btn = gr.Button("Generate", variant="primary", size="lg")
82
- clear_btn = gr.Button("Clear", variant="secondary", size="sm")
83
-
84
- # Main panel with tabs
85
  with gr.Column():
86
  with gr.Tabs():
87
  with gr.Tab("Code"):
88
- code_output = gr.Code(language="html", lines=25, interactive=True, label="Generated code")
89
  with gr.Tab("Preview"):
90
- sandbox = gr.HTML(label="Live preview")
91
  with gr.Tab("History"):
92
- history_output = gr.Chatbot(show_label=False, height=400, type="messages")
93
 
94
- # Event hookups
95
  load_project_btn.click(
96
- fn=lambda url: handle_load_project(url),
97
  inputs=[load_project_url],
98
- outputs=[load_project_status, code_output, sandbox, load_project_url, history, history_output]
99
  )
100
 
101
- btn.click(
102
  fn=generation_code,
103
- inputs=[
104
- input_box, image_input, file_input, website_url_input,
105
- setting, history, current_model, search_toggle,
106
- language_dropdown, gr.State("auto")
107
- ],
108
- outputs=[code_output, history, sandbox, history_output]
109
  )
110
 
111
- clear_btn.click(
112
- fn=lambda: ([], [], None, ""),
113
- outputs=[history, history_output, file_input, website_url_input]
114
- )
115
-
116
- # Preview update
117
- code_output.change(
118
- fn=lambda code, lang: send_to_sandbox(code) if lang=="html" else "<div>No preview</div>",
119
- inputs=[code_output, language_dropdown],
120
- outputs=sandbox
121
- )
122
-
123
- # Model switch
124
- model_dropdown.change(
125
- fn=lambda name: (next(m for m in AVAILABLE_MODELS if m["name"]==name),),
126
- inputs=model_dropdown,
127
- outputs=current_model
128
- )
129
 
130
  if __name__ == "__main__":
131
- demo.queue(api_open=False, default_concurrency_limit=20) \
132
- .launch(show_api=False, ssr_mode=True, mcp_server=False)
 
1
  # app.py
2
 
3
+ from typing import Optional, Dict, List, Tuple
4
+ import gradio as gr
5
+
6
+ from constants import HTML_SYSTEM_PROMPT, AVAILABLE_MODELS, DEMO_LIST
7
+ from hf_client import get_inference_client
8
  from tavily_search import enhance_query_with_search
9
+ from utils import (
10
+ extract_text_from_file,
11
+ extract_website_content,
12
+ apply_search_replace_changes,
13
+ history_to_messages,
14
+ history_to_chatbot_messages,
15
+ remove_code_block,
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]]
23
 
24
+ # Core generation function
25
  def generation_code(
26
  query: Optional[str],
27
  image: Optional[gr.Image],
 
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()