mgbam commited on
Commit
6dcd973
Β·
verified Β·
1 Parent(s): f316f73

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -114
app.py CHANGED
@@ -1,7 +1,27 @@
1
- from typing import Optional, Dict, List, Tuple
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
 
3
 
4
- from constants import HTML_SYSTEM_PROMPT, AVAILABLE_MODELS, DEMO_LIST
 
 
5
  from hf_client import get_inference_client
6
  from tavily_search import enhance_query_with_search
7
  from utils import (
@@ -16,141 +36,214 @@ from utils import (
16
  )
17
  from deploy import send_to_sandbox, load_project_from_url
18
 
19
- # Type aliases
20
  History = List[Tuple[str, str]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- # Core generation function
23
- # This function signature correctly includes 'hf_token'. Gradio will automatically
24
- # provide this value if the user is logged in.
25
  def generation_code(
26
  query: Optional[str],
27
- image: Optional[gr.Image],
28
  file: Optional[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
- hf_token: str
37
  ) -> Tuple[str, History, str, List[Dict[str, str]]]:
38
- # Initialize inputs
39
- if query is None:
40
- query = ''
41
- if _history is None:
42
- _history = []
43
-
44
- # System prompt and history
45
- system_prompt = _setting.get('system', HTML_SYSTEM_PROMPT)
46
- messages = history_to_messages(_history, system_prompt)
47
-
48
- # File input
49
- if file:
50
- text = extract_text_from_file(file)
51
- query += f"\n\n[File content]\n{text[:5000]}"
52
-
53
- # Website input
54
- if website_url:
55
- text = extract_website_content(website_url)
56
- if not text.startswith('Error'):
57
- query += f"\n\n[Website content]\n{text[:8000]}"
58
-
59
- # Web search enhancement
60
- final_query = enhance_query_with_search(query, enable_search)
61
- messages.append({'role': 'user', 'content': final_query})
62
-
63
- # Model inference - using the provided user token for billing
64
- client = get_inference_client(_current_model_name, provider, user_token=hf_token)
65
- resp = client.chat.completions.create(
66
- model=_current_model_name,
67
- messages=messages,
68
- max_tokens=10000
69
- )
70
- content = resp.choices[0].message.content
71
-
72
- # Post-processing
73
- has_existing = bool(_history)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  if language == 'transformers.js':
75
  files = parse_transformers_js_output(content)
76
  code_str = format_transformers_js_output(files)
77
- preview_html = send_to_sandbox(files['index.html'])
78
  else:
79
- clean = remove_code_block(content)
80
- if has_existing:
81
- clean = apply_search_replace_changes(_history[-1][1], clean)
82
- code_str = clean
83
- preview_html = send_to_sandbox(clean) if language == 'html' else ''
 
 
 
 
 
 
84
 
85
- # Update history
86
- new_history = _history + [(query, code_str)]
87
- chat_msgs = history_to_chatbot_messages(new_history)
88
 
89
- return code_str, new_history, preview_html, chat_msgs
90
 
91
- # Build UI
92
- with gr.Blocks(theme=gr.themes.Base(), title="AnyCoder - AI Code Generator") as demo:
93
- # State
 
 
 
 
 
94
  history_state = gr.State([])
95
- setting_state = gr.State({'system': HTML_SYSTEM_PROMPT})
96
- model_state = gr.State(AVAILABLE_MODELS[0]['id'])
 
97
 
 
98
  with gr.Sidebar():
99
- gr.Markdown("## AnyCoder AI")
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
- gr.Markdown("---")
104
- prompt_in = gr.Textbox(label="Prompt", lines=3)
105
- file_in = gr.File(label="Reference file")
106
- image_in = gr.Image(label="Design image")
107
- url_site = gr.Textbox(label="Website URL")
108
- search_chk = gr.Checkbox(label="Enable Web Search")
109
- language_dd = gr.Dropdown(choices=["html", "python", "transformers.js"], value="html", label="Language")
110
- model_dd = gr.Dropdown(choices=[m['name'] for m in AVAILABLE_MODELS], value=AVAILABLE_MODELS[0]['name'], label="Model")
111
- gen_btn = gr.Button("Generate")
112
- clr_btn = gr.Button("Clear")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  with gr.Column():
115
  with gr.Tabs():
116
- with gr.Tab("Code"):
117
- code_out = gr.Code(label="Generated Code")
118
- with gr.Tab("Preview"):
119
  preview_out = gr.HTML(label="Live Preview")
120
- with gr.Tab("History"):
121
- # FIX: The chatbot now correctly uses the modern 'messages' format.
122
- chat_out = gr.Chatbot(label="History", type="messages")
123
-
124
- # Events
125
- load_btn.click(
126
- fn=lambda u: load_project_from_url(u),
127
- inputs=[url_in],
128
- outputs=[load_status, code_out, preview_out, url_in, history_state, chat_out]
129
- )
130
-
131
- def on_model_change(name: str) -> str:
132
- for m in AVAILABLE_MODELS:
133
- if m['name'] == name:
134
- return m['id']
135
- return AVAILABLE_MODELS[0]['id']
136
-
137
- model_dd.change(fn=on_model_change, inputs=[model_dd], outputs=[model_state])
138
-
139
- gen_btn.click(
140
- fn=generation_code,
141
- # FIX: The 'inputs' list now only contains Gradio components.
142
- # The 'hf_token' is passed automatically by Gradio because it's
143
- # in the function's signature.
144
- inputs=[
145
- prompt_in, image_in, file_in, url_site,
146
- setting_state, history_state, model_state,
147
- search_chk, language_dd, gr.State('auto')
148
- ],
149
- outputs=[code_out, history_state, preview_out, chat_out]
150
- )
151
-
152
- clr_btn.click(fn=lambda: ([], [], "", []), outputs=[history_state, chat_out, preview_out, code_out])
 
 
 
 
 
 
 
153
 
154
  if __name__ == '__main__':
155
- # FIX: The launch() method is now correct, without any extra arguments.
156
  demo.queue().launch()
 
1
+ """
2
+ app.py
3
+
4
+ Main application file for AnyCoder, a Gradio-based AI code generation tool.
5
+
6
+ This application provides a user interface for generating code in various languages
7
+ using different AI models. It supports inputs from text prompts, files, images,
8
+ and websites, and includes features like web search enhancement and live code previews.
9
+
10
+ Structure:
11
+ - Imports & Configuration: Loads necessary libraries and constants.
12
+ - Helper Functions: Small utility functions supporting the UI logic.
13
+ - Core Application Logic: The main `generation_code` function that handles the AI interaction.
14
+ - UI Layout: Defines the Gradio interface using `gr.Blocks`.
15
+ - Event Wiring: Connects UI components to backend functions.
16
+ - Application Entry Point: Launches the Gradio app.
17
+ """
18
+
19
  import gradio as gr
20
+ from typing import Optional, Dict, List, Tuple, Any
21
 
22
+ # --- Local Module Imports ---
23
+ # These modules contain the application's configuration, clients, and utility functions.
24
+ from constants import SYSTEM_PROMPTS, AVAILABLE_MODELS, DEMO_LIST
25
  from hf_client import get_inference_client
26
  from tavily_search import enhance_query_with_search
27
  from utils import (
 
36
  )
37
  from deploy import send_to_sandbox, load_project_from_url
38
 
39
+ # --- Type Aliases for Readability ---
40
  History = List[Tuple[str, str]]
41
+ Model = Dict[str, Any]
42
+
43
+
44
+ # ==============================================================================
45
+ # HELPER FUNCTIONS
46
+ # ==============================================================================
47
+
48
+ def get_model_details(model_name: str) -> Optional[Model]:
49
+ """Finds the full dictionary for a model given its name."""
50
+ for model in AVAILABLE_MODELS:
51
+ if model["name"] == model_name:
52
+ return model
53
+ return None
54
+
55
+
56
+ # ==============================================================================
57
+ # CORE APPLICATION LOGIC
58
+ # ==============================================================================
59
 
 
 
 
60
  def generation_code(
61
  query: Optional[str],
 
62
  file: Optional[str],
63
  website_url: Optional[str],
64
+ current_model: Model,
 
 
65
  enable_search: bool,
66
  language: str,
67
+ history: Optional[History],
68
+ hf_token: str,
69
  ) -> Tuple[str, History, str, List[Dict[str, str]]]:
70
+ """
71
+ The main function to handle a user's code generation request.
72
+
73
+ Args:
74
+ query: The user's text prompt.
75
+ file: An uploaded file for context.
76
+ website_url: A URL to scrape for context.
77
+ current_model: The dictionary of the currently selected AI model.
78
+ enable_search: Flag to enable web search for query enhancement.
79
+ language: The target programming language.
80
+ history: The existing conversation history.
81
+ hf_token: The logged-in user's Hugging Face token for billing.
82
+
83
+ Returns:
84
+ A tuple containing the generated code, updated history, preview HTML,
85
+ and formatted chatbot messages.
86
+ """
87
+ # 1. --- Initialization and Input Sanitization ---
88
+ query = query or ""
89
+ history = history or []
90
+
91
+ try:
92
+ # 2. --- System Prompt and Model Selection ---
93
+ system_prompt = SYSTEM_PROMPTS.get(language, SYSTEM_PROMPTS["default"])
94
+ model_id = current_model["id"]
95
+ provider = current_model["provider"]
96
+
97
+ # 3. --- Assemble Full Context for the AI ---
98
+ messages = history_to_messages(history, system_prompt)
99
+ context_query = query
100
+
101
+ if file:
102
+ text = extract_text_from_file(file)
103
+ context_query += f"\n\n[Attached File Content]\n{text[:5000]}"
104
+
105
+ if website_url:
106
+ text = extract_website_content(website_url)
107
+ if not text.startswith('Error'):
108
+ context_query += f"\n\n[Scraped Website Content]\n{text[:8000]}"
109
+
110
+ final_query = enhance_query_with_search(context_query, enable_search)
111
+ messages.append({'role': 'user', 'content': final_query})
112
+
113
+ # 4. --- AI Model Inference with Robust Error Handling ---
114
+ client = get_inference_client(model_id, provider, user_token=hf_token)
115
+ resp = client.chat.completions.create(
116
+ model=model_id,
117
+ messages=messages,
118
+ max_tokens=16384, # Increased token limit for complex code
119
+ temperature=0.1 # Low temperature for more predictable, stable code
120
+ )
121
+ content = resp.choices[0].message.content
122
+
123
+ except Exception as e:
124
+ # If the API call fails, show a user-friendly error in the chat.
125
+ error_message = f"❌ **An error occurred:**\n\n```\n{str(e)}\n```\n\nPlease check your API keys, model selection, or try again."
126
+ history.append((query, error_message))
127
+ return "", history, "", history_to_chatbot_messages(history)
128
+
129
+ # 5. --- Post-process the AI's Output ---
130
  if language == 'transformers.js':
131
  files = parse_transformers_js_output(content)
132
  code_str = format_transformers_js_output(files)
133
+ preview_html = send_to_sandbox(files.get('index.html', ''))
134
  else:
135
+ clean_code = remove_code_block(content)
136
+ if history and history[-1][1] not in (None, ""):
137
+ # Apply search/replace if a previous turn exists
138
+ code_str = apply_search_replace_changes(history[-1][1], clean_code)
139
+ else:
140
+ code_str = clean_code
141
+ preview_html = send_to_sandbox(code_str) if language == 'html' else ''
142
+
143
+ # 6. --- Update History and Final Outputs ---
144
+ updated_history = history + [(query, code_str)]
145
+ chat_messages = history_to_chatbot_messages(updated_history)
146
 
147
+ return code_str, updated_history, preview_html, chat_messages
 
 
148
 
 
149
 
150
+ # ==============================================================================
151
+ # UI LAYOUT
152
+ # ==============================================================================
153
+
154
+ with gr.Blocks(theme=gr.themes.Soft(), title="AnyCoder - AI Code Generator") as demo:
155
+ # --- State Management ---
156
+ # Using gr.State to hold non-visible data like conversation history
157
+ # and the full dictionary of the selected model.
158
  history_state = gr.State([])
159
+ # Initialize with the first model from our constants list
160
+ initial_model = AVAILABLE_MODELS[0]
161
+ model_state = gr.State(initial_model)
162
 
163
+ # --- UI Definition ---
164
  with gr.Sidebar():
165
+ gr.Markdown("## πŸš€ AnyCoder AI")
166
+ gr.Markdown("Your personal AI partner for generating, modifying, and understanding code.")
167
+
168
+ # Group models by category for a better user experience
169
+ model_choices = {}
170
+ for model in AVAILABLE_MODELS:
171
+ category = model.get("category", "Other")
172
+ if category not in model_choices:
173
+ model_choices[category] = []
174
+ model_choices[category].append(model["name"])
175
+
176
+ model_dd = gr.Dropdown(
177
+ choices=list(model_choices.values()),
178
+ value=initial_model["name"],
179
+ label="πŸ€– Select AI Model",
180
+ info="Different models have different strengths. Experiment!"
181
+ )
182
+
183
+ with gr.Accordion("πŸ› οΈ Inputs & Context", open=True):
184
+ prompt_in = gr.Textbox(label="Prompt", lines=3, placeholder="e.g., 'Create a dark-themed login form with a spinning loader.'")
185
+ file_in = gr.File(label="πŸ“Ž Attach File (Optional)", type="filepath")
186
+ url_site = gr.Textbox(label="🌐 Scrape Website (Optional)", placeholder="https://example.com")
187
+
188
+ with gr.Accordion("βš™οΈ Settings", open=False):
189
+ language_dd = gr.Dropdown(
190
+ choices=["html", "python", "transformers.js", "sql", "javascript", "css"],
191
+ value="html",
192
+ label="🎯 Target Language"
193
+ )
194
+ search_chk = gr.Checkbox(label="🧠 Enable Web Search", info="Enhances the AI's knowledge with real-time information.")
195
+
196
+ with gr.Row():
197
+ gen_btn = gr.Button("Generate Code", variant="primary", scale=2)
198
+ clr_btn = gr.Button("Clear", variant="secondary", scale=1)
199
 
200
  with gr.Column():
201
  with gr.Tabs():
202
+ with gr.Tab("πŸ’» Code", id="code_tab"):
203
+ code_out = gr.Code(label="Generated Code", language="html")
204
+ with gr.Tab("πŸ‘οΈ Live Preview", id="preview_tab"):
205
  preview_out = gr.HTML(label="Live Preview")
206
+ with gr.Tab("πŸ“œ History", id="history_tab"):
207
+ chat_out = gr.Chatbot(label="Conversation History", type="messages", bubble_full_width=False)
208
+
209
+
210
+ # ==============================================================================
211
+ # EVENT WIRING
212
+ # ==============================================================================
213
+
214
+ # Update the model_state when the user selects a new model from the dropdown.
215
+ def on_model_change(model_name: str) -> Dict:
216
+ model_details = get_model_details(model_name)
217
+ return model_details or initial_model
218
+ model_dd.change(fn=on_model_change, inputs=[model_dd], outputs=[model_state])
219
+
220
+ # Update the syntax highlighting when the language changes.
221
+ language_dd.change(fn=lambda lang: gr.Code(language=lang), inputs=[language_dd], outputs=[code_out])
222
+
223
+ # The main event listener for the "Generate" button.
224
+ gen_btn.click(
225
+ fn=generation_code,
226
+ # Note: `hf_token` is passed automatically by Gradio and is not listed here.
227
+ inputs=[
228
+ prompt_in, file_in, url_site,
229
+ model_state, search_chk, language_dd, history_state
230
+ ],
231
+ outputs=[code_out, history_state, preview_out, chat_out]
232
+ )
233
+
234
+ # Clear button functionality to reset the interface.
235
+ def clear_session():
236
+ return "", [], "", [], None, ""
237
+ clr_btn.click(
238
+ fn=clear_session,
239
+ outputs=[prompt_in, history_state, preview_out, chat_out, file_in, url_site]
240
+ )
241
+
242
+
243
+ # ==============================================================================
244
+ # APPLICATION ENTRY POINT
245
+ # ==============================================================================
246
 
247
  if __name__ == '__main__':
248
+ # Launch the Gradio app with queuing enabled for handling multiple users.
249
  demo.queue().launch()