Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,27 @@
|
|
1 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import gradio as gr
|
|
|
3 |
|
4 |
-
|
|
|
|
|
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
|
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 |
-
|
31 |
-
_history: Optional[History],
|
32 |
-
_current_model_name: str,
|
33 |
enable_search: bool,
|
34 |
language: str,
|
35 |
-
|
36 |
-
hf_token: str
|
37 |
) -> Tuple[str, History, str, List[Dict[str, str]]]:
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
78 |
else:
|
79 |
-
|
80 |
-
if
|
81 |
-
|
82 |
-
|
83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
|
85 |
-
|
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 |
-
#
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
94 |
history_state = gr.State([])
|
95 |
-
|
96 |
-
|
|
|
97 |
|
|
|
98 |
with gr.Sidebar():
|
99 |
-
gr.Markdown("## AnyCoder AI")
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
model_dd = gr.Dropdown(
|
111 |
-
|
112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
153 |
|
154 |
if __name__ == '__main__':
|
155 |
-
#
|
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()
|