mgbam commited on
Commit
10686a9
·
verified ·
1 Parent(s): caf61b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -91
app.py CHANGED
@@ -1,15 +1,30 @@
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 +36,112 @@ 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, tavily_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
+ apply_transformers_js_search_replace_changes,
14
+ history_to_messages,
15
+ history_to_chatbot_messages,
16
+ remove_code_block,
17
+ parse_transformers_js_output,
18
+ format_transformers_js_output
19
+ )
20
+ from search_replace import SEARCH_START, DIVIDER, REPLACE_END
21
+ from web_scraper import extract_text_from_image
22
+ from deploy import send_to_sandbox, handle_load_project
23
 
24
+ # Type aliases
25
+ History = List[Tuple[str, str]]
26
 
27
+ # Core generation function
28
  def generation_code(
29
  query: Optional[str],
30
  image: Optional[gr.Image],
 
36
  enable_search: bool,
37
  language: str,
38
  provider: str
39
+ ) -> Tuple[str, History, str, List[Dict[str, str]]]:
40
+ # Initialize inputs
41
+ if query is None:
42
+ query = ''
43
+ if _history is None:
44
+ _history = []
45
+
46
+ # Prepare system prompt and history
47
+ system_prompt = _setting.get('system', HTML_SYSTEM_PROMPT)
48
+ messages = history_to_messages(_history, system_prompt)
49
+
50
+ # Append file content if provided
51
+ if file:
52
+ file_text = extract_text_from_file(file)
53
+ if file_text:
54
+ query += f"\n\n[Reference file content below]\n{file_text[:5000]}"
55
+
56
+ # Append website content if provided
57
+ if website_url:
58
+ website_text = extract_website_content(website_url)
59
+ if not website_text.startswith("Error"):
60
+ query += f"\n\n[Website content below]\n{website_text[:8000]}"
61
+
62
+ # Enhance with web search if enabled
63
+ final_query = enhance_query_with_search(query, enable_search)
64
+ messages.append({'role': 'user', 'content': final_query})
65
+
66
+ # Call HF inference
67
+ client = get_inference_client(_current_model['id'], provider)
68
+ completion = client.chat.completions.create(
69
+ model=_current_model['id'],
70
+ messages=messages,
71
+ max_tokens=10000
72
+ )
73
+ content = completion.choices[0].message.content
74
+
75
+ # Process output based on language and existing content
76
+ has_existing = bool(_history and _history[-1][1])
77
+ if language == 'transformers.js':
78
+ files = parse_transformers_js_output(content)
79
+ code_str = format_transformers_js_output(files)
80
+ sandbox_html = send_to_sandbox(files['index.html'])
81
+ else:
82
+ clean = remove_code_block(content)
83
+ if has_existing and not clean.strip().startswith('<!DOCTYPE'):
84
+ clean = apply_search_replace_changes(_history[-1][1], clean)
85
+ code_str = clean
86
+ sandbox_html = send_to_sandbox(clean) if language == 'html' else ''
87
 
88
+ # Update history and prepare chatbot messages
89
+ new_history = _history + [(query, code_str)]
90
+ chat_msgs = history_to_chatbot_messages(new_history)
91
+
92
+ # Return exactly four outputs: code, history state, preview HTML, and chat history
93
+ return code_str, new_history, sandbox_html, chat_msgs
94
+
95
+ # Build Gradio UI
96
  with gr.Blocks(
97
+ theme=gr.themes.Base(),
 
 
 
 
 
 
 
 
 
98
  title="AnyCoder - AI Code Generator"
99
  ) as demo:
100
+ history_state = gr.State([])
101
+ setting_state = gr.State({ 'system': HTML_SYSTEM_PROMPT })
102
  current_model = gr.State(AVAILABLE_MODELS[9])
 
 
103
 
 
104
  with gr.Sidebar():
105
+ gr.LoginButton()
106
+ load_project_url = gr.Textbox(label="Hugging Face Space URL")
107
+ load_project_btn = gr.Button("Import Project")
 
108
  load_project_status = gr.Markdown(visible=False)
109
 
110
+ input_box = gr.Textbox(label="What to build?", lines=3)
111
+ language_dropdown = gr.Dropdown(choices=["html","python","transformers.js"], value="html")
112
+ website_input = gr.Textbox(label="Website URL")
113
+ file_input = gr.File(label="Reference file")
114
+ image_input = gr.Image(label="Design image")
115
+ search_toggle = gr.Checkbox(label="Web search")
116
+ model_dropdown = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[9]['name'])
117
+
118
+ generate_btn = gr.Button("Generate")
119
+ clear_btn = gr.Button("Clear")
120
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  with gr.Column():
122
  with gr.Tabs():
123
  with gr.Tab("Code"):
124
+ code_output = gr.Code(label="Generated code")
125
  with gr.Tab("Preview"):
126
+ preview = gr.HTML(label="Live preview")
127
  with gr.Tab("History"):
128
+ history_output = gr.Chatbot()
129
 
 
130
  load_project_btn.click(
131
+ fn=handle_load_project,
132
  inputs=[load_project_url],
133
+ outputs=[load_project_status, code_output, preview, load_project_url, history_state, history_output]
134
  )
135
 
136
+ generate_btn.click(
137
  fn=generation_code,
138
+ inputs=[input_box, image_input, file_input, website_input,
139
+ setting_state, history_state, current_model,
140
+ search_toggle, language_dropdown, gr.State('auto')],
141
+ outputs=[code_output, history_state, preview, history_output]
 
 
142
  )
143
 
144
+ clear_btn.click(lambda: ([], [], "", []), outputs=[history_state, history_output, preview, code_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
 
146
  if __name__ == "__main__":
147
+ demo.queue().launch()