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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -120
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
- 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
22
- from utils import (
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 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",
39
  "sql-cassandra", "sql-plSQL", "sql-hive", "sql-pgSQL", "sql-gql",
40
- "sql-gpSQL", "sql-sparkSQL", "sql-esper",
41
  ]
42
 
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
  )
167
 
168
- clear_btn.click(
169
- lambda: ("", None, "", "html", False, [], [], "", ""),
170
- outputs=[prompt_box, file_box, url_box, lang_dd, search_ck,
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