mgbam commited on
Commit
588ca16
Β·
verified Β·
1 Parent(s): 49d4630

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -137
app.py CHANGED
@@ -1,188 +1,201 @@
 
 
1
  """
2
- app.py – AnyCoderΒ AI (Gradio)
3
 
4
- * Logo: assets/logo.png
5
- * Models: full list from constants.AVAILABLE_MODELS
6
- * No height= arg on gr.Code (Gradio β‰₯5)
7
  """
8
 
9
- from __future__ import annotations
10
  import gradio as gr
11
- from typing import List, Tuple, Dict, Optional
12
 
13
- # ── local modules ──────────────────────────────────────────────────────────
14
  from constants import (
15
- HTML_SYSTEM_PROMPT, HTML_SYSTEM_PROMPT_WITH_SEARCH,
16
- TRANSFORMERS_JS_SYSTEM_PROMPT, TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH,
17
- GENERIC_SYSTEM_PROMPT, GENERIC_SYSTEM_PROMPT_WITH_SEARCH,
18
- TransformersJSFollowUpSystemPrompt, FollowUpSystemPrompt,
19
- AVAILABLE_MODELS, DEMO_LIST, get_gradio_language,
20
  )
21
- from hf_client import get_inference_client
22
  from tavily_search import enhance_query_with_search
23
- from utils import (
24
- extract_text_from_file, extract_website_content,
25
- history_to_messages, history_to_chatbot_messages,
26
- remove_code_block, parse_transformers_js_output,
27
- format_transformers_js_output,
28
- )
29
- from search_replace import ( # <-- moved here
30
  apply_search_replace_changes,
31
- apply_transformers_js_search_replace_changes,
 
 
 
 
32
  )
33
- from deploy import send_to_sandbox
34
 
35
- # ── aliases ────────────────────────────────────────────────────────────────
36
  History = List[Tuple[str, str]]
37
- Model = Dict[str, str]
38
-
39
- # ── code generation core ───────────────────────────────────────────────────
40
- def generate_code(
41
- prompt: str,
42
- file_path: Optional[str],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  website_url: Optional[str],
44
- model: Model,
45
- language: str,
46
  enable_search: bool,
 
47
  history: Optional[History],
48
- ):
 
49
  history = history or []
50
- prompt = prompt or ""
51
-
52
- # choose system prompt
53
- if history:
54
- system_prompt = (
55
- TransformersJSFollowUpSystemPrompt if language == "transformers.js"
56
- else FollowUpSystemPrompt
57
- )
58
- else:
59
  if language == "html":
60
- system_prompt = HTML_SYSTEM_PROMPT_WITH_SEARCH if enable_search else HTML_SYSTEM_PROMPT
61
  elif language == "transformers.js":
62
- system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT_WITH_SEARCH if enable_search else TRANSFORMERS_JS_SYSTEM_PROMPT
63
  else:
 
64
  system_prompt = (
65
- GENERIC_SYSTEM_PROMPT_WITH_SEARCH.format(language=language)
66
- if enable_search else GENERIC_SYSTEM_PROMPT.format(language=language)
67
  )
68
 
69
- messages = history_to_messages(history, system_prompt)
70
-
71
- # attach context
72
- if file_path:
73
- prompt += f"\n\n[File]\n{extract_text_from_file(file_path)[:5000]}"
74
- if website_url:
75
- prompt += f"\n\n[Website]\n{extract_website_content(website_url)[:8000]}"
76
-
77
- messages.append({"role": "user", "content": enhance_query_with_search(prompt, enable_search)})
78
-
79
- # call model
80
- client = get_inference_client(model["id"])
81
- try:
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  resp = client.chat.completions.create(
83
- model=model["id"],
84
- messages=messages,
85
  max_tokens=16000,
86
- temperature=0.1,
87
  )
88
- answer = resp.choices[0].message.content
 
89
  except Exception as e:
90
  err = f"❌ **Error:**\n```\n{e}\n```"
91
- history.append((prompt, err))
92
- return err, history, "", history_to_chatbot_messages(history)
93
 
94
- # post‑process
95
  if language == "transformers.js":
96
- files = parse_transformers_js_output(answer)
97
- code = format_transformers_js_output(files)
98
- preview = send_to_sandbox(files["index.html"]) if files["index.html"] else ""
99
  else:
