Update app.py
Browse files
app.py
CHANGED
@@ -1,174 +1,210 @@
|
|
1 |
-
# app.py
|
2 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
3 |
-
"""
|
4 |
-
AnyCoderΒ /Β ShashaΒ AI β Gradio interface
|
5 |
-
β’ Works with the model registry in models.py
|
6 |
-
β’ Uses inference.chat_completion for providerβaware calls
|
7 |
-
β’ Supports prompt / file / website context
|
8 |
-
β’ 25+ target languages
|
9 |
-
β’ Optional Tavily webβsearch enrichment
|
10 |
-
β’ Live HTML preview + chat history
|
11 |
"""
|
|
|
12 |
|
13 |
-
|
14 |
-
|
|
|
|
|
15 |
|
16 |
import gradio as gr
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
from
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
from tavily_search import enhance_query_with_search
|
22 |
-
from utils
|
23 |
extract_text_from_file,
|
24 |
extract_website_content,
|
|
|
25 |
history_to_messages,
|
26 |
history_to_chatbot_messages,
|
27 |
-
apply_search_replace_changes,
|
28 |
remove_code_block,
|
29 |
parse_transformers_js_output,
|
30 |
format_transformers_js_output,
|
31 |
)
|
32 |
-
from deploy
|
|
|
|
|
|
|
|
|
33 |
|
34 |
-
#
|
35 |
-
|
36 |
"python", "c", "cpp", "markdown", "latex", "json", "html", "css",
|
37 |
"javascript", "jinja2", "typescript", "yaml", "dockerfile", "shell",
|
38 |
"r", "sql", "sql-msSQL", "sql-mySQL", "sql-mariaDB", "sql-sqlite",
|
39 |
"sql-cassandra", "sql-plSQL", "sql-hive", "sql-pgSQL", "sql-gql",
|
40 |
-
"sql-gpSQL", "sql-sparkSQL", "sql-esper"
|
41 |
]
|
42 |
|
43 |
-
|
44 |
-
|
45 |
-
"
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
History = List[Tuple[str, str]]
|
55 |
-
|
56 |
-
# ββ backend callback ββββββββββββββββββββββββββββββββββββββββββββ
|
57 |
-
def generate(
|
58 |
-
prompt: str,
|
59 |
-
file_path: str | None,
|
60 |
-
website_url: str | None,
|
61 |
-
model_name: str,
|
62 |
enable_search: bool,
|
63 |
language: str,
|
64 |
-
history: History
|
65 |
) -> Tuple[str, History, str, List[Dict[str, str]]]:
|
66 |
-
|
67 |
history = history or []
|
68 |
-
prompt = (prompt or "").strip()
|
69 |
-
|
70 |
-
# 1Β system + conversation
|
71 |
-
sys_p = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
|
72 |
-
msgs = history_to_messages(history, sys_p)
|
73 |
-
|
74 |
-
ctx: List[str] = [prompt] if prompt else []
|
75 |
-
if file_path:
|
76 |
-
ctx += ["[File]", extract_text_from_file(file_path)[:5_000]]
|
77 |
-
if website_url:
|
78 |
-
html = extract_website_content(website_url)
|
79 |
-
if not html.startswith("Error"):
|
80 |
-
ctx += ["[Website]", html[:8_000]]
|
81 |
-
|
82 |
-
user_msg = enhance_query_with_search("\n\n".join(ctx), enable_search)
|
83 |
-
msgs.append({"role": "user", "content": user_msg})
|
84 |
-
|
85 |
-
# 2Β model call
|
86 |
-
model: ModelInfo = find_model(model_name) or AVAILABLE_MODELS[0]
|
87 |
try:
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
92 |
return "", history, "", history_to_chatbot_messages(history)
|
93 |
|
94 |
-
#
|
95 |
if language == "transformers.js":
|
96 |
-
files
|
97 |
-
code
|
98 |
preview = send_to_sandbox(files.get("index.html", ""))
|
99 |
else:
|
100 |
-
cleaned = remove_code_block(
|
101 |
-
if history and not history[-1][1].startswith("β"):
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
body{font-family
|
114 |
-
#
|
115 |
-
#subtitle{
|
|
|
|
|
116 |
"""
|
117 |
|
118 |
-
with gr.Blocks(theme=
|
119 |
-
|
|
|
|
|
120 |
|
121 |
-
gr.Markdown("
|
122 |
-
gr.Markdown("Your AI partner for generating, modifying
|
123 |
|
124 |
with gr.Row():
|
125 |
-
# ββ inputs sidebar
|
126 |
with gr.Column(scale=1):
|
127 |
-
gr.Markdown("###
|
128 |
model_dd = gr.Dropdown(
|
129 |
-
choices=[m
|
130 |
-
value=
|
131 |
-
label="AI Model"
|
132 |
)
|
133 |
|
134 |
-
gr.Markdown("###
|
135 |
with gr.Tabs():
|
136 |
-
with gr.Tab("Prompt"
|
137 |
-
|
138 |
-
with gr.Tab("File"
|
139 |
-
|
140 |
-
with gr.Tab("Website"
|
141 |
-
|
142 |
|
143 |
-
gr.Markdown("###
|
144 |
-
lang_dd
|
145 |
-
|
146 |
|
147 |
with gr.Row():
|
148 |
-
|
149 |
-
gen_btn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
150 |
|
151 |
-
# ββ outputs
|
152 |
with gr.Column(scale=2):
|
153 |
with gr.Tabs():
|
154 |
-
with gr.Tab("Code"):
|
155 |
-
code_out
|
156 |
-
with gr.Tab("Live Preview"):
|
157 |
preview_out = gr.HTML()
|
158 |
-
with gr.Tab("History"):
|
159 |
-
chat_out
|
|
|
|
|
160 |
|
161 |
-
# ββ wiring
|
162 |
gen_btn.click(
|
163 |
-
|
164 |
-
inputs=[
|
165 |
-
outputs=[code_out,
|
166 |
)
|
167 |
|
168 |
-
|
169 |
-
lambda: ("", None, "",
|
170 |
-
outputs=[
|
171 |
-
state_hist, code_out, preview_out, chat_out],
|
172 |
queue=False,
|
173 |
)
|
174 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
"""
|
2 |
+
Main application file for SHASHA AI, a Gradio-based AI code generation tool.
|
3 |
|
4 |
+
Provides a UI for generating code in many languages using various AI models.
|
5 |
+
Supports text prompts, file uploads, website scraping, optional web search,
|
6 |
+
and live previews of HTML output.
|
7 |
+
"""
|
8 |
|
9 |
import gradio as gr
|
10 |
+
from typing import Optional, Dict, List, Tuple, Any
|
11 |
+
|
12 |
+
# --- Local module imports ---
|
13 |
+
from constants import (
|
14 |
+
HTML_SYSTEM_PROMPT,
|
15 |
+
TRANSFORMERS_JS_SYSTEM_PROMPT,
|
16 |
+
AVAILABLE_MODELS,
|
17 |
+
DEMO_LIST,
|
18 |
+
)
|
19 |
+
from hf_client import get_inference_client
|
20 |
from tavily_search import enhance_query_with_search
|
21 |
+
from utils import (
|
22 |
extract_text_from_file,
|
23 |
extract_website_content,
|
24 |
+
apply_search_replace_changes,
|
25 |
history_to_messages,
|
26 |
history_to_chatbot_messages,
|
|
|
27 |
remove_code_block,
|
28 |
parse_transformers_js_output,
|
29 |
format_transformers_js_output,
|
30 |
)
|
31 |
+
from deploy import send_to_sandbox, load_project_from_url
|
32 |
+
|
33 |
+
# --- Type aliases ---
|
34 |
+
History = List[Tuple[str, str]]
|
35 |
+
Model = Dict[str, Any]
|
36 |
|
37 |
+
# --- Supported languages for dropdown ---
|
38 |
+
SUPPORTED_LANGUAGES = [
|
39 |
"python", "c", "cpp", "markdown", "latex", "json", "html", "css",
|
40 |
"javascript", "jinja2", "typescript", "yaml", "dockerfile", "shell",
|
41 |
"r", "sql", "sql-msSQL", "sql-mySQL", "sql-mariaDB", "sql-sqlite",
|
42 |
"sql-cassandra", "sql-plSQL", "sql-hive", "sql-pgSQL", "sql-gql",
|
43 |
+
"sql-gpSQL", "sql-sparkSQL", "sql-esper"
|
44 |
]
|
45 |
|
46 |
+
def get_model_details(name: str) -> Optional[Model]:
|
47 |
+
for m in AVAILABLE_MODELS:
|
48 |
+
if m["name"] == name:
|
49 |
+
return m
|
50 |
+
return None
|
51 |
+
|
52 |
+
def generation_code(
|
53 |
+
query: Optional[str],
|
54 |
+
file: Optional[str],
|
55 |
+
website_url: Optional[str],
|
56 |
+
current_model: Model,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
57 |
enable_search: bool,
|
58 |
language: str,
|
59 |
+
history: Optional[History],
|
60 |
) -> Tuple[str, History, str, List[Dict[str, str]]]:
|
61 |
+
query = query or ""
|
62 |
history = history or []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
try:
|
64 |
+
# Choose system prompt based on language
|
65 |
+
if language == "html":
|
66 |
+
system_prompt = HTML_SYSTEM_PROMPT
|
67 |
+
elif language == "transformers.js":
|
68 |
+
system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT
|
69 |
+
else:
|
70 |
+
# Generic fallback prompt
|
71 |
+
system_prompt = (
|
72 |
+
f"You are an expert {language} developer. "
|
73 |
+
f"Write clean, idiomatic {language} code based on the user's request."
|
74 |
+
)
|
75 |
+
|
76 |
+
model_id = current_model["id"]
|
77 |
+
# Determine provider
|
78 |
+
if model_id.startswith("openai/") or model_id in {"gpt-4", "gpt-3.5-turbo"}:
|
79 |
+
provider = "openai"
|
80 |
+
elif model_id.startswith("gemini/") or model_id.startswith("google/"):
|
81 |
+
provider = "gemini"
|
82 |
+
elif model_id.startswith("fireworks-ai/"):
|
83 |
+
provider = "fireworks-ai"
|
84 |
+
else:
|
85 |
+
provider = "auto"
|
86 |
+
|
87 |
+
# Build message history
|
88 |
+
msgs = history_to_messages(history, system_prompt)
|
89 |
+
context = query
|
90 |
+
if file:
|
91 |
+
ftext = extract_text_from_file(file)
|
92 |
+
context += f"\n\n[Attached file]\n{ftext[:5000]}"
|
93 |
+
if website_url:
|
94 |
+
wtext = extract_website_content(website_url)
|
95 |
+
if not wtext.startswith("Error"):
|
96 |
+
context += f"\n\n[Website content]\n{wtext[:8000]}"
|
97 |
+
final_q = enhance_query_with_search(context, enable_search)
|
98 |
+
msgs.append({"role": "user", "content": final_q})
|
99 |
+
|
100 |
+
# Call the model
|
101 |
+
client = get_inference_client(model_id, provider)
|
102 |
+
resp = client.chat.completions.create(
|
103 |
+
model=model_id,
|
104 |
+
messages=msgs,
|
105 |
+
max_tokens=16000,
|
106 |
+
temperature=0.1
|
107 |
+
)
|
108 |
+
content = resp.choices[0].message.content
|
109 |
+
|
110 |
+
except Exception as e:
|
111 |
+
err = f"β **Error:**\n```\n{e}\n```"
|
112 |
+
history.append((query, err))
|
113 |
return "", history, "", history_to_chatbot_messages(history)
|
114 |
|
115 |
+
# Process model output
|
116 |
if language == "transformers.js":
|
117 |
+
files = parse_transformers_js_output(content)
|
118 |
+
code = format_transformers_js_output(files)
|
119 |
preview = send_to_sandbox(files.get("index.html", ""))
|
120 |
else:
|
121 |
+
cleaned = remove_code_block(content)
|
122 |
+
if history and history[-1][1] and not history[-1][1].startswith("β"):
|
123 |
+
code = apply_search_replace_changes(history[-1][1], cleaned)
|
124 |
+
else:
|
125 |
+
code = cleaned
|
126 |
+
preview = send_to_sandbox(code) if language == "html" else ""
|
127 |
+
|
128 |
+
new_hist = history + [(query, code)]
|
129 |
+
chat = history_to_chatbot_messages(new_hist)
|
130 |
+
return code, new_hist, preview, chat
|
131 |
+
|
132 |
+
# --- Custom CSS ---
|
133 |
+
CUSTOM_CSS = """
|
134 |
+
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
|
135 |
+
#main_title { text-align: center; font-size: 2.5rem; margin-top: 1.5rem; }
|
136 |
+
#subtitle { text-align: center; color: #4a5568; margin-bottom: 2.5rem; }
|
137 |
+
.gradio-container { background-color: #f7fafc; }
|
138 |
+
#gen_btn { box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
|
139 |
"""
|
140 |
|
141 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), css=CUSTOM_CSS, title="Shasha AI") as demo:
|
142 |
+
history_state = gr.State([])
|
143 |
+
initial_model = AVAILABLE_MODELS[0]
|
144 |
+
model_state = gr.State(initial_model)
|
145 |
|
146 |
+
gr.Markdown("# π Shasha AI", elem_id="main_title")
|
147 |
+
gr.Markdown("Your AI partner for generating, modifying, and understanding code.", elem_id="subtitle")
|
148 |
|
149 |
with gr.Row():
|
|
|
150 |
with gr.Column(scale=1):
|
151 |
+
gr.Markdown("### 1. Select Model")
|
152 |
model_dd = gr.Dropdown(
|
153 |
+
choices=[m["name"] for m in AVAILABLE_MODELS],
|
154 |
+
value=initial_model["name"],
|
155 |
+
label="AI Model"
|
156 |
)
|
157 |
|
158 |
+
gr.Markdown("### 2. Provide Context")
|
159 |
with gr.Tabs():
|
160 |
+
with gr.Tab("π Prompt"):
|
161 |
+
prompt_in = gr.Textbox(lines=7, placeholder="Describe your request...", show_label=False)
|
162 |
+
with gr.Tab("π File"):
|
163 |
+
file_in = gr.File(type="filepath")
|
164 |
+
with gr.Tab("π Website"):
|
165 |
+
url_in = gr.Textbox(placeholder="https://example.com")
|
166 |
|
167 |
+
gr.Markdown("### 3. Configure Output")
|
168 |
+
lang_dd = gr.Dropdown(SUPPORTED_LANGUAGES, value="html", label="Target Language")
|
169 |
+
search_chk = gr.Checkbox(label="Enable Web Search")
|
170 |
|
171 |
with gr.Row():
|
172 |
+
clr_btn = gr.Button("Clear Session", variant="secondary")
|
173 |
+
gen_btn = gr.Button("Generate Code", variant="primary", elem_id="gen_btn")
|
174 |
+
|
175 |
+
# --- Hugging Face Integration ---
|
176 |
+
gr.Markdown("---")
|
177 |
+
gr.Markdown("#### Hugging Face Integration")
|
178 |
+
hf_url = gr.Textbox(label="Load HF Space URL")
|
179 |
+
hf_load_btn = gr.Button("Import Project")
|
180 |
+
hf_status = gr.Markdown(visible=False)
|
181 |
+
|
182 |
+
hf_load_btn.click(
|
183 |
+
fn=lambda u: load_project_from_url(u),
|
184 |
+
inputs=hf_url,
|
185 |
+
outputs=[hf_status, code_out, preview_out, hf_url, history_state, chat_out]
|
186 |
+
)
|
187 |
|
|
|
188 |
with gr.Column(scale=2):
|
189 |
with gr.Tabs():
|
190 |
+
with gr.Tab("π» Code"):
|
191 |
+
code_out = gr.Code(language="html", interactive=True)
|
192 |
+
with gr.Tab("ποΈ Live Preview"):
|
193 |
preview_out = gr.HTML()
|
194 |
+
with gr.Tab("π History"):
|
195 |
+
chat_out = gr.Chatbot(type="messages")
|
196 |
+
|
197 |
+
model_dd.change(lambda n: get_model_details(n) or initial_model, inputs=[model_dd], outputs=[model_state])
|
198 |
|
|
|
199 |
gen_btn.click(
|
200 |
+
fn=generation_code,
|
201 |
+
inputs=[prompt_in, file_in, url_in, model_state, search_chk, lang_dd, history_state],
|
202 |
+
outputs=[code_out, history_state, preview_out, chat_out],
|
203 |
)
|
204 |
|
205 |
+
clr_btn.click(
|
206 |
+
lambda: ("", None, "", [], "", "", []),
|
207 |
+
outputs=[prompt_in, file_in, url_in, history_state, code_out, preview_out, chat_out],
|
|
|
208 |
queue=False,
|
209 |
)
|
210 |
|