Update app.py
Browse files
app.py
CHANGED
@@ -1,140 +1,180 @@
|
|
1 |
# app.py
|
2 |
-
#
|
3 |
"""
|
4 |
-
AnyCoderΒ /Β ShashaΒ AI β Gradio
|
5 |
|
6 |
-
β’
|
7 |
-
|
8 |
-
β’
|
9 |
-
|
10 |
-
|
11 |
-
All heavy lifting (model registry, provider routing, webβsearch, etc.) lives in
|
12 |
-
β’ models.py, inference.py, utils.py, deploy.py β¦
|
13 |
"""
|
14 |
|
|
|
|
|
15 |
from pathlib import Path
|
16 |
-
from typing import List, Tuple, Dict
|
17 |
|
18 |
import gradio as gr
|
19 |
|
20 |
-
# ββ
|
21 |
-
from
|
|
|
22 |
from tavily_search import enhance_query_with_search
|
23 |
-
from
|
24 |
-
from models import AVAILABLE_MODELS, find_model, ModelInfo
|
25 |
-
from utils import (
|
26 |
extract_text_from_file,
|
27 |
extract_website_content,
|
28 |
history_to_messages,
|
|
|
29 |
apply_search_replace_changes,
|
30 |
remove_code_block,
|
31 |
parse_transformers_js_output,
|
32 |
format_transformers_js_output,
|
33 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
|
35 |
-
# ββ System prompts keyed by language ββββββββββββββββββββββββββββββββββββββββ
|
36 |
SYSTEM_PROMPTS = {
|
37 |
"html": (
|
38 |
-
"ONLY USE HTML, CSS AND JAVASCRIPT.
|
39 |
-
"```html ...```."
|
40 |
),
|
41 |
"transformers.js": (
|
42 |
-
"Generate THREE
|
43 |
-
"
|
44 |
),
|
45 |
}
|
46 |
|
47 |
-
|
48 |
-
History = List[Tuple[str, str]] #Β [(user_query, generated_code), β¦]
|
49 |
|
50 |
-
|
51 |
-
#
|
52 |
-
|
53 |
-
def generate(
|
54 |
prompt: str,
|
55 |
file_path: str | None,
|
56 |
website_url: str | None,
|
57 |
-
|
|
|
58 |
language: str,
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
"""
|
65 |
-
history = history or []
|
66 |
-
|
67 |
-
# ---- Build system + user messages --------------------------------------
|
68 |
-
sys_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
|
69 |
-
messages = history_to_messages(history, sys_prompt)
|
70 |
|
71 |
-
|
|
|
|
|
72 |
|
|
|
73 |
if file_path:
|
74 |
-
|
75 |
-
ctx.append(extract_text_from_file(file_path)[:5_000])
|
76 |
-
|
77 |
if website_url:
|
78 |
html = extract_website_content(website_url)
|
79 |
if not html.startswith("Error"):
|
80 |
-
|
81 |
-
ctx.append(html[:8_000])
|
82 |
|
83 |
-
|
84 |
-
|
85 |
-
messages.append({"role": "user", "content": user_query})
|
86 |
|
87 |
-
#
|
88 |
-
model: ModelInfo = find_model(
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
90 |
|
91 |
-
#
|
92 |
if language == "transformers.js":
|
93 |
-
files = parse_transformers_js_output(
|
94 |
code = format_transformers_js_output(files)
|
|
|
95 |
else:
|
96 |
-
|
97 |
-
if
|
98 |
-
|
99 |
-
code
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
#
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
)
|
137 |
|
138 |
-
# ---------------------------------------------------------------------------
|
139 |
if __name__ == "__main__":
|
140 |
demo.queue().launch()
|
|
|
1 |
# app.py
|
2 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
3 |
"""
|
4 |
+
AnyCoderΒ /Β ShashaΒ AI β lightweight Gradio frontβend
|
5 |
|
6 |
+
β’ Pick an AI model from models.py β AVAILABLE_MODELS
|
7 |
+
β’ Provide context (prompt / file / website)
|
8 |
+
β’ Choose a target language from 25+ options
|
9 |
+
β’ Optional Tavily webβsearch enrichment
|
10 |
+
β’ Generate code & liveβpreview HTML
|
|
|
|
|
11 |
"""
|
12 |
|
13 |
+
from __future__ import annotations
|
14 |
+
|
15 |
from pathlib import Path
|
16 |
+
from typing import List, Tuple, Dict, Any, Optional
|
17 |
|
18 |
import gradio as gr
|
19 |
|
20 |
+
# ββ local helpers βββββββββββββββββββββββββββββββββββββββββββββββ
|
21 |
+
from models import AVAILABLE_MODELS, find_model, ModelInfo
|
22 |
+
from inference import chat_completion
|
23 |
from tavily_search import enhance_query_with_search
|
24 |
+
from utils import (
|
|
|
|
|
25 |
extract_text_from_file,
|
26 |
extract_website_content,
|
27 |
history_to_messages,
|
28 |
+
history_to_chatbot_messages,
|
29 |
apply_search_replace_changes,
|
30 |
remove_code_block,
|
31 |
parse_transformers_js_output,
|
32 |
format_transformers_js_output,
|
33 |
)
|
34 |
+
from deploy import send_to_sandbox
|
35 |
+
|
36 |
+
# ββ constants βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
37 |
+
SUPPORTED_LANGUAGES = [
|
38 |
+
"python", "c", "cpp", "markdown", "latex", "json", "html", "css",
|
39 |
+
"javascript", "jinja2", "typescript", "yaml", "dockerfile", "shell",
|
40 |
+
"r", "sql", "sql-msSQL", "sql-mySQL", "sql-mariaDB", "sql-sqlite",
|
41 |
+
"sql-cassandra", "sql-plSQL", "sql-hive", "sql-pgSQL", "sql-gql",
|
42 |
+
"sql-gpSQL", "sql-sparkSQL", "sql-esper",
|
43 |
+
]
|
44 |
|
|
|
45 |
SYSTEM_PROMPTS = {
|
46 |
"html": (
|
47 |
+
"ONLY USE HTML, CSS AND JAVASCRIPT. Produce ONE complete HTML file "
|
48 |
+
"wrapped in ```html ...```."
|
49 |
),
|
50 |
"transformers.js": (
|
51 |
+
"Generate THREE fenced blocks (index.html / index.js / style.css) "
|
52 |
+
"for a transformers.js webβapp."
|
53 |
),
|
54 |
}
|
55 |
|
56 |
+
History = List[Tuple[str, str]]
|
|
|
57 |
|
58 |
+
|
59 |
+
# ββ core callback βββββββββββββββββββββββββββββββββββββββββββββββ
|
60 |
+
def generate_code(
|
|
|
61 |
prompt: str,
|
62 |
file_path: str | None,
|
63 |
website_url: str | None,
|
64 |
+
model_name: str,
|
65 |
+
enable_search: bool,
|
66 |
language: str,
|
67 |
+
hist: History | None,
|
68 |
+
) -> Tuple[str, History, str, List[Dict[str, str]]]:
|
69 |
+
"""Backβend for the βGenerate Codeβ button."""
|
70 |
+
hist = hist or []
|
71 |
+
prompt = (prompt or "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
+
# 1Β build messages
|
74 |
+
sys_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
|
75 |
+
messages = history_to_messages(hist, sys_prompt)
|
76 |
|
77 |
+
ctx_parts: list[str] = [prompt]
|
78 |
if file_path:
|
79 |
+
ctx_parts += ["[File]", extract_text_from_file(file_path)[:5000]]
|
|
|
|
|
80 |
if website_url:
|
81 |
html = extract_website_content(website_url)
|
82 |
if not html.startswith("Error"):
|
83 |
+
ctx_parts += ["[Website]", html[:8000]]
|
|
|
84 |
|
85 |
+
user_msg = enhance_query_with_search("\n\n".join(ctx_parts), enable_search)
|
86 |
+
messages.append({"role": "user", "content": user_msg})
|
|
|
87 |
|
88 |
+
# 2Β run model (provider selection handled in inference.chat_completion)
|
89 |
+
model: ModelInfo = find_model(model_name) or AVAILABLE_MODELS[0]
|
90 |
+
try:
|
91 |
+
raw_out = chat_completion(model.id, messages)
|
92 |
+
except Exception as exc: # pragma: no cover
|
93 |
+
err = f"βΒ **Error**\n```{exc}```"
|
94 |
+
hist.append((prompt, err))
|
95 |
+
return "", hist, "", history_to_chatbot_messages(hist)
|
96 |
|
97 |
+
# 3Β postβprocess
|
98 |
if language == "transformers.js":
|
99 |
+
files = parse_transformers_js_output(raw_out)
|
100 |
code = format_transformers_js_output(files)
|
101 |
+
preview = send_to_sandbox(files.get("index.html", ""))
|
102 |
else:
|
103 |
+
cleaned = remove_code_block(raw_out)
|
104 |
+
if hist and not hist[-1][1].startswith("β"):
|
105 |
+
cleaned = apply_search_replace_changes(hist[-1][1], cleaned)
|
106 |
+
code = cleaned
|
107 |
+
preview = send_to_sandbox(cleaned) if language == "html" else ""
|
108 |
+
|
109 |
+
hist.append((prompt, code))
|
110 |
+
chat_view = history_to_chatbot_messages(hist)
|
111 |
+
return code, hist, preview, chat_view
|
112 |
+
|
113 |
+
|
114 |
+
# ββ UI ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
115 |
+
THEME = gr.themes.Soft(primary_hue="indigo")
|
116 |
+
custom_css = """
|
117 |
+
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
|
118 |
+
#main_title { text-align:center;font-size:2.4rem;margin-top:1rem }
|
119 |
+
#subtitle { text-align:center;color:#5a6475;margin-bottom:2rem }
|
120 |
+
"""
|
121 |
+
|
122 |
+
with gr.Blocks(title="AnyCoderΒ AI", theme=THEME, css=custom_css) as demo:
|
123 |
+
state_hist: gr.State[History] = gr.State([])
|
124 |
+
|
125 |
+
gr.Markdown("## πβ―AnyCoderΒ AI", elem_id="main_title")
|
126 |
+
gr.Markdown("Your AI partner for generating, modifying & understanding code.", elem_id="subtitle")
|
127 |
+
|
128 |
+
with gr.Row():
|
129 |
+
# ββββββββββ inputs (sidebar) ββββββββββ
|
130 |
+
with gr.Column(scale=1):
|
131 |
+
gr.Markdown("#### 1β―Β·β―Selectβ―Model")
|
132 |
+
model_dd = gr.Dropdown(
|
133 |
+
choices=[m.name for m in AVAILABLE_MODELS],
|
134 |
+
value=AVAILABLE_MODELS[0].name,
|
135 |
+
label="AIΒ Model",
|
136 |
+
)
|
137 |
+
|
138 |
+
gr.Markdown("#### 2β―Β·β―Provideβ―Context")
|
139 |
+
with gr.Tabs():
|
140 |
+
with gr.Tab("Prompt"):
|
141 |
+
prompt_box = gr.Textbox(lines=6, placeholder="Describe what you wantβ¦")
|
142 |
+
with gr.Tab("File"):
|
143 |
+
file_box = gr.File(type="filepath")
|
144 |
+
with gr.Tab("Website"):
|
145 |
+
url_box = gr.Textbox(placeholder="https://example.com")
|
146 |
+
|
147 |
+
gr.Markdown("#### 3β―Β·β―Configureβ―Output")
|
148 |
+
lang_dd = gr.Dropdown(SUPPORTED_LANGUAGES, value="html", label="TargetΒ Language")
|
149 |
+
search_ck = gr.Checkbox(label="EnableΒ TavilyΒ WebΒ Search")
|
150 |
+
|
151 |
+
with gr.Row():
|
152 |
+
clear_btn = gr.Button("Clear Session", variant="secondary")
|
153 |
+
gen_btn = gr.Button("GenerateΒ Code", variant="primary")
|
154 |
+
|
155 |
+
# ββββββββββ outputs (main panel) βββββ
|
156 |
+
with gr.Column(scale=2):
|
157 |
+
with gr.Tabs():
|
158 |
+
with gr.Tab("Code"):
|
159 |
+
code_out = gr.Code(interactive=True)
|
160 |
+
with gr.Tab("Liveβ―Preview"):
|
161 |
+
preview_out = gr.HTML()
|
162 |
+
with gr.Tab("History"):
|
163 |
+
chat_out = gr.Chatbot(type="messages")
|
164 |
+
|
165 |
+
# ββ wiring βββββββββββββββββββββββββββββββββββββββββββ
|
166 |
+
gen_btn.click(
|
167 |
+
generate_code,
|
168 |
+
inputs=[prompt_box, file_box, url_box, model_dd, search_ck, lang_dd, state_hist],
|
169 |
+
outputs=[code_out, state_hist, preview_out, chat_out],
|
170 |
+
)
|
171 |
+
|
172 |
+
clear_btn.click(
|
173 |
+
lambda: ("", None, "", "html", False, [], [], "", ""),
|
174 |
+
outputs=[prompt_box, file_box, url_box, lang_dd, search_ck,
|
175 |
+
state_hist, code_out, preview_out, chat_out],
|
176 |
+
queue=False,
|
177 |
)
|
178 |
|
|
|
179 |
if __name__ == "__main__":
|
180 |
demo.queue().launch()
|