100
- clean = remove_code_block(answer)
101
- if history and not history[-1][1].startswith("❌"):
102
- clean = apply_search_replace_changes(history[-1][1], clean)
103
- code = clean
 
104
  preview = send_to_sandbox(code) if language == "html" else ""
105
 
106
- history.append((prompt, code))
107
- chat_msgs = history_to_chatbot_messages(history)
108
- return code, history, preview, chat_msgs
109
-
110
- # ── UI ─────────────────────────────────────────────────────────────────────
111
- theme = gr.themes.Base(primary_hue="indigo", font="Inter")
 
 
 
 
 
 
112
 
113
- with gr.Blocks(theme=theme, title="AnyCoderΒ AI") as demo:
114
- st_hist = gr.State([])
115
- st_model = gr.State(AVAILABLE_MODELS[0])
 
116
 
117
- # header with logo
118
- gr.HTML(
119
- '<div style="text-align:center;margin:1rem 0;">'
120
- '<img src="assets/logo.png" alt="logo" style="width:120px;"><br>'
121
- '<h1 style="margin:0.4rem 0 0">AnyCoderΒ AI</h1>'
122
- '<p style="color:#555">Your AI partner for generating, modifying &amp; understanding code.</p>'
123
- '</div>'
124
- )
125
 
126
  with gr.Row():
127
  with gr.Column(scale=1):
128
- gr.Markdown("### 1 Β· Model")
129
- dd_model = gr.Dropdown([m["name"] for m in AVAILABLE_MODELS],
130
- value=AVAILABLE_MODELS[0]["name"],
131
- label="AIΒ Model")
 
 
132
 
133
- gr.Markdown("### 2 Β· Context")
134
  with gr.Tabs():
135
- with gr.Tab("Prompt"):
136
- tb_prompt = gr.Textbox(lines=6, placeholder="Describe what you want…")
137
- with gr.Tab("File"):
138
- fi_file = gr.File()
139
- with gr.Tab("Website"):
140
- tb_url = gr.Textbox(placeholder="https://example.com")
141
-
142
- gr.Markdown("### 3 Β· Output")
143
- dd_lang = gr.Dropdown(
144
- [l for l in get_gradio_language.__defaults__[0] if l], # supported list
145
- value="html",
146
- label="Target language"
147
- )
148
- cb_search = gr.Checkbox(label="Enable Tavily Webβ€―Search")
149
 
150
  with gr.Row():
151
- btn_clear = gr.Button("Clear", variant="secondary")
152
- btn_gen = gr.Button("Generateβ€―Code", variant="primary")
153
 
154
  with gr.Column(scale=2):
155
  with gr.Tabs():
156
- with gr.Tab("Code"):
157
- code_out = gr.Code(language="html", lines=25)
158
- with gr.Tab("Preview"):
159
- html_prev = gr.HTML()
160
- with gr.Tab("History"):
161
- chat_out = gr.Chatbot(type="messages", height=400)
162
-
163
- # quick demos
164
- gr.Markdown("#### QuickΒ Start")
165
- with gr.Row():
166
- for d in DEMO_LIST[:6]:
167
- gr.Button(d["title"], size="sm").click(
168
- lambda desc=d["description"]: desc, outputs=tb_prompt
169
- )
170
-
171
- # callbacks
172
- dd_model.change(lambda n: next(m for m in AVAILABLE_MODELS if m["name"] == n),
173
- dd_model, st_model)
174
-
175
- btn_gen.click(
176
- generate_code,
177
- inputs=[tb_prompt, fi_file, tb_url, st_model, dd_lang, cb_search, st_hist],
178
- outputs=[code_out, st_hist, html_prev, chat_out],
179
  )
180
 
181
- btn_clear.click(
182
- lambda: ("", None, "", [], [], "", ""),
183
- outputs=[tb_prompt, fi_file, tb_url, st_hist, chat_out, code_out, html_prev],
184
  queue=False,
185
  )
186
 
187
  if __name__ == "__main__":
188
- demo.launch()
 
1
+ # app.py
2
+
3
  """
4
+ Main application file for SHASHA AI, a Gradio-based AI code generation tool.
5
 
6
+ Provides a UI for generating code in many languages using various AI models.
7
+ Supports text prompts, file uploads, website scraping, optional web search,
8
+ and live previews of HTML output.
9
  """
