suvradeepp commited on
Commit
b2eeb5b
Β·
verified Β·
1 Parent(s): 0709ae6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +311 -2
app.py CHANGED
@@ -1,4 +1,313 @@
1
  import streamlit as st
 
 
 
 
 
 
 
 
2
 
3
- x = st.slider('Select a value')
4
- st.write(x, 'squared is', x * x)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import google.generativeai as genai
3
+ import os
4
+ from pathlib import Path
5
+ import json
6
+ import time
7
+ from dotenv import load_dotenv
8
+ import re
9
+ import urllib.parse
10
 
11
+
12
+ st.set_page_config(layout="wide", page_title="Gemini Web Builder (React CDN)")
13
+ load_dotenv()
14
+
15
+ WORKSPACE_DIR = Path("workspace")
16
+ WORKSPACE_DIR.mkdir(exist_ok=True)
17
+ CSS_FILENAME = "style.css"
18
+
19
+
20
+ try:
21
+ api_key = os.getenv("GOOGLE_API_KEY")
22
+ if not api_key:
23
+ st.error("πŸ”΄ Google API Key not found. Please ensure GOOGLE_API_KEY is set in your .env file.")
24
+ st.stop()
25
+ genai.configure(api_key=api_key)
26
+ model_name = os.getenv("GEMINI_MODEL", "gemini-2.5-pro-exp-03-25")
27
+ st.sidebar.caption(f"Using Model: `{model_name}`")
28
+ model = genai.GenerativeModel(model_name)
29
+ except Exception as e:
30
+ st.error(f"πŸ”΄ Failed to configure Gemini or load model '{model_name}': {e}")
31
+ st.stop()
32
+
33
+ if "messages" not in st.session_state: st.session_state.messages = []
34
+ if "selected_file" not in st.session_state: st.session_state.selected_file = None
35
+ if "file_content" not in st.session_state: st.session_state.file_content = ""
36
+ if "rendered_html" not in st.session_state: st.session_state.rendered_html = ""
37
+
38
+ def get_workspace_files():
39
+ try: return sorted([f.name for f in WORKSPACE_DIR.iterdir() if f.is_file()])
40
+ except Exception as e: st.error(f"Error listing workspace files: {e}"); return []
41
+
42
+ def read_file_content(filename):
43
+ if not filename: return None
44
+ if ".." in filename or filename.startswith(("/", "\\")): return None
45
+ filepath = WORKSPACE_DIR / filename
46
+ try:
47
+ with open(filepath, "r", encoding="utf-8") as f: return f.read()
48
+ except FileNotFoundError: return None
49
+ except Exception as e: st.error(f"Error reading file '{filename}': {e}"); return None
50
+
51
+ def save_file_content(filename, content):
52
+ if not filename: return False
53
+ if ".." in filename or filename.startswith(("/", "\\")): return False
54
+ filepath = WORKSPACE_DIR / filename
55
+ try:
56
+ filepath.parent.mkdir(parents=True, exist_ok=True)
57
+ with open(filepath, "w", encoding="utf-8") as f: f.write(content); return True
58
+ except Exception as e: st.error(f"Error saving file '{filename}': {e}"); return False
59
+
60
+ def delete_file(filename):
61
+ if not filename: return False
62
+ if ".." in filename or filename.startswith(("/", "\\")): return False
63
+ filepath = WORKSPACE_DIR / filename
64
+ try:
65
+ os.remove(filepath)
66
+ if st.session_state.selected_file == filename: # Clear state if selected file is deleted
67
+ st.session_state.selected_file = None
68
+ st.session_state.file_content = ""
69
+ st.session_state.rendered_html = ""
70
+ st.session_state.pop(f"rendered_for_{filename}", None)
71
+ return True
72
+ except FileNotFoundError: st.warning(f"File '{filename}' not found for deletion."); return False
73
+ except Exception as e: st.error(f"Error deleting file '{filename}': {e}"); return False
74
+
75
+
76
+ def parse_and_execute_commands(ai_response_text):
77
+ parsed_commands = []
78
+ try:
79
+ response_text_cleaned = ai_response_text.strip()
80
+ if response_text_cleaned.startswith("```json"): response_text_cleaned = response_text_cleaned[7:-3].strip()
81
+ elif response_text_cleaned.startswith("```"): response_text_cleaned = response_text_cleaned[3:-3].strip()
82
+ commands = json.loads(response_text_cleaned) # Strict parsing
83
+ if not isinstance(commands, list): return [{"action": "chat", "content": f"AI (Non-list JSON): {ai_response_text}"}]
84
+ for command in commands:
85
+ if not isinstance(command, dict): parsed_commands.append({"action": "chat", "content": f"Skipped: {command}"}); continue
86
+ action=command.get("action"); filename=command.get("filename"); content=command.get("content")
87
+ parsed_commands.append(command)
88
+ if action=="create_update":
89
+ if filename and content is not None:
90
+ if not save_file_content(filename, content): st.warning(f"Failed save '{filename}'.")
91
+ else: st.warning(f"⚠️ Invalid 'create_update': {command}")
92
+ elif action=="delete":
93
+ if filename: delete_file(filename)
94
+ else: st.warning(f"⚠️ Invalid 'delete': {command}")
95
+ elif action=="chat": pass
96
+ else: st.warning(f"⚠️ Unknown action '{action}': {command}")
97
+ return parsed_commands
98
+ except json.JSONDecodeError as e:
99
+ st.error(f"πŸ”΄ Invalid JSON: {e}\nTxt:\n'{ai_response_text[:500]}...'")
100
+ return [{"action": "chat", "content": f"AI(Invalid JSON): {ai_response_text}"}]
101
+ except Exception as e:
102
+ st.error(f"πŸ”΄ Error processing commands: {e}")
103
+ return [{"action": "chat", "content": f"Error processing commands: {e}"}]
104
+
105
+
106
+ def call_gemini(history):
107
+ safe_history = []
108
+ for msg in history:
109
+ if isinstance(msg, dict) and "role" in msg and "content" in msg:
110
+ safe_history.append({"role": msg["role"], "content": str(msg["content"])})
111
+
112
+ instruction = """
113
+ You are an AI assistant that helps users create web pages and simple web applications.
114
+ Your goal is to generate HTML, CSS, JavaScript code, or self-contained React preview files.
115
+ Based on the user's request, you MUST respond ONLY with a valid JSON array containing file operation objects.
116
+
117
+ **JSON FORMATTING RULES (VERY IMPORTANT):**
118
+ 1. The entire response MUST be a single JSON array starting with '[' and ending with ']'.
119
+ 2. All keys (like "action", "filename", "content") MUST be enclosed in **double quotes** (").
120
+ 3. All string values (like filenames and the large code content) MUST be enclosed in **double quotes** ("). Single quotes (') or backticks (`) are NOT ALLOWED for keys or string values in the JSON structure.
121
+ 4. Special characters within the "content" string (like newlines, double quotes inside the code) MUST be properly escaped (e.g., use '\\n' for newlines, '\\"' for double quotes).
122
+
123
+ **EXAMPLE of Correct JSON action object:**
124
+ {
125
+ "action": "create_update",
126
+ "filename": "example.html",
127
+ "content": "<!DOCTYPE html>\\n<html>\\n<head>\\n <title>Example</title>\\n</head>\\n<body>\\n <h1>Hello World!</h1>\\n <p>This contains a \\"quote\\" example.</p>\\n</body>\\n</html>"
128
+ }
129
+
130
+ Possible action objects in the JSON array:
131
+ - {"action": "create_update", "filename": "path/to/file.ext", "content": "file content string here..."}
132
+ - {"action": "delete", "filename": "path/to/file.ext"}
133
+ - {"action": "chat", "content": "Your helpful answer string here..."}
134
+
135
+ **VERY IMPORTANT - UPDATING FILES:**
136
+ If the user asks you to modify an existing file (e.g., "add a footer to index.html", "change the button color in style.css"), you MUST provide the **ENTIRE**, complete, updated file content within the 'content' field of the 'create_update' action object, following all JSON formatting rules. Do NOT provide only the changed lines or a diff.
137
+
138
+ **REACT PREVIEWS:**
139
+ If the user asks for a simple React component/app to preview, generate a SINGLE self-contained HTML file (e.g., 'react_preview.html') using 'create_update'. This file MUST use CDN links for React/ReactDOM/Babel, have a <div id="root">, include JSX in a <script type="text/babel"> tag, render to the root, and include CSS in <style> tags within the <head>. (Ensure valid JSON).
140
+
141
+ **GENERAL:**
142
+ Use standard filenames ('index.html', 'style.css', 'script.js'). The standard CSS file for injection is 'style.css'. If unsure, ask the user. Respond ONLY with the JSON array. Use 'chat' action for questions or explanations.
143
+ """
144
+ current_files = get_workspace_files()
145
+ file_list_prompt = f"Current files in workspace: {', '.join(current_files) if current_files else 'None'}"
146
+ gemini_history = []
147
+ gemini_history.append({"role": "user", "parts": [{"text": f"{instruction}\n{file_list_prompt}"}]})
148
+ gemini_history.append({"role": "model", "parts": [{"text": '[{"action": "chat", "content": "Okay, I understand the strict JSON formatting rules (double quotes, escaping) and the need to provide full file content on updates. I will respond only with the valid JSON array. Ready."}]'}]})
149
+ for msg in safe_history:
150
+ role = "user" if msg["role"] == "user" else "model"; content_text = msg["content"]
151
+ if role == "model" and isinstance(msg["content"], list):
152
+ try: content_text = json.dumps(msg["content"])
153
+ except Exception: content_text = str(msg["content"])
154
+ gemini_history.append({"role": role, "parts": [{"text": content_text}]})
155
+ try:
156
+ response = model.generate_content(gemini_history); return response.text
157
+ except Exception as e:
158
+ if "429" in str(e): st.error("πŸ”΄ Gemini API Quota/Rate Limit Exceeded.")
159
+ else: st.error(f"πŸ”΄ Gemini API call failed: {e}")
160
+ error_content = f"Error calling AI: {str(e)}".replace('"',"'"); return json.dumps([{"action": "chat", "content": error_content}])
161
+
162
+
163
+ with st.sidebar:
164
+ st.header("πŸ’¬ Chat with AI")
165
+ st.markdown("Ask the AI to create or modify web files (HTML, CSS, JS, React CDN Previews).")
166
+ st.caption(f"Using Model: `{model_name}`")
167
+ chat_container = st.container(height=500)
168
+ with chat_container:
169
+ if st.session_state.messages:
170
+ for message in st.session_state.messages:
171
+ with st.chat_message(message["role"]):
172
+ if isinstance(message.get("content"), list) and message.get("role") == "assistant":
173
+ display_text = ""; chat_messages = []
174
+ for command in message["content"]:
175
+ if not isinstance(command, dict): continue
176
+ action = command.get("action"); filename = command.get("filename")
177
+ if action == "create_update": display_text += f"πŸ“ Create/Update: `{filename}`\n"
178
+ elif action == "delete": display_text += f"πŸ—‘οΈ Delete: `{filename}`\n"
179
+ elif action == "chat": chat_messages.append(command.get('content', '...'))
180
+ else: display_text += f"⚠️ {command.get('content', f'Unknown action: {action}')}\n"
181
+ final_display = (display_text + "\n".join(chat_messages)).strip()
182
+ if not final_display: final_display = "(No action)"
183
+ st.markdown(final_display)
184
+ else: st.write(str(message.get("content", "")))
185
+ else: st.info("Chat history empty.")
186
+ if prompt := st.chat_input("e.g., Create index.html with a title"):
187
+ st.session_state.messages.append({"role": "user", "content": prompt})
188
+ with st.spinner("🧠 AI Thinking..."):
189
+ ai_response_text = call_gemini(st.session_state.messages)
190
+ executed_commands = parse_and_execute_commands(ai_response_text)
191
+ st.session_state.messages.append({"role": "assistant", "content": executed_commands})
192
+ st.rerun()
193
+
194
+ st.title("πŸ€– AI Web Builder (React CDN Preview)")
195
+ tab1, tab2 = st.tabs([" πŸ“‚ Workspace ", " πŸ‘€ Preview "])
196
+
197
+ with tab1:
198
+ st.header("Workspace & Editor")
199
+ st.markdown("---")
200
+ st.subheader("Files")
201
+ available_files = get_workspace_files()
202
+ if not available_files: st.info(f"Workspace '{WORKSPACE_DIR.name}' empty.")
203
+ current_selection_index = 0; options = [None] + available_files
204
+ if st.session_state.selected_file in options:
205
+ try: current_selection_index = options.index(st.session_state.selected_file)
206
+ except ValueError: st.session_state.selected_file = None
207
+ selected_file_option = st.selectbox("Select file:", options=options, format_func=lambda x: "--- Select ---" if x is None else x, key="ws_file_select", index=current_selection_index)
208
+ st.subheader("Edit Code")
209
+ editor_key = f"editor_{st.session_state.selected_file or 'none'}"
210
+ if selected_file_option != st.session_state.selected_file:
211
+ st.session_state.selected_file = selected_file_option
212
+ st.session_state.file_content = read_file_content(st.session_state.selected_file) or "" if st.session_state.selected_file else ""
213
+ st.session_state.rendered_html = ""; st.session_state.pop(f"rendered_for_{st.session_state.selected_file}", None)
214
+ st.rerun()
215
+ if st.session_state.selected_file:
216
+ st.caption(f"Editing: `{st.session_state.selected_file}`")
217
+ file_ext = Path(st.session_state.selected_file).suffix.lower()
218
+ lang_map = {".html": "html", ".css": "css", ".js": "javascript", ".py":"python", ".md": "markdown", ".json": "json", ".jsx":"javascript", ".vue":"vue", ".svelte":"svelte", ".txt":"text"}
219
+ language = lang_map.get(file_ext)
220
+ edited_content = st.text_area("Code Editor", value=st.session_state.file_content, height=400, key=editor_key, label_visibility="collapsed", args=(language,))
221
+ if edited_content != st.session_state.file_content:
222
+ if st.button("πŸ’Ύ Save Manual Changes"):
223
+ if save_file_content(st.session_state.selected_file, edited_content):
224
+ st.session_state.file_content = edited_content; st.success(f"Saved: `{st.session_state.selected_file}`")
225
+ st.session_state.rendered_html = ""; st.session_state.pop(f"rendered_for_{st.session_state.selected_file}", None)
226
+ time.sleep(0.5); st.rerun()
227
+ else: st.error("Failed to save.")
228
+ else:
229
+ st.info("Select a file to edit.")
230
+ st.text_area("Code Editor", value="Select a file...", height=400, key="editor_placeholder", disabled=True, label_visibility="collapsed")
231
+
232
+ with tab2:
233
+ st.header("Live Preview")
234
+ st.markdown("---")
235
+ css_applied_info = ""
236
+
237
+ if st.session_state.selected_file:
238
+ if st.session_state.selected_file.lower().endswith(('.html', '.htm')):
239
+ current_file_content_for_preview = read_file_content(st.session_state.selected_file)
240
+ rendered_marker_key = f"rendered_for_{st.session_state.selected_file}"
241
+ needs_render_update = False
242
+ if current_file_content_for_preview is not None:
243
+ needs_render_update = (not st.session_state.rendered_html or st.session_state.get(rendered_marker_key) != current_file_content_for_preview)
244
+ else:
245
+ st.session_state.rendered_html = ""; st.session_state.pop(rendered_marker_key, None)
246
+
247
+ if needs_render_update:
248
+ if current_file_content_for_preview is not None:
249
+ final_html = current_file_content_for_preview
250
+ is_react_cdn_preview = "<script src=\"https://unpkg.com/@babel/standalone" in final_html
251
+ css_applied_info = ""
252
+ if not is_react_cdn_preview:
253
+ css_content = read_file_content(CSS_FILENAME)
254
+ if css_content:
255
+ style_tag = f"\n<style>\n{css_content}\n</style>\n"
256
+ head_match = re.search(r"</head>", final_html, re.IGNORECASE)
257
+ if head_match:
258
+ injection_point = head_match.start()
259
+ final_html = final_html[:injection_point] + style_tag + final_html[injection_point:]
260
+ css_applied_info = f"🎨 Injected `{CSS_FILENAME}`."
261
+ st.session_state.rendered_html = final_html
262
+ st.session_state[rendered_marker_key] = current_file_content_for_preview
263
+
264
+ else:
265
+ st.warning(f"Could not read `{st.session_state.selected_file}` for preview.")
266
+ st.session_state.rendered_html = "Error reading file for preview."
267
+ st.session_state.pop(rendered_marker_key, None)
268
+
269
+
270
+ if st.session_state.rendered_html and "Error reading file" not in st.session_state.rendered_html:
271
+ st.info(f"Previewing: `{st.session_state.selected_file}`")
272
+ st.markdown("---")
273
+
274
+ try:
275
+
276
+ encoded_html = urllib.parse.quote(st.session_state.rendered_html)
277
+ data_uri = f"data:text/html;charset=utf-8,{encoded_html}"
278
+ st.markdown(f'<a href="{data_uri}" target="_blank" rel="noopener noreferrer"><button>πŸš€ Open Preview in New Window</button></a>', unsafe_allow_html=True)
279
+ st.caption("_(Uses Data URI - best for self-contained HTML/CSS/JS)_")
280
+ except Exception as e:
281
+ st.warning(f"Could not create 'Open in New Window' link: {e}")
282
+
283
+
284
+ st.components.v1.html(st.session_state.rendered_html, height=600, scrolling=True)
285
+ st.markdown("---")
286
+ preview_note = "Note: Basic HTML Preview."
287
+ if "<script src=\"https://unpkg.com/@babel/standalone" in st.session_state.rendered_html:
288
+ preview_note = "Note: Preview uses CDN links & in-browser transpiling for simple React demos."
289
+
290
+ if not is_react_cdn_preview and f"Injected `{CSS_FILENAME}`" in css_applied_info:
291
+ preview_note += f" {css_applied_info}"
292
+ st.caption(preview_note)
293
+
294
+ elif "Error reading file" in str(st.session_state.rendered_html):
295
+ st.error("Preview failed: Could not read the HTML file.")
296
+
297
+ else: # File selected, but not HTML
298
+ st.info(f"Preview is available for HTML files only. Selected: `{st.session_state.selected_file}`")
299
+ st.session_state.rendered_html = ""
300
+ st.session_state.pop(f"rendered_for_{st.session_state.selected_file}", None)
301
+ else: # No file selected
302
+ st.info("Select an HTML file from the 'Workspace' tab to see a preview.")
303
+ st.session_state.rendered_html = ""
304
+
305
+ st.sidebar.markdown("---")
306
+ st.sidebar.warning("""
307
+ **Prototype Limitations & Warnings:**
308
+ - **Security:** AI can modify files directly! Use locally & cautiously. **Do not expose publicly.**
309
+ - **File Operations:** Basic create/update/delete. Errors possible.
310
+ - **Preview:** Basic HTML rendering. Attempts `style.css` injection. Can render simple React CDN examples. **No build process, linked JS/CSS (unless injected), etc.** "Open in New Window" uses Data URI and has limitations (URL length, no relative paths for images).
311
+ - **AI Reliability:** AI might misunderstand, generate invalid JSON/code, or fail updates. Prompt tuning helps. Errors are caught, but file ops may fail.
312
+ - **State:** Lost on browser refresh.
313
+ """, icon="⚠️")