Update app.py
Browse files
app.py
CHANGED
@@ -1,27 +1,25 @@
|
|
1 |
# app.py
|
2 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
3 |
"""
|
4 |
-
AnyCoderΒ /Β ShashaΒ AI β
|
5 |
-
|
6 |
-
β’
|
7 |
-
β’
|
8 |
-
β’
|
9 |
-
β’
|
10 |
-
β’ Generate code & liveβpreview HTML
|
11 |
"""
|
12 |
|
13 |
from __future__ import annotations
|
14 |
|
15 |
-
from
|
16 |
-
from typing import List, Tuple, Dict, Any, Optional
|
17 |
|
18 |
import gradio as gr
|
19 |
|
20 |
-
# ββ local
|
21 |
-
from models
|
22 |
-
from inference
|
23 |
from tavily_search import enhance_query_with_search
|
24 |
-
from utils
|
25 |
extract_text_from_file,
|
26 |
extract_website_content,
|
27 |
history_to_messages,
|
@@ -31,7 +29,7 @@ from utils import (
|
|
31 |
parse_transformers_js_output,
|
32 |
format_transformers_js_output,
|
33 |
)
|
34 |
-
from deploy
|
35 |
|
36 |
# ββ constants βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
37 |
SUPPORTED_LANGUAGES = [
|
@@ -44,19 +42,19 @@ SUPPORTED_LANGUAGES = [
|
|
44 |
|
45 |
SYSTEM_PROMPTS = {
|
46 |
"html": (
|
47 |
-
"ONLY USE HTML, CSS AND JAVASCRIPT.
|
48 |
-
"wrapped in ```html ...```."
|
49 |
),
|
50 |
"transformers.js": (
|
51 |
-
"Generate THREE fenced blocks
|
52 |
-
"for a transformers.js webβapp."
|
53 |
),
|
54 |
}
|
55 |
|
56 |
History = List[Tuple[str, str]]
|
57 |
|
58 |
|
59 |
-
# ββ
|
60 |
def generate_code(
|
61 |
prompt: str,
|
62 |
file_path: str | None,
|
@@ -66,103 +64,103 @@ def generate_code(
|
|
66 |
language: str,
|
67 |
hist: History | None,
|
68 |
) -> Tuple[str, History, str, List[Dict[str, str]]]:
|
69 |
-
"""
|
70 |
hist = hist or []
|
71 |
prompt = (prompt or "").strip()
|
72 |
|
73 |
-
# 1Β build
|
74 |
sys_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
|
75 |
-
|
76 |
|
77 |
-
|
78 |
if file_path:
|
79 |
-
|
80 |
if website_url:
|
81 |
-
|
82 |
-
if not
|
83 |
-
|
84 |
|
85 |
-
|
86 |
-
|
87 |
|
88 |
-
# 2Β
|
89 |
model: ModelInfo = find_model(model_name) or AVAILABLE_MODELS[0]
|
90 |
try:
|
91 |
-
|
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
|
100 |
-
code
|
101 |
preview = send_to_sandbox(files.get("index.html", ""))
|
102 |
else:
|
103 |
-
cleaned = remove_code_block(
|
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 |
-
|
111 |
-
return code, hist, preview,
|
112 |
|
113 |
|
114 |
-
# ββ UI
|
115 |
THEME = gr.themes.Soft(primary_hue="indigo")
|
116 |
-
|
117 |
-
body {
|
118 |
-
#
|
119 |
-
#subtitle
|
120 |
"""
|
121 |
|
122 |
-
with gr.Blocks(title="AnyCoderΒ AI"
|
123 |
state_hist: gr.State[History] = gr.State([])
|
124 |
|
125 |
-
gr.Markdown("## π
|
126 |
gr.Markdown("Your AI partner for generating, modifying & understanding code.", elem_id="subtitle")
|
127 |
|
128 |
with gr.Row():
|
129 |
-
#
|
130 |
with gr.Column(scale=1):
|
131 |
-
gr.Markdown("#### 1
|
132 |
model_dd = gr.Dropdown(
|
133 |
choices=[m.name for m in AVAILABLE_MODELS],
|
134 |
value=AVAILABLE_MODELS[0].name,
|
135 |
-
label="AI
|
136 |
)
|
137 |
|
138 |
-
gr.Markdown("#### 2
|
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
|
148 |
lang_dd = gr.Dropdown(SUPPORTED_LANGUAGES, value="html", label="TargetΒ Language")
|
149 |
-
search_ck = gr.Checkbox(label="Enable
|
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 |
-
#
|
156 |
with gr.Column(scale=2):
|
157 |
with gr.Tabs():
|
158 |
with gr.Tab("Code"):
|
159 |
-
code_out
|
160 |
-
with gr.Tab("Live
|
161 |
preview_out = gr.HTML()
|
162 |
with gr.Tab("History"):
|
163 |
-
chat_out
|
164 |
|
165 |
-
#
|
166 |
gen_btn.click(
|
167 |
generate_code,
|
168 |
inputs=[prompt_box, file_box, url_box, model_dd, search_ck, lang_dd, state_hist],
|
|
|
1 |
# app.py
|
2 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
3 |
"""
|
4 |
+
AnyCoderΒ /Β ShashaΒ AI β singleβfile Gradio interface
|
5 |
+
β’ Pick a model (registry in models.py)
|
6 |
+
β’ Give context (prompt, file upload, or website URL)
|
7 |
+
β’ Choose from 25+ target languages
|
8 |
+
β’ Optional Tavily webβsearch enrichment
|
9 |
+
β’ Generate code, preview HTML, see conversation history
|
|
|
10 |
"""
|
11 |
|
12 |
from __future__ import annotations
|
13 |
|
14 |
+
from typing import List, Tuple, Dict, Any
|
|
|
15 |
|
16 |
import gradio as gr
|
17 |
|
18 |
+
# ββ local modules βββββββββββββββββββββββββββββββββββββββββββββββ
|
19 |
+
from models import AVAILABLE_MODELS, find_model, ModelInfo
|
20 |
+
from inference import chat_completion
|
21 |
from tavily_search import enhance_query_with_search
|
22 |
+
from utils import (
|
23 |
extract_text_from_file,
|
24 |
extract_website_content,
|
25 |
history_to_messages,
|
|
|
29 |
parse_transformers_js_output,
|
30 |
format_transformers_js_output,
|
31 |
)
|
32 |
+
from deploy import send_to_sandbox
|
33 |
|
34 |
# ββ constants βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
35 |
SUPPORTED_LANGUAGES = [
|
|
|
42 |
|
43 |
SYSTEM_PROMPTS = {
|
44 |
"html": (
|
45 |
+
"ONLY USE HTML, CSS AND JAVASCRIPT. "
|
46 |
+
"Return exactly one complete HTML page wrapped in ```html ...```."
|
47 |
),
|
48 |
"transformers.js": (
|
49 |
+
"Generate THREE fenced blocks: "
|
50 |
+
"`index.html`, `index.js`, and `style.css` for a transformers.js webβapp."
|
51 |
),
|
52 |
}
|
53 |
|
54 |
History = List[Tuple[str, str]]
|
55 |
|
56 |
|
57 |
+
# ββ backβend callback βββββββββββββββββββββββββββββββββββββββββββ
|
58 |
def generate_code(
|
59 |
prompt: str,
|
60 |
file_path: str | None,
|
|
|
64 |
language: str,
|
65 |
hist: History | None,
|
66 |
) -> Tuple[str, History, str, List[Dict[str, str]]]:
|
67 |
+
"""Runs on **Generate Code** click."""
|
68 |
hist = hist or []
|
69 |
prompt = (prompt or "").strip()
|
70 |
|
71 |
+
# 1Β build message list
|
72 |
sys_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
|
73 |
+
msgs = history_to_messages(hist, sys_prompt)
|
74 |
|
75 |
+
ctx: List[str] = [prompt] if prompt else []
|
76 |
if file_path:
|
77 |
+
ctx += ["[File]", extract_text_from_file(file_path)[:5000]]
|
78 |
if website_url:
|
79 |
+
site_html = extract_website_content(website_url)
|
80 |
+
if not site_html.startswith("Error"):
|
81 |
+
ctx += ["[Website]", site_html[:8000]]
|
82 |
|
83 |
+
user_query = enhance_query_with_search("\n\n".join(ctx), enable_search)
|
84 |
+
msgs.append({"role": "user", "content": user_query})
|
85 |
|
86 |
+
# 2Β call model through inference.py
|
87 |
model: ModelInfo = find_model(model_name) or AVAILABLE_MODELS[0]
|
88 |
try:
|
89 |
+
raw = chat_completion(model.id, msgs)
|
90 |
except Exception as exc: # pragma: no cover
|
91 |
err = f"βΒ **Error**\n```{exc}```"
|
92 |
hist.append((prompt, err))
|
93 |
return "", hist, "", history_to_chatbot_messages(hist)
|
94 |
|
95 |
+
# 3Β postβprocess response
|
96 |
if language == "transformers.js":
|
97 |
+
files = parse_transformers_js_output(raw)
|
98 |
+
code = format_transformers_js_output(files)
|
99 |
preview = send_to_sandbox(files.get("index.html", ""))
|
100 |
else:
|
101 |
+
cleaned = remove_code_block(raw)
|
102 |
if hist and not hist[-1][1].startswith("β"):
|
103 |
cleaned = apply_search_replace_changes(hist[-1][1], cleaned)
|
104 |
code = cleaned
|
105 |
preview = send_to_sandbox(cleaned) if language == "html" else ""
|
106 |
|
107 |
hist.append((prompt, code))
|
108 |
+
chat_display = history_to_chatbot_messages(hist)
|
109 |
+
return code, hist, preview, chat_display
|
110 |
|
111 |
|
112 |
+
# ββ Gradio UI βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
113 |
THEME = gr.themes.Soft(primary_hue="indigo")
|
114 |
+
CSS = """
|
115 |
+
body {font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif}
|
116 |
+
#title {text-align:center;font-size:2.3rem;margin-top:1rem}
|
117 |
+
#subtitle {text-align:center;color:#55606d;margin-bottom:2rem}
|
118 |
"""
|
119 |
|
120 |
+
with gr.Blocks(theme=THEME, css=CSS, title="AnyCoderΒ AI") as demo:
|
121 |
state_hist: gr.State[History] = gr.State([])
|
122 |
|
123 |
+
gr.Markdown("## πΒ AnyCoderΒ AI", elem_id="title")
|
124 |
gr.Markdown("Your AI partner for generating, modifying & understanding code.", elem_id="subtitle")
|
125 |
|
126 |
with gr.Row():
|
127 |
+
# ββ sidebar (inputs)
|
128 |
with gr.Column(scale=1):
|
129 |
+
gr.Markdown("#### 1Β Β·Β Model")
|
130 |
model_dd = gr.Dropdown(
|
131 |
choices=[m.name for m in AVAILABLE_MODELS],
|
132 |
value=AVAILABLE_MODELS[0].name,
|
133 |
+
label="AI Model",
|
134 |
)
|
135 |
|
136 |
+
gr.Markdown("#### 2Β Β·Β Context")
|
137 |
with gr.Tabs():
|
138 |
with gr.Tab("Prompt"):
|
139 |
+
prompt_box = gr.Textbox(lines=6, placeholder="Describe what you want to buildβ¦")
|
140 |
with gr.Tab("File"):
|
141 |
file_box = gr.File(type="filepath")
|
142 |
with gr.Tab("Website"):
|
143 |
url_box = gr.Textbox(placeholder="https://example.com")
|
144 |
|
145 |
+
gr.Markdown("#### 3Β Β·Β Output")
|
146 |
lang_dd = gr.Dropdown(SUPPORTED_LANGUAGES, value="html", label="TargetΒ Language")
|
147 |
+
search_ck = gr.Checkbox(label="Enable Tavily WebΒ Search")
|
148 |
|
149 |
with gr.Row():
|
150 |
clear_btn = gr.Button("Clear Session", variant="secondary")
|
151 |
gen_btn = gr.Button("GenerateΒ Code", variant="primary")
|
152 |
|
153 |
+
# ββ main panel (outputs)
|
154 |
with gr.Column(scale=2):
|
155 |
with gr.Tabs():
|
156 |
with gr.Tab("Code"):
|
157 |
+
code_out = gr.Code(interactive=True, label=None)
|
158 |
+
with gr.Tab("Live Preview"):
|
159 |
preview_out = gr.HTML()
|
160 |
with gr.Tab("History"):
|
161 |
+
chat_out = gr.Chatbot(type="messages")
|
162 |
|
163 |
+
# wiring
|
164 |
gen_btn.click(
|
165 |
generate_code,
|
166 |
inputs=[prompt_box, file_box, url_box, model_dd, search_ck, lang_dd, state_hist],
|