10
 
 
11
  import gradio as gr
12
+ from typing import Optional, Dict, List, Tuple, Any
13
 
14
+ # --- Local module imports ---
15
  from constants import (
16
+ HTML_SYSTEM_PROMPT,
17
+ TRANSFORMERS_JS_SYSTEM_PROMPT,
18
+ AVAILABLE_MODELS,
19
+ DEMO_LIST,
 
20
  )
21
+ from hf_client import get_inference_client
22
  from tavily_search import enhance_query_with_search
23
+ from utils import (
24
+ extract_text_from_file,
25
+ extract_website_content,
 
 
 
 
26
  apply_search_replace_changes,
27
+ history_to_messages,
28
+ history_to_chatbot_messages,
29
+ remove_code_block,
30
+ parse_transformers_js_output,
31
+ format_transformers_js_output,
32
  )
33
+ from deploy import send_to_sandbox
34
 
35
+ # --- Type aliases ---
36
  History = List[Tuple[str, str]]
37
+ Model = Dict[str, Any]
38
+
39
+ # --- Supported languages for dropdown ---
40
+ SUPPORTED_LANGUAGES = [
41
+ "python", "c", "cpp", "markdown", "latex", "json", "html", "css",
42
+ "javascript", "jinja2", "typescript", "yaml", "dockerfile", "shell",
43
+ "r", "sql", "sql-msSQL", "sql-mySQL", "sql-mariaDB", "sql-sqlite",
44
+ "sql-cassandra", "sql-plSQL", "sql-hive", "sql-pgSQL", "sql-gql",
45
+ "sql-gpSQL", "sql-sparkSQL", "sql-esper"
46
+ ]
47
+
48
+ def get_model_details(name: str) -> Optional[Model]:
49
+ for m in AVAILABLE_MODELS:
50
+ if m["name"] == name:
51
+ return m
52
+ return None
53
+
54
+ def generation_code(
55
+ query: Optional[str],
56
+ file: Optional[str],
57
  website_url: Optional[str],
58
+ current_model: Model,
 
59
  enable_search: bool,
60
+ language: str,
61
  history: Optional[History],
62
+ ) -> Tuple[str, History, str, List[Dict[str, str]]]:
63
+ query = query or ""
64
  history = history or []
65
+ try:
66
+ # Choose system prompt based on language
 
 
 
 
 
 
 
67
  if language == "html":
68
+ system_prompt = HTML_SYSTEM_PROMPT
69
  elif language == "transformers.js":
70
+ system_prompt = TRANSFORMERS_JS_SYSTEM_PROMPT
71
  else:
72
+ # Generic fallback prompt
73
  system_prompt = (
74
+ f"You are an expert {language} developer. "
75
+ f"Write clean, idiomatic {language} code based on the user's request."
76
  )
77
 
78
+ model_id = current_model["id"]
79
+ # Determine provider
80
+ if model_id.startswith("openai/") or model_id in {"gpt-4", "gpt-3.5-turbo"}:
81
+ provider = "openai"
82
+ elif model_id.startswith("gemini/") or model_id.startswith("google/"):
83
+ provider = "gemini"
84
+ elif model_id.startswith("fireworks-ai/"):
85
+ provider = "fireworks-ai"
86
+ else:
87
+ provider = "auto"
88
+
89
+ # Build message history
90
+ msgs = history_to_messages(history, system_prompt)
91
+ context = query
92
+ if file:
93
+ ftext = extract_text_from_file(file)
94
+ context += f"\n\n[Attached file]\n{ftext[:5000]}"
95
+ if website_url:
96
+ wtext = extract_website_content(website_url)
97
+ if not wtext.startswith("Error"):
98
+ context += f"\n\n[Website content]\n{wtext[:8000]}"
99
+ final_q = enhance_query_with_search(context, enable_search)
100
+ msgs.append({"role": "user", "content": final_q})
101
+
102
+ # Call the model
103
+ client = get_inference_client(model_id, provider)
104
  resp = client.chat.completions.create(
105
+ model=model_id,
106
+ messages=msgs,
107
  max_tokens=16000,
108
+ temperature=0.1
109
  )
110
+ content = resp.choices[0].message.content
111
+
112
  except Exception as e:
113
  err = f"❌ **Error:**\n```\n{e}\n```"
