mgbam commited on
Commit
ea998ae
Β·
verified Β·
1 Parent(s): 2bb38db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -78
app.py CHANGED
@@ -1,82 +1,59 @@
 
1
  """
2
- AnyCoderΒ /Β ShashaΒ AI – Gradio back‑end
3
-
4
- β€’ Serves the custom front‑end shipped in index.html (+ static/style.css & static/index.js).
5
- β€’ Exposes one JSON endpointΒ (`POSTΒ /run/predict`) that the JS front‑end
6
- calls to run model inference.
7
  """
8
-
9
  from pathlib import Path
10
  from typing import List, Tuple
11
 
12
  import gradio as gr
13
 
14
- # ---- local helpers --------------------------------------------------------
15
  from inference import chat_completion
16
  from tavily_search import enhance_query_with_search
17
- from deploy import send_to_sandbox
18
  from models import AVAILABLE_MODELS, find_model, ModelInfo
19
  from utils import (
20
- extract_text_from_file,
21
- extract_website_content,
22
- history_to_messages,
23
- history_to_chatbot_messages,
24
- apply_search_replace_changes,
25
- remove_code_block,
26
- parse_transformers_js_output,
27
- format_transformers_js_output,
28
  )
29
 
30
- # ------------------- constants ---------------------------------------------
31
  SYSTEM_PROMPTS = {
32
- "html": (
33
- "ONLY USE HTML, CSS AND JAVASCRIPT. Return ONE html file "
34
- "wrapped in ```html ...```."
35
- ),
36
- "transformers.js": (
37
- "Generate THREE separate files (index.html / index.js / style.css) "
38
- "as three fenced blocks."
39
- ),
40
  }
41
  History = List[Tuple[str, str]]
42
 
43
- # ------------------- core callback -----------------------------------------
44
- def generate(
45
- prompt: str,
46
- file_path: str | None,
47
- website_url: str | None,
48
- model_id: str,
49
- language: str,
50
- enable_search: bool,
51
- history: History | None,
52
- ) -> Tuple[str, History]:
53
- """Called by the JS front‑end via POSTΒ /run/predict."""
54
  history = history or []
 
 
55
 
56
- # ----- build system + messages -----------------------------------------
57
- system_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
58
- messages = history_to_messages(history, system_prompt)
59
-
60
- ctx_parts: list[str] = [prompt.strip()]
61
-
62
  if file_path:
63
- ctx_parts.append("[File]")
64
- ctx_parts.append(extract_text_from_file(file_path)[:5000])
65
  if website_url:
66
- site_html = extract_website_content(website_url)
67
- if not site_html.startswith("Error"):
68
- ctx_parts.append("[Website]")
69
- ctx_parts.append(site_html[:8000])
70
 
71
- user_query = "\n\n".join(filter(None, ctx_parts))
72
- user_query = enhance_query_with_search(user_query, enable_search)
73
- messages.append({"role": "user", "content": user_query})
74
 
75
- # ----- run model --------------------------------------------------------
76
  model: ModelInfo = find_model(model_id) or AVAILABLE_MODELS[0]
77
  answer = chat_completion(model.id, messages)
78
 
79
- # ----- post‑process output ---------------------------------------------
80
  if language == "transformers.js":
81
  files = parse_transformers_js_output(answer)
82
  code = format_transformers_js_output(files)
