mgbam commited on
Commit
129a08f
Β·
verified Β·
1 Parent(s): a8e5826

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +53 -55
app.py CHANGED
@@ -1,21 +1,21 @@
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
@@ -32,7 +32,7 @@ from utils import (
32
  from deploy import send_to_sandbox
33
 
34
  # ── constants ───────────────────────────────────────────────────
35
- SUPPORTED_LANGUAGES = [
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 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,
61
  website_url: str | None,
62
  model_name: str,
63
  enable_search: bool,
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],
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
  )