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