114
+ history.append((query, err))
115
+ return "", history, "", history_to_chatbot_messages(history)
116
 
117
+ # Process model output
118
  if language == "transformers.js":
119
+ files = parse_transformers_js_output(content)
120
+ code = format_transformers_js_output(files)
121
+ preview = send_to_sandbox(files.get("index.html", ""))
122
  else:
123
+ cleaned = remove_code_block(content)
124
+ if history and history[-1][1] and not history[-1][1].startswith("❌"):
125
+ code = apply_search_replace_changes(history[-1][1], cleaned)
126
+ else:
127
+ code = cleaned
128
  preview = send_to_sandbox(code) if language == "html" else ""
129
 
130
+ new_hist = history + [(query, code)]
131
+ chat = history_to_chatbot_messages(new_hist)
132
+ return code, new_hist, preview, chat
133
+
134
+ # --- Custom CSS ---
135
+ CUSTOM_CSS = """
136
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
137
+ #main_title { text-align: center; font-size: 2.5rem; margin-top: 1.5rem; }
138
+ #subtitle { text-align: center; color: #4a5568; margin-bottom: 2.5rem; }
139
+ .gradio-container { background-color: #f7fafc; }
140
+ #gen_btn { box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
141
+ """
142
 
143
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue"), css=CUSTOM_CSS, title="Shasha AI") as demo:
144
+ history_state = gr.State([])
145
+ initial_model = AVAILABLE_MODELS[0]
146
+ model_state = gr.State(initial_model)
147
 
148
+ gr.Markdown("# πŸš€ Shasha AI", elem_id="main_title")
149
+ gr.Markdown("Your AI partner for generating, modifying, and understanding code.", elem_id="subtitle")
 
 
 
 
 
 
150
 
151
  with gr.Row():
152
  with gr.Column(scale=1):
153
+ gr.Markdown("### 1. Select Model")
154
+ model_dd = gr.Dropdown(
155
+ choices=[m["name"] for m in AVAILABLE_MODELS],
156
+ value=initial_model["name"],
157
+ label="AI Model"
158
+ )
159
 
160
+ gr.Markdown("### 2. Provide Context")
161
  with gr.Tabs():
162
+ with gr.Tab("πŸ“ Prompt"):
163
+ prompt_in = gr.Textbox(lines=7, placeholder="Describe your request...", show_label=False)
164
+ with gr.Tab("πŸ“„ File"):
165
+ file_in = gr.File(type="filepath")
166
+ with gr.Tab("🌐 Website"):
167
+ url_in = gr.Textbox(placeholder="https://example.com")
168
+
169
+ gr.Markdown("### 3. Configure Output")
170
+ lang_dd = gr.Dropdown(SUPPORTED_LANGUAGES, value="html", label="Target Language")
171
+ search_chk = gr.Checkbox(label="Enable Web Search")
 
 
 
 
172
 
173
  with gr.Row():
174
+ clr_btn = gr.Button("Clear Session", variant="secondary")
175
+ gen_btn = gr.Button("Generate Code", variant="primary", elem_id="gen_btn")
176
 
177
  with gr.Column(scale=2):
178
  with gr.Tabs():
179
+ with gr.Tab("πŸ’» Code"):
180
+ code_out = gr.Code(language="html", interactive=True)
181
+ with gr.Tab("πŸ‘οΈ Live Preview"):
182
+ preview_out = gr.HTML()
183
+ with gr.Tab("πŸ“œ History"):
184
+ chat_out = gr.Chatbot(type="messages")
185
+
186
+ model_dd.change(lambda n: get_model_details(n) or initial_model, inputs=[model_dd], outputs=[model_state])
187
+
188
+ gen_btn.click(
189
+ fn=generation_code,
190
+ inputs=[prompt_in, file_in, url_in, model_state, search_chk, lang_dd, history_state],
191
+ outputs=[code_out, history_state, preview_out, chat_out],
 
 
 
 
 
 
 
 
 
 
192
  )
193
 
194
+ clr_btn.click(
195
+ lambda: ("", None, "", [], "", "", []),
196
+ outputs=[prompt_in, file_in, url_in, history_state, code_out, preview_out, chat_out],
197
  queue=False,
198
  )
199
 
200
  if __name__ == "__main__":
201
+ demo.queue().launch()