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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -56
app.py CHANGED
@@ -1,27 +1,25 @@
1
  # app.py
2
  # ────────────────────────────────────────────────────────────────
3
  """
4
- AnyCoderΒ /Β ShashaΒ AI – lightweight Gradio front‑end
5
-
6
- β€’ Pick an AI model from models.py ➜ AVAILABLE_MODELS
7
- β€’ Provide context (prompt / file / website)
8
- β€’ Choose a target language from 25+ options
9
- β€’ Optional Tavily web‑search enrichment
10
- β€’ Generate code & live‑preview HTML
11
  """
12
 
13
  from __future__ import annotations
14
 
15
- from pathlib import Path
16
- from typing import List, Tuple, Dict, Any, Optional
17
 
18
  import gradio as gr
19
 
20
- # ── local helpers ───────────────────────────────────────────────
21
- from models import AVAILABLE_MODELS, find_model, ModelInfo
22
- from inference import chat_completion
23
  from tavily_search import enhance_query_with_search
24
- from utils import (
25
  extract_text_from_file,
26
  extract_website_content,
27
  history_to_messages,
@@ -31,7 +29,7 @@ from utils import (
31
  parse_transformers_js_output,
32
  format_transformers_js_output,
33
  )
34
- from deploy import send_to_sandbox
35
 
36
  # ── constants ───────────────────────────────────────────────────
37
  SUPPORTED_LANGUAGES = [
@@ -44,19 +42,19 @@ SUPPORTED_LANGUAGES = [
44
 
45
  SYSTEM_PROMPTS = {
46
  "html": (
47
- "ONLY USE HTML, CSS AND JAVASCRIPT. Produce ONE complete HTML file "
48
- "wrapped in ```html ...```."
49
  ),
50
  "transformers.js": (
51
- "Generate THREE fenced blocks (index.html / index.js / style.css) "
52
- "for a transformers.js web‑app."
53
  ),
54
  }
55
 
56
  History = List[Tuple[str, str]]
57
 
58
 
59
- # ── core callback ───────────────────────────────────────────────
60
  def generate_code(
61
  prompt: str,
62
  file_path: str | None,
@@ -66,103 +64,103 @@ def generate_code(
66
  language: str,
67
  hist: History | None,
68
  ) -> Tuple[str, History, str, List[Dict[str, str]]]:
69
- """Back‑end for the β€˜Generate Code’ button."""
70
  hist = hist or []
71
  prompt = (prompt or "").strip()
72
 
73
- # 1Β build messages
74
  sys_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
75
- messages = history_to_messages(hist, sys_prompt)
76
 
77
- ctx_parts: list[str] = [prompt]
78
  if file_path:
79
- ctx_parts += ["[File]", extract_text_from_file(file_path)[:5000]]
80
  if website_url:
81
- html = extract_website_content(website_url)
82
- if not html.startswith("Error"):
83
- ctx_parts += ["[Website]", html[:8000]]
84
 
85
- user_msg = enhance_query_with_search("\n\n".join(ctx_parts), enable_search)
86
- messages.append({"role": "user", "content": user_msg})
87
 
88
- # 2Β run model (provider selection handled in inference.chat_completion)
89
  model: ModelInfo = find_model(model_name) or AVAILABLE_MODELS[0]
90
  try:
91
- raw_out = chat_completion(model.id, messages)
92
  except Exception as exc: # pragma: no cover
93
  err = f"❌ **Error**\n```{exc}```"
94
  hist.append((prompt, err))
95
  return "", hist, "", history_to_chatbot_messages(hist)
96
 
97
- # 3Β post‑process
98
  if language == "transformers.js":
99
- files = parse_transformers_js_output(raw_out)
100
- code = format_transformers_js_output(files)
101
  preview = send_to_sandbox(files.get("index.html", ""))
102
  else:
103
- cleaned = remove_code_block(raw_out)
104
  if hist and not hist[-1][1].startswith("❌"):
105
  cleaned = apply_search_replace_changes(hist[-1][1], cleaned)
106
  code = cleaned
107
  preview = send_to_sandbox(cleaned) if language == "html" else ""
108
 
109
  hist.append((prompt, code))
110
- chat_view = history_to_chatbot_messages(hist)
111
- return code, hist, preview, chat_view
112
 
113
 
114
- # ── UI ──────────────────────────────────────────────────────────
115
  THEME = gr.themes.Soft(primary_hue="indigo")
116
- custom_css = """
117
- body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
118
- #main_title { text-align:center;font-size:2.4rem;margin-top:1rem }
119
- #subtitle { text-align:center;color:#5a6475;margin-bottom:2rem }
120
  """
121
 
122
- with gr.Blocks(title="AnyCoderΒ AI", theme=THEME, css=custom_css) as demo:
123
  state_hist: gr.State[History] = gr.State([])
124
 
125
- gr.Markdown("## πŸš€β€―AnyCoderΒ AI", elem_id="main_title")
126
  gr.Markdown("Your AI partner for generating, modifying & understanding code.", elem_id="subtitle")
127
 
128
  with gr.Row():
129
- # ────────── inputs (sidebar) ──────────
130
  with gr.Column(scale=1):
131
- gr.Markdown("#### 1β€―Β·β€―Selectβ€―Model")
132
  model_dd = gr.Dropdown(
133
  choices=[m.name for m in AVAILABLE_MODELS],
134
  value=AVAILABLE_MODELS[0].name,
135
- label="AIΒ Model",
136
  )
137
 
138
- gr.Markdown("#### 2β€―Β·β€―Provideβ€―Context")
139
  with gr.Tabs():
140
  with gr.Tab("Prompt"):
141
- prompt_box = gr.Textbox(lines=6, placeholder="Describe what you want…")
142
  with gr.Tab("File"):
143
  file_box = gr.File(type="filepath")
144
  with gr.Tab("Website"):
145
  url_box = gr.Textbox(placeholder="https://example.com")
146
 
147
- gr.Markdown("#### 3β€―Β·β€―Configureβ€―Output")
148
  lang_dd = gr.Dropdown(SUPPORTED_LANGUAGES, value="html", label="TargetΒ Language")
149
- search_ck = gr.Checkbox(label="EnableΒ TavilyΒ WebΒ Search")
150
 
151
  with gr.Row():
152
  clear_btn = gr.Button("Clear Session", variant="secondary")
153
  gen_btn = gr.Button("GenerateΒ Code", variant="primary")
154
 
155
- # ────────── outputs (main panel) ─────
156
  with gr.Column(scale=2):
157
  with gr.Tabs():
158
  with gr.Tab("Code"):
159
- code_out = gr.Code(interactive=True)
160
- with gr.Tab("Liveβ€―Preview"):
161
  preview_out = gr.HTML()
162
  with gr.Tab("History"):
163
- chat_out = gr.Chatbot(type="messages")
164
 
165
- # ── wiring ───────────────────────────────────────────
166
  gen_btn.click(
167
  generate_code,
168
  inputs=[prompt_box, file_box, url_box, model_dd, search_ck, lang_dd, state_hist],
 
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
22
+ from utils import (
23
  extract_text_from_file,
24
  extract_website_content,
25
  history_to_messages,
 
29
  parse_transformers_js_output,
30
  format_transformers_js_output,
31
  )
32
+ from deploy import send_to_sandbox
33
 
34
  # ── constants ───────────────────────────────────────────────────
35
  SUPPORTED_LANGUAGES = [
 
42
 
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,
 
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],