@@ -89,35 +66,27 @@ def generate(
89
  history.append((prompt, code))
90
  return code, history
91
 
92
- # ------------------- read custom HTML --------------------------------------
93
- HTML_SOURCE = Path("index.html").read_text(encoding="utf‑8")
94
 
95
- # ------------------- Gradio UI ---------------------------------------------
96
  with gr.Blocks(css="body{margin:0}", title="AnyCoderΒ AI") as demo:
97
- # 1Β visible: your custom front‑end
98
- gr.HTML(HTML_SOURCE) # <- sanitize=False removed
99
-
100
- # 2Β hidden: API inputs / outputs
101
- with gr.Group(visible=False) as api:
102
- prompt_in = gr.Textbox()
103
- file_in = gr.File()
104
- url_in = gr.Textbox()
105
- model_in = gr.Textbox()
106
- lang_in = gr.Textbox()
107
- search_in = gr.Checkbox()
108
- hist_state = gr.State([])
109
-
110
  code_out, hist_out = gr.Textbox(), gr.State([])
111
 
112
- # expose /run/predict
113
- api_btn = gr.Button(visible=False)
114
- api_btn.click(
115
- fn=generate,
116
- inputs=[
117
- prompt_in, file_in, url_in,
118
- model_in, lang_in, search_in, hist_state
119
- ],
120
- outputs=[code_out, hist_out],
121
  api_name="predict",
122
  )
123
 
 
1
+ # app.py ── root of the repo
2
  """
3
+ AnyCoderΒ /Β ShashaΒ AI – Gradio back‑end
4
+ β€’ Hosts the custom HTML/JS/CSS in /static
5
+ β€’ Exposes POST /run/predict for the browser‑side fetch()
 
 
6
  """
7
+ from __future__ import annotations
8
  from pathlib import Path
9
  from typing import List, Tuple
10
 
11
  import gradio as gr
12
 
 
13
  from inference import chat_completion
14
  from tavily_search import enhance_query_with_search
 
15
  from models import AVAILABLE_MODELS, find_model, ModelInfo
16
  from utils import (
17
+ extract_text_from_file, extract_website_content,
18
+ history_to_messages, history_to_chatbot_messages,
19
+ apply_search_replace_changes, remove_code_block,
20
+ parse_transformers_js_output, format_transformers_js_output,
 
 
 
 
21
  )
22
 
 
23
  SYSTEM_PROMPTS = {
24
+ "html": "ONLY USE HTML, CSS &β€―JS. Return ONE file wrapped in ```html```.",
25
+ "transformers.js":"Generate THREE files (index.html / index.js / style.css) as fenced blocks."
 
 
 
 
 
 
26
  }
27
  History = List[Tuple[str, str]]
28
 
29
+ # ─────────────────────────────────────────────────────────────────────────────
30
+ def generate(prompt:str,
31
+ file_path:str|None,
32
+ website_url:str|None,
33
+ model_id:str,
34
+ language:str,
35
+ enable_search:bool,
36
+ history:History|None) -> Tuple[str,History]:
37
+ """Invoked by the JS front‑end."""
 
 
38
  history = history or []
39
+ sys_prompt = SYSTEM_PROMPTS.get(language, f"You are an expert {language} developer.")
40
+ messages = history_to_messages(history, sys_prompt)
41
 
42
+ ctx: list[str] = [prompt.strip()]
 
 
 
 
 
43
  if file_path:
44
+ ctx.append("[File]\n" + extract_text_from_file(file_path)[:5_000])
 
45
  if website_url:
46
+ html = extract_website_content(website_url)
47
+ if not html.startswith("Error"):
48
+ ctx.append("[Website]\n" + html[:8_000])
 
49
 
50
+ user_q = "\n\n".join(filter(None, ctx))
51
+ user_q = enhance_query_with_search(user_q, enable_search)
52
+ messages.append({"role": "user", "content": user_q})
53
 
 
54
  model: ModelInfo = find_model(model_id) or AVAILABLE_MODELS[0]
55
  answer = chat_completion(model.id, messages)
56
 
 
57
  if language == "transformers.js":
58
  files = parse_transformers_js_output(answer)
59
  code = format_transformers_js_output(files)
 
66
  history.append((prompt, code))
67
  return code, history
68
 
69
+ # ───────────────────────────────────────────��─────────────────────────────────
70
+ HTML_SOURCE = Path("static/index.html").read_text(encoding="utf-8")
71
 
 
72
  with gr.Blocks(css="body{margin:0}", title="AnyCoderΒ AI") as demo:
73
+ gr.HTML(HTML_SOURCE) # the whole UI
74
+ # hidden I/O elements for the JS fetch()
75
+ with gr.Group(visible=False):
76
+ prompt_in = gr.Textbox()
77
+ file_in = gr.File()
78
+ url_in = gr.Textbox()
79
+ model_in = gr.Textbox()
80
+ lang_in = gr.Textbox()
81
+ search_in = gr.Checkbox()
82
+ hist_state = gr.State([])
 
 
 
83
  code_out, hist_out = gr.Textbox(), gr.State([])
84
 
85
+ gr.Button(visible=False).click( # POST /run/predict
86
+ generate,
87
+ [prompt_in, file_in, url_in,
88
+ model_in, lang_in, search_in, hist_state],
89
+ [code_out, hist_out],
 
 
 
 
90
  api_name="predict",
91
  )
92