broadfield-dev commited on
Commit
2b87e9c
Β·
verified Β·
1 Parent(s): 97035f0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +822 -0
app.py ADDED
@@ -0,0 +1,822 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import re
3
+ import json
4
+ import os
5
+ import tempfile
6
+ import shlex
7
+ from huggingface_hub import HfApi
8
+
9
+ try:
10
+ from build_logic import (
11
+ create_space as build_logic_create_space,
12
+ _get_api_token as build_logic_get_api_token,
13
+ whoami as build_logic_whoami,
14
+ list_space_files_for_browsing,
15
+ get_space_repository_info,
16
+ get_space_file_content,
17
+ update_space_file,
18
+ parse_markdown as build_logic_parse_markdown,
19
+ delete_space_file as build_logic_delete_space_file,
20
+ get_space_runtime_status
21
+ )
22
+ print("build_logic.py loaded successfully.")
23
+
24
+ from model_logic import (
25
+ get_available_providers,
26
+ get_models_for_provider,
27
+ get_default_model_for_provider,
28
+ generate_stream
29
+ )
30
+ print("model_logic.py loaded successfully.")
31
+ except ImportError:
32
+ print("Warning: Local modules (build_logic.py, model_logic.py) not found. Using dummy functions.")
33
+ def get_available_providers(): return ["DummyProvider"]
34
+ def get_models_for_provider(p): return ["dummy-model"]
35
+ def get_default_model_for_provider(p): return "dummy-model"
36
+ def generate_stream(p, m, a, msgs):
37
+ yield "Error: Local modules not found. This is a dummy response."
38
+ def build_logic_create_space(*args, **kwargs): return "Error: build_logic not found."
39
+ def build_logic_get_api_token(key): return (key or os.getenv("HF_TOKEN"), None)
40
+ def build_logic_whoami(token): return {"name": "dummy_user"}
41
+ def list_space_files_for_browsing(*args): return ([], "Error: build_logic not found.")
42
+ def get_space_repository_info(*args): return (None, [], "Error: build_logic not found.")
43
+ def get_space_file_content(*args): return ("", "Error: build_logic not found.")
44
+ def update_space_file(*args, **kwargs): return "Error: build_logic not found."
45
+ def build_logic_parse_markdown(md): return {"files": []}
46
+ def build_logic_delete_space_file(*args): return "Error: build_logic not found."
47
+ def get_space_runtime_status(*args): return (None, "Error: build_logic not found.")
48
+ # --- END: Dummy functions ---
49
+
50
+
51
+ # --- New Feature Functions (can be moved to build_logic.py) ---
52
+ def build_logic_set_space_privacy(hf_api_key, repo_id, private: bool):
53
+ """Sets the privacy of a Hugging Face Space."""
54
+ print(f"[ACTION] Setting privacy for '{repo_id}' to {private}.")
55
+ try:
56
+ token, err = build_logic_get_api_token(hf_api_key)
57
+ if err or not token: return f"Error getting token: {err or 'Token not found.'}"
58
+ api = HfApi(token=token)
59
+ api.update_repo_visibility(repo_id=repo_id, private=private, repo_type='space')
60
+ return f"Successfully set privacy for {repo_id} to {private}."
61
+ except Exception as e:
62
+ print(f"Error setting privacy: {e}")
63
+ return f"Error setting privacy: {e}"
64
+
65
+ def build_logic_delete_space(hf_api_key, owner, space_name):
66
+ """Deletes an entire Hugging Face Space."""
67
+ repo_id = f"{owner}/{space_name}"
68
+ print(f"[ACTION] Deleting space '{repo_id}'. THIS IS A DESTRUCTIVE ACTION.")
69
+ try:
70
+ token, err = build_logic_get_api_token(hf_api_key)
71
+ if err or not token: return f"Error getting token: {err or 'Token not found.'}"
72
+ api = HfApi(token=token)
73
+ api.delete_repo(repo_id=repo_id, repo_type='space')
74
+ return f"Successfully deleted space {repo_id}."
75
+ except Exception as e:
76
+ print(f"Error deleting space: {e}")
77
+ return f"Error deleting space: {e}"
78
+
79
+
80
+ # --- CORE FIX: Define triple backticks safely to prevent Markdown rendering issues ---
81
+ backtick = chr(96)
82
+ bbb = f'{backtick}{backtick}{backtick}'
83
+
84
+ parsed_code_blocks_state_cache = []
85
+ BOT_ROLE_NAME = "assistant"
86
+
87
+ DEFAULT_SYSTEM_PROMPT = f"""You are an expert AI programmer and Hugging Face assistant. Your role is to generate code and file structures based on user requests, or to modify existing code provided by the user.
88
+
89
+ **File and Code Formatting:**
90
+ When you provide NEW code for a file, or MODIFIED code for an existing file, use the following format exactly:
91
+ ### File: path/to/filename.ext
92
+ (You can add a short, optional, parenthesized description after the filename on the SAME line)
93
+ {bbb}language
94
+ # Your full code here
95
+ {bbb}
96
+
97
+ If the file is binary, or you cannot show its content, use this format:
98
+ ### File: path/to/binaryfile.ext
99
+ [Binary file - approximate_size bytes]
100
+
101
+ When you provide a project file structure, use this format:
102
+ ## File Structure
103
+ {bbb}
104
+ πŸ“ Root
105
+ πŸ“„ file1.py
106
+ πŸ“ subfolder
107
+ πŸ“„ file2.js
108
+ {bbb}
109
+
110
+ **Instructions and Rules:**
111
+ - The role name for your responses in the chat history must be '{BOT_ROLE_NAME}'.
112
+ - Adhere strictly to these formatting instructions.
113
+ - If you update a file, provide the FULL file content again under the same filename.
114
+ - Only the latest version of each file mentioned throughout the chat will be used for the final output. The system will merge your changes with the prior state.
115
+ - Filenames in the '### File:' line should be clean paths (e.g., 'src/app.py', 'Dockerfile') and should NOT include Markdown backticks.
116
+
117
+ **Hugging Face Space Actions:**
118
+ To perform direct actions on the Hugging Face Space, use the `HF_ACTION` command. This is a powerful tool to manage the repository programmatically.
119
+ The format is `### HF_ACTION: COMMAND arguments...` on a single line.
120
+
121
+ Available commands:
122
+ - `CREATE_SPACE owner/repo_name --sdk <sdk> --private <true|false>`: Creates a new, empty space. SDK can be gradio, streamlit, docker, or static. Private is optional and defaults to false.
123
+ - `DELETE_FILE path/to/file.ext`: Deletes a specific file from the current space.
124
+ - `SET_PRIVATE <true|false>`: Sets the privacy for the current space.
125
+ - `DELETE_SPACE`: Deletes the entire current space. THIS IS PERMANENT AND REQUIRES CAUTION.
126
+
127
+ You can issue multiple actions. For example, to delete a file and then add a new one:
128
+ ### HF_ACTION: DELETE_FILE old_app.py
129
+ ### File: new_app.py
130
+ {bbb}python
131
+ # new code
132
+ {bbb}
133
+ Use these actions when the user's request explicitly calls for them (e.g., "delete the readme file", "make this space private", "create a new private space called my-test-app"). If no code is provided, assist the user with their tasks.
134
+ """
135
+
136
+ # --- Helper Functions (largely unchanged) ---
137
+ def escape_html_for_markdown(text):
138
+ if not isinstance(text, str): return ""
139
+ return text.replace("&", "&").replace("<", "<").replace(">", ">")
140
+
141
+ def _infer_lang_from_filename(filename):
142
+ if not filename: return "plaintext"
143
+ if '.' in filename:
144
+ ext = filename.split('.')[-1].lower()
145
+ mapping = {
146
+ 'py': 'python', 'js': 'javascript', 'ts': 'typescript', 'jsx': 'javascript', 'tsx': 'typescript',
147
+ 'html': 'html', 'htm': 'html', 'css': 'css', 'scss': 'scss', 'sass': 'sass', 'less': 'less',
148
+ 'json': 'json', 'xml': 'xml', 'yaml': 'yaml', 'yml': 'yaml', 'toml': 'toml',
149
+ 'md': 'markdown', 'rst': 'rst',
150
+ 'sh': 'bash', 'bash': 'bash', 'zsh': 'bash', 'bat': 'batch', 'cmd': 'batch', 'ps1': 'powershell',
151
+ 'c': 'c', 'h': 'c', 'cpp': 'cpp', 'hpp': 'cpp', 'cs': 'csharp', 'java': 'java',
152
+ 'rb': 'ruby', 'php': 'php', 'go': 'go', 'rs': 'rust', 'swift': 'swift', 'kt': 'kotlin', 'kts': 'kotlin',
153
+ 'sql': 'sql', 'dockerfile': 'docker', 'tf': 'terraform', 'hcl': 'terraform',
154
+ 'txt': 'plaintext', 'log': 'plaintext', 'ini': 'ini', 'conf': 'plaintext', 'cfg': 'plaintext',
155
+ 'csv': 'plaintext', 'tsv': 'plaintext', 'err': 'plaintext',
156
+ '.env': 'plaintext', '.gitignore': 'plaintext', '.npmrc': 'plaintext', '.gitattributes': 'plaintext',
157
+ 'makefile': 'makefile',
158
+ }
159
+ return mapping.get(ext, "plaintext")
160
+ base_filename = os.path.basename(filename)
161
+ if base_filename == 'Dockerfile': return 'docker'
162
+ if base_filename == 'Makefile': return 'makefile'
163
+ if base_filename.startswith('.'): return 'plaintext'
164
+ return "plaintext"
165
+
166
+ def _clean_filename(filename_line_content):
167
+ text = filename_line_content.strip()
168
+ text = re.sub(r'[`\*_]+', '', text)
169
+ path_match = re.match(r'^([\w\-\.\s\/\\]+)', text)
170
+ if path_match:
171
+ parts = re.split(r'\s*\(', path_match.group(1).strip(), 1)
172
+ return parts[0].strip() if parts else ""
173
+ backtick_match = re.search(r'`([^`]+)`', text)
174
+ if backtick_match:
175
+ potential_fn = backtick_match.group(1).strip()
176
+ parts = re.split(r'\s*\(|\s{2,}', potential_fn, 1)
177
+ cleaned_fn = parts[0].strip() if parts else ""
178
+ cleaned_fn = cleaned_fn.strip('`\'":;,')
179
+ if cleaned_fn: return cleaned_fn
180
+ parts = re.split(r'\s*\(|\s{2,}', text, 1)
181
+ filename_candidate = parts[0].strip() if parts else text.strip()
182
+ filename_candidate = filename_candidate.strip('`\'":;,')
183
+ return filename_candidate if filename_candidate else text.strip()
184
+
185
+ def _parse_chat_stream_logic(latest_bot_message_content, existing_files_state=None):
186
+ global parsed_code_blocks_state_cache
187
+ latest_blocks_dict = {}
188
+ if existing_files_state:
189
+ for block in existing_files_state:
190
+ if not block.get("is_structure_block"):
191
+ latest_blocks_dict[block["filename"]] = block.copy()
192
+
193
+ results = {"parsed_code_blocks": [], "preview_md": "", "default_selected_filenames": [], "error_message": None}
194
+ content = latest_bot_message_content or ""
195
+
196
+ file_pattern = re.compile(r"### File:\s*(?P<filename_line>[^\n]+)\n(?:```(?P<lang>[\w\.\-\+]*)\n(?P<code>[\s\S]*?)\n```|(?P<binary_msg>\[Binary file(?: - [^\]]+)?\]))")
197
+ structure_pattern = re.compile(r"## File Structure\n```(?:(?P<struct_lang>[\w.-]*)\n)?(?P<structure_code>[\s\S]*?)\n```")
198
+
199
+ structure_match = structure_pattern.search(content)
200
+ if structure_match:
201
+ latest_blocks_dict["File Structure (original)"] = {"filename": "File Structure (original)", "language": structure_match.group("struct_lang") or "plaintext", "code": structure_match.group("structure_code").strip(), "is_binary": False, "is_structure_block": True}
202
+ else:
203
+ existing_structure_block = next((b for b in parsed_code_blocks_state_cache if b.get("is_structure_block")), None)
204
+ if existing_structure_block:
205
+ latest_blocks_dict["File Structure (original)"] = existing_structure_block.copy()
206
+
207
+ current_message_file_blocks = {}
208
+ for match in file_pattern.finditer(content):
209
+ filename = _clean_filename(match.group("filename_line"))
210
+ if not filename: continue
211
+ lang, code_block, binary_msg = match.group("lang"), match.group("code"), match.group("binary_msg")
212
+ item_data = {"filename": filename, "is_binary": False, "is_structure_block": False}
213
+ if code_block is not None:
214
+ item_data["code"], item_data["language"] = code_block.strip(), (lang.strip().lower() if lang else _infer_lang_from_filename(filename))
215
+ elif binary_msg is not None:
216
+ item_data["code"], item_data["language"], item_data["is_binary"] = binary_msg.strip(), "binary", True
217
+ else: continue
218
+ current_message_file_blocks[filename] = item_data
219
+
220
+ latest_blocks_dict.update(current_message_file_blocks)
221
+ current_parsed_blocks = list(latest_blocks_dict.values())
222
+ current_parsed_blocks.sort(key=lambda b: (0, b["filename"]) if b.get("is_structure_block") else (1, b["filename"]))
223
+ results["parsed_code_blocks"] = current_parsed_blocks
224
+ results["default_selected_filenames"] = [b["filename"] for b in current_parsed_blocks if not b.get("is_structure_block")]
225
+ return results
226
+
227
+ def _export_selected_logic(selected_filenames, space_line_name_for_md, parsed_blocks_for_export):
228
+ results = {"output_str": "", "error_message": None, "download_filepath": None}
229
+ exportable_blocks_content = [b for b in parsed_blocks_for_export if not b.get("is_structure_block") and not b.get("is_binary") and not (b.get("code", "").startswith(("[Error loading content:", "[Binary or Skipped file]")))]
230
+ binary_blocks_content = [b for b in parsed_blocks_for_export if b.get("is_binary") or b.get("code", "").startswith("[Binary or Skipped file]")]
231
+ all_filenames_in_state = sorted(list(set(b["filename"] for b in parsed_blocks_for_export if not b.get("is_structure_block"))))
232
+
233
+ if not all_filenames_in_state and not any(b.get("is_structure_block") for b in parsed_blocks_for_export):
234
+ results["output_str"] = f"# Space: {space_line_name_for_md}\n## File Structure\n{bbb}\nπŸ“ Root\n{bbb}\n\n*No files to list in structure or export.*"
235
+ try:
236
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding='utf-8') as tmpfile:
237
+ tmpfile.write(results["output_str"]); results["download_filepath"] = tmpfile.name
238
+ except Exception as e: print(f"Error creating temp file for empty export: {e}")
239
+ return results
240
+
241
+ output_lines = [f"# Space: {space_line_name_for_md}"]
242
+ structure_block = next((b for b in parsed_blocks_for_export if b.get("is_structure_block")), None)
243
+ if structure_block:
244
+ output_lines.extend(["## File Structure", bbb, structure_block["code"].strip(), bbb, ""])
245
+ else:
246
+ output_lines.extend(["## File Structure", bbb, "πŸ“ Root"])
247
+ if all_filenames_in_state:
248
+ for fname in all_filenames_in_state: output_lines.append(f" πŸ“„ {fname}")
249
+ output_lines.extend([bbb, ""])
250
+
251
+ output_lines.append("Below are the contents of all files in the space:\n")
252
+ files_to_export_content = [b for b in exportable_blocks_content if not selected_filenames or b["filename"] in selected_filenames]
253
+ binary_error_blocks_to_export = [b for b in binary_blocks_content if not selected_filenames or b["filename"] in selected_filenames]
254
+ all_blocks_to_export_content = sorted(files_to_export_content + binary_error_blocks_to_export, key=lambda b: b["filename"])
255
+
256
+ exported_content = False
257
+ for block in all_blocks_to_export_content:
258
+ output_lines.append(f"### File: {block['filename']}")
259
+ if block.get('is_binary') or block.get("code", "").startswith(("[Binary file", "[Error loading content:", "[Binary or Skipped file]")):
260
+ output_lines.append(block.get('code','[Binary or Skipped file]'))
261
+ else:
262
+ output_lines.extend([f"{bbb}{block.get('language', 'plaintext') or 'plaintext'}", block.get('code',''), bbb])
263
+ output_lines.append(""); exported_content = True
264
+
265
+ if not exported_content and not all_filenames_in_state: output_lines.append("*No files in state.*")
266
+ elif not exported_content: output_lines.append("*No files with editable content are in the state or selected.*")
267
+
268
+ final_output_str = "\n".join(output_lines)
269
+ results["output_str"] = final_output_str
270
+ try:
271
+ with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".md", encoding='utf-8') as tmpfile:
272
+ tmpfile.write(final_output_str); results["download_filepath"] = tmpfile.name
273
+ except Exception as e:
274
+ print(f"Error creating temp file: {e}")
275
+ results["error_message"] = "Could not prepare file for download."
276
+ return results
277
+
278
+ def _convert_gr_history_to_api_messages(system_prompt, gr_history, current_user_message=None):
279
+ messages = [{"role": "system", "content": system_prompt}] if system_prompt else []
280
+ for user_msg, bot_msg in gr_history:
281
+ if user_msg: messages.append({"role": "user", "content": user_msg})
282
+ if bot_msg and isinstance(bot_msg, str): messages.append({"role": BOT_ROLE_NAME, "content": bot_msg})
283
+ if current_user_message: messages.append({"role": "user", "content": current_user_message})
284
+ return messages
285
+
286
+ def _generate_ui_outputs_from_cache(owner, space_name):
287
+ global parsed_code_blocks_state_cache
288
+ preview_md_val = "*No files in cache to display.*"
289
+ formatted_md_val = f"# Space: {owner}/{space_name}\n## File Structure\n{bbb}\nπŸ“ Root\n{bbb}\n\n*No files in cache.*" if owner and space_name else "*Load or define a Space to see its Markdown structure.*"
290
+ download_file = None
291
+
292
+ if parsed_code_blocks_state_cache:
293
+ preview_md_lines = ["## Detected/Updated Files & Content (Latest Versions):"]
294
+ for block in parsed_code_blocks_state_cache:
295
+ preview_md_lines.append(f"\n----\n**File:** `{escape_html_for_markdown(block['filename'])}`")
296
+ if block.get('is_structure_block'): preview_md_lines.append(f" (Original File Structure from AI)\n")
297
+ elif block.get('is_binary'): preview_md_lines.append(f" (Binary File)\n")
298
+ else: preview_md_lines.append(f" (Language: `{block['language']}`)\n")
299
+
300
+ content = block.get('code', '')
301
+ if block.get('is_binary') or content.startswith(("[Binary file", "[Error loading content:", "[Binary or Skipped file]")):
302
+ preview_md_lines.append(f"\n`{escape_html_for_markdown(content)}`\n")
303
+ else:
304
+ preview_md_lines.append(f"\n{bbb}{block.get('language', 'plaintext') or 'plaintext'}\n{content}\n{bbb}\n")
305
+ preview_md_val = "\n".join(preview_md_lines)
306
+ space_line_name = f"{owner}/{space_name}" if owner and space_name else (owner or space_name or "your-space")
307
+ export_result = _export_selected_logic(None, space_line_name, parsed_code_blocks_state_cache)
308
+ formatted_md_val = export_result["output_str"]
309
+ download_file = export_result["download_filepath"]
310
+
311
+ return formatted_md_val, preview_md_val, gr.update(value=download_file, interactive=download_file is not None)
312
+
313
+ # --- NEW: Core logic for Change Staging and Confirmation ---
314
+
315
+ def generate_and_stage_changes(ai_response_content, current_files_state, hf_owner_name, hf_repo_name):
316
+ """
317
+ Parses AI response, compares with current state, and generates a structured changeset.
318
+ Returns the changeset and a markdown summary for display.
319
+ """
320
+ changeset = []
321
+ current_files_dict = {f["filename"]: f for f in current_files_state if not f.get("is_structure_block")}
322
+
323
+ # 1. Parse proposed files from AI response
324
+ parsing_result = _parse_chat_stream_logic(ai_response_content, existing_files_state=current_files_state)
325
+ proposed_files = parsing_result.get("parsed_code_blocks", [])
326
+
327
+ # 2. Parse HF_ACTION commands from AI response
328
+ action_pattern = re.compile(r"### HF_ACTION:\s*(?P<command_line>[^\n]+)")
329
+ for match in action_pattern.finditer(ai_response_content):
330
+ cmd_parts = shlex.split(match.group("command_line").strip())
331
+ if not cmd_parts: continue
332
+ command, args = cmd_parts[0].upper(), cmd_parts[1:]
333
+
334
+ # Add actions to the changeset
335
+ if command == "DELETE_FILE" and args:
336
+ changeset.append({"type": "DELETE_FILE", "path": args[0]})
337
+ elif command == "SET_PRIVATE" and args:
338
+ changeset.append({"type": "SET_PRIVACY", "private": args[0].lower() == 'true', "repo_id": f"{hf_owner_name}/{hf_repo_name}"})
339
+ elif command == "DELETE_SPACE":
340
+ changeset.append({"type": "DELETE_SPACE", "owner": hf_owner_name, "space_name": hf_repo_name})
341
+ elif command == "CREATE_SPACE" and args:
342
+ repo_id = args[0]
343
+ sdk = "gradio" # default
344
+ private = False # default
345
+ if '--sdk' in args: sdk = args[args.index('--sdk') + 1]
346
+ if '--private' in args: private = args[args.index('--private') + 1].lower() == 'true'
347
+ changeset.append({"type": "CREATE_SPACE", "repo_id": repo_id, "sdk": sdk, "private": private})
348
+
349
+ # 3. Compare proposed files with current files to determine CREATE/UPDATE
350
+ for file_block in proposed_files:
351
+ if file_block.get("is_structure_block"): continue
352
+
353
+ filename = file_block["filename"]
354
+ if filename not in current_files_dict:
355
+ changeset.append({"type": "CREATE_FILE", "path": filename, "content": file_block["code"], "lang": file_block["language"]})
356
+ elif file_block["code"] != current_files_dict[filename]["code"]:
357
+ changeset.append({"type": "UPDATE_FILE", "path": filename, "content": file_block["code"], "lang": file_block["language"]})
358
+
359
+ # 4. Format the changeset into a human-readable Markdown string
360
+ if not changeset:
361
+ return [], "The AI did not propose any specific changes to files or the space.", parsing_result
362
+
363
+ md_summary = ["### πŸ“‹ Proposed Changes Plan\n"]
364
+ md_summary.append("The AI has proposed the following changes. Please review and confirm.")
365
+
366
+ for change in changeset:
367
+ if change["type"] == "CREATE_FILE":
368
+ md_summary.append(f"- **βž• Create File:** `{change['path']}`")
369
+ elif change["type"] == "UPDATE_FILE":
370
+ md_summary.append(f"- **πŸ”„ Update File:** `{change['path']}`")
371
+ elif change["type"] == "DELETE_FILE":
372
+ md_summary.append(f"- **βž– Delete File:** `{change['path']}`")
373
+ elif change["type"] == "CREATE_SPACE":
374
+ md_summary.append(f"- **πŸš€ Create New Space:** `{change['repo_id']}` (SDK: {change['sdk']}, Private: {change['private']})")
375
+ elif change["type"] == "SET_PRIVACY":
376
+ md_summary.append(f"- **πŸ”’ Set Privacy:** Set `{change['repo_id']}` to `private={change['private']}`")
377
+ elif change["type"] == "DELETE_SPACE":
378
+ md_summary.append(f"- **πŸ’₯ DELETE ENTIRE SPACE:** `{change['owner']}/{change['space_name']}` **(DESTRUCTIVE ACTION)**")
379
+
380
+ return changeset, "\n".join(md_summary), parsing_result
381
+
382
+ # --- Gradio Event Handlers ---
383
+
384
+ def handle_chat_submit(user_message, chat_history, hf_api_key_input, provider_select, model_select, system_prompt, hf_owner_name, hf_repo_name):
385
+ global parsed_code_blocks_state_cache
386
+ _chat_msg_in, _chat_hist = "", list(chat_history)
387
+
388
+ # UI updates for streaming
389
+ yield (
390
+ _chat_msg_in, _chat_hist, "Initializing...",
391
+ gr.update(), gr.update(), gr.update(interactive=False),
392
+ [], gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
393
+ )
394
+
395
+ if not user_message.strip():
396
+ yield (
397
+ _chat_msg_in, _chat_hist, "Cannot send an empty message.",
398
+ gr.update(), gr.update(), gr.update(),
399
+ [], gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
400
+ )
401
+ return
402
+
403
+ _chat_hist.append((user_message, None))
404
+ yield (
405
+ _chat_msg_in, _chat_hist, f"Sending to {model_select}...",
406
+ gr.update(), gr.update(), gr.update(),
407
+ [], gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
408
+ )
409
+
410
+ # Prepare context for the AI
411
+ current_sys_prompt = system_prompt.strip() or DEFAULT_SYSTEM_PROMPT
412
+ export_result = _export_selected_logic(None, f"{hf_owner_name}/{hf_repo_name}", parsed_code_blocks_state_cache)
413
+ current_files_context = f"\n\n## Current Space Context: {hf_owner_name}/{hf_repo_name}\n{export_result['output_str']}"
414
+ user_message_with_context = user_message.strip() + "\n" + current_files_context
415
+ api_msgs = _convert_gr_history_to_api_messages(current_sys_prompt, _chat_hist[:-1], user_message_with_context)
416
+
417
+ try:
418
+ full_bot_response_content = ""
419
+ for chunk in generate_stream(provider_select, model_select, None, api_msgs):
420
+ if chunk is None: continue
421
+ if isinstance(chunk, str) and (chunk.startswith("Error:") or chunk.startswith("API HTTP Error")):
422
+ full_bot_response_content = chunk; break
423
+ full_bot_response_content += str(chunk)
424
+ _chat_hist[-1] = (user_message, full_bot_response_content)
425
+ yield (
426
+ _chat_msg_in, _chat_hist, f"Streaming from {model_select}...",
427
+ gr.update(), gr.update(), gr.update(),
428
+ [], gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
429
+ )
430
+
431
+ if "Error:" in full_bot_response_content:
432
+ _status = full_bot_response_content
433
+ yield (_chat_msg_in, _chat_hist, _status, gr.update(), gr.update(), gr.update(), [], gr.update(), gr.update(), gr.update(), gr.update())
434
+ return
435
+
436
+ # NEW: Instead of applying, generate and stage changes
437
+ _status = "Stream complete. Generating change plan..."
438
+ yield (_chat_msg_in, _chat_hist, _status, gr.update(), gr.update(), gr.update(), [], gr.update(), gr.update(), gr.update(), gr.update())
439
+
440
+ staged_changeset, summary_md, parsing_res = generate_and_stage_changes(full_bot_response_content, parsed_code_blocks_state_cache, hf_owner_name, hf_repo_name)
441
+
442
+ if parsing_res["error_message"]:
443
+ _status = f"Parsing Error: {parsing_res['error_message']}"
444
+ yield (_chat_msg_in, _chat_hist, _status, gr.update(), gr.update(), gr.update(), [], gr.update(), gr.update(), gr.update(), gr.update())
445
+ return
446
+
447
+ if not staged_changeset:
448
+ _status = summary_md # "No changes proposed" message
449
+ # Still update the cache with the AI's *view* of the world, even if no changes.
450
+ parsed_code_blocks_state_cache = parsing_res["parsed_code_blocks"]
451
+ _formatted, _detected, _download = _generate_ui_outputs_from_cache(hf_owner_name, hf_repo_name)
452
+ yield (_chat_msg_in, _chat_hist, _status, _detected, _formatted, _download, [], gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False))
453
+ else:
454
+ _status = "Change plan generated. Please review and confirm below."
455
+ yield (
456
+ _chat_msg_in, _chat_hist, _status,
457
+ gr.update(), gr.update(), gr.update(),
458
+ staged_changeset, # Send changeset to state
459
+ gr.update(value=summary_md), # Display summary
460
+ gr.update(visible=True), # Show the accordion
461
+ gr.update(visible=True), # Show confirm button
462
+ gr.update(visible=True) # Show cancel button
463
+ )
464
+
465
+ except Exception as e:
466
+ error_msg = f"An unexpected error occurred: {e}"
467
+ print(f"Error in handle_chat_submit: {e}")
468
+ if _chat_hist: _chat_hist[-1] = (user_message, error_msg)
469
+ yield (
470
+ _chat_msg_in, _chat_hist, error_msg,
471
+ gr.update(), gr.update(), gr.update(),
472
+ [], gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
473
+ )
474
+
475
+ def handle_confirm_changes(hf_api_key, owner_name, space_name, changeset):
476
+ """Applies the staged changes from the changeset."""
477
+ global parsed_code_blocks_state_cache
478
+ if not changeset:
479
+ return "No changes to apply.", gr.update(), gr.update(), gr.update(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
480
+
481
+ status_messages = []
482
+
483
+ # Handle space creation first, as other ops might depend on it
484
+ create_space_op = next((c for c in changeset if c['type'] == 'CREATE_SPACE'), None)
485
+ if create_space_op:
486
+ repo_parts = create_space_op['repo_id'].split('/')
487
+ if len(repo_parts) == 2:
488
+ owner, repo = repo_parts
489
+ # We need to pass the full markdown for creation. Let's build it from the plan.
490
+ # This is a simplification; a more robust solution would pass the planned files directly.
491
+ # For now, we assume the AI provides file content for the new space.
492
+
493
+ planned_files_md = [f"# Space: {create_space_op['repo_id']}"]
494
+ for change in changeset:
495
+ if change['type'] in ['CREATE_FILE', 'UPDATE_FILE']:
496
+ planned_files_md.append(f"### File: {change['path']}\n{bbb}{change.get('lang', 'plaintext')}\n{change['content']}\n{bbb}")
497
+
498
+ markdown_for_creation = "\n\n".join(planned_files_md)
499
+
500
+ result = build_logic_create_space(
501
+ ui_api_token_from_textbox=hf_api_key,
502
+ space_name_ui=repo,
503
+ owner_ui=owner,
504
+ sdk_ui=create_space_op['sdk'],
505
+ private=create_space_op['private'],
506
+ markdown_input=markdown_for_creation
507
+ )
508
+ status_messages.append(f"CREATE_SPACE: {result}")
509
+ if "Error" in result:
510
+ # Stop if space creation failed
511
+ final_status = " | ".join(status_messages)
512
+ return final_status, gr.update(), gr.update(), gr.update(), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), []
513
+
514
+ # Apply all other changes
515
+ for change in changeset:
516
+ try:
517
+ if change['type'] == 'UPDATE_FILE':
518
+ msg = update_space_file(hf_api_key, space_name, owner_name, change['path'], change['content'], f"AI: Update {change['path']}")
519
+ status_messages.append(f"UPDATE '{change['path']}': {msg}")
520
+ if "Success" in msg:
521
+ # Update cache on success
522
+ for block in parsed_code_blocks_state_cache:
523
+ if block['filename'] == change['path']:
524
+ block['code'] = change['content']
525
+ break
526
+ elif change['type'] == 'CREATE_FILE' and not create_space_op: # Don't re-create if handled by CREATE_SPACE
527
+ msg = update_space_file(hf_api_key, space_name, owner_name, change['path'], change['content'], f"AI: Create {change['path']}")
528
+ status_messages.append(f"CREATE '{change['path']}': {msg}")
529
+ if "Success" in msg:
530
+ parsed_code_blocks_state_cache.append({'filename': change['path'], 'code': change['content'], 'language': change['lang'], 'is_binary': False})
531
+ elif change['type'] == 'DELETE_FILE':
532
+ msg = build_logic_delete_space_file(hf_api_key, space_name, owner_name, change['path'])
533
+ status_messages.append(f"DELETE '{change['path']}': {msg}")
534
+ if "Success" in msg:
535
+ parsed_code_blocks_state_cache = [b for b in parsed_code_blocks_state_cache if b["filename"] != change['path']]
536
+ elif change['type'] == 'SET_PRIVACY':
537
+ msg = build_logic_set_space_privacy(hf_api_key, change['repo_id'], change['private'])
538
+ status_messages.append(f"SET_PRIVACY: {msg}")
539
+ elif change['type'] == 'DELETE_SPACE':
540
+ msg = build_logic_delete_space(hf_api_key, change['owner'], change['space_name'])
541
+ status_messages.append(f"DELETE_SPACE: {msg}")
542
+ if "Success" in msg:
543
+ parsed_code_blocks_state_cache = [] # Clear everything
544
+ except Exception as e:
545
+ status_messages.append(f"Error applying {change['type']} for {change.get('path', '')}: {e}")
546
+
547
+ final_status = " | ".join(status_messages)
548
+ _formatted, _detected, _download = _generate_ui_outputs_from_cache(owner_name, space_name)
549
+
550
+ # Hide the confirmation UI and clear the state
551
+ return final_status, _formatted, _detected, _download, gr.update(visible=False), gr.update(visible=False), gr.update(visible=False), []
552
+
553
+ def handle_cancel_changes():
554
+ """Clears the staged changeset and hides the confirmation UI."""
555
+ return "Changes cancelled.", [], gr.update(value="*No changes proposed.*"), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
556
+
557
+ def update_models_dropdown(provider_select):
558
+ if not provider_select: return gr.update(choices=[], value=None)
559
+ models = get_models_for_provider(provider_select)
560
+ default_model = get_default_model_for_provider(provider_select)
561
+ selected_value = default_model if default_model in models else (models[0] if models else None)
562
+ return gr.update(choices=models, value=selected_value)
563
+
564
+ def handle_load_existing_space(hf_api_key_ui, ui_owner_name, ui_space_name):
565
+ global parsed_code_blocks_state_cache
566
+ _formatted_md_val, _detected_preview_val, _status_val = "*Loading files...*", "*Loading files...*", f"Loading Space: {ui_owner_name}/{ui_space_name}..."
567
+ _file_browser_update, _iframe_html_update, _download_btn_update = gr.update(visible=False, choices=[], value=None), gr.update(value=None, visible=False), gr.update(interactive=False, value=None)
568
+ _build_status_clear, _edit_status_clear, _runtime_status_clear = "*Build status...*", "*Select a file...*", "*Runtime status...*"
569
+ _chat_history_clear = []
570
+ outputs = [_formatted_md_val, _detected_preview_val, _status_val, _file_browser_update, gr.update(value=ui_owner_name), gr.update(value=ui_space_name), _iframe_html_update, _download_btn_update, _build_status_clear, _edit_status_clear, _runtime_status_clear, _chat_history_clear]
571
+ yield outputs
572
+
573
+ owner_to_use = ui_owner_name
574
+ if not owner_to_use:
575
+ token, err = build_logic_get_api_token(hf_api_key_ui)
576
+ if err or not token:
577
+ _status_val = f"Error: {err or 'Cannot determine owner from token.'}"
578
+ outputs[2] = _status_val; yield outputs; return
579
+ try:
580
+ user_info = build_logic_whoami(token=token)
581
+ owner_to_use = user_info.get('name')
582
+ if not owner_to_use: raise Exception("Could not find user name from token.")
583
+ outputs[4] = gr.update(value=owner_to_use)
584
+ _status_val += f" (Auto-detected owner: {owner_to_use})"
585
+ except Exception as e:
586
+ _status_val = f"Error auto-detecting owner: {e}"; outputs[2] = _status_val; yield outputs; return
587
+
588
+ if not owner_to_use or not ui_space_name:
589
+ _status_val = "Error: Owner and Space Name are required."; outputs[2] = _status_val; yield outputs; return
590
+
591
+ sdk, file_list, err = get_space_repository_info(hf_api_key_ui, ui_space_name, owner_to_use)
592
+ if err and not file_list:
593
+ _status_val = f"File List Error: {err}"; parsed_code_blocks_state_cache = []
594
+ _formatted, _detected, _download = _generate_ui_outputs_from_cache(owner_to_use, ui_space_name)
595
+ outputs[0], outputs[1], outputs[2], outputs[7] = _formatted, _detected, _status_val, _download
596
+ yield outputs; return
597
+
598
+ sub_owner = re.sub(r'[^a-z0-9\-]+', '-', owner_to_use.lower()).strip('-') or 'owner'
599
+ sub_repo = re.sub(r'[^a-z0-9\-]+', '-', ui_space_name.lower()).strip('-') or 'space'
600
+ iframe_url = f"https://{sub_owner}-{sub_repo}{'.static.hf.space' if sdk == 'static' else '.hf.space'}"
601
+ outputs[6] = gr.update(value=f'<iframe src="{iframe_url}?__theme=light&embed=true" width="100%" height="500px"></iframe>', visible=True)
602
+
603
+ loaded_files = []
604
+ for file_path in file_list:
605
+ content, err_get = get_space_file_content(hf_api_key_ui, ui_space_name, owner_to_use, file_path)
606
+ lang = _infer_lang_from_filename(file_path)
607
+ is_binary = lang == "binary" or err_get
608
+ code = f"[Error loading content: {err_get}]" if err_get else content
609
+ loaded_files.append({"filename": file_path, "code": code, "language": lang, "is_binary": is_binary, "is_structure_block": False})
610
+
611
+ parsed_code_blocks_state_cache = loaded_files
612
+ _formatted, _detected, _download = _generate_ui_outputs_from_cache(owner_to_use, ui_space_name)
613
+ _status_val = f"Successfully loaded {len(file_list)} files from {owner_to_use}/{ui_space_name}."
614
+ outputs[0], outputs[1], outputs[2], outputs[7] = _formatted, _detected, _status_val, _download
615
+ outputs[3] = gr.update(visible=True, choices=sorted(file_list or []), value=None)
616
+ yield outputs
617
+
618
+ def handle_build_space_button(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, space_sdk_ui, is_private_ui, formatted_markdown_content):
619
+ _build_status, _iframe_html, _file_browser_update = "Starting space build process...", gr.update(value=None, visible=False), gr.update(visible=False, choices=[], value=None)
620
+ yield _build_status, _iframe_html, _file_browser_update, gr.update(value=ui_owner_name_part), gr.update(value=ui_space_name_part)
621
+ if not ui_space_name_part or "/" in ui_space_name_part:
622
+ _build_status = f"Build Error: Invalid Space Name '{ui_space_name_part}'."
623
+ yield _build_status, _iframe_html, _file_browser_update, gr.update(), gr.update(); return
624
+
625
+ result_message = build_logic_create_space(ui_api_token_from_textbox=hf_api_key_ui, space_name_ui=ui_space_name_part, owner_ui=ui_owner_name_part, sdk_ui=space_sdk_ui, markdown_input=formatted_markdown_content, private=is_private_ui)
626
+ _build_status = f"Build Process: {result_message}"
627
+
628
+ if "Successfully" in result_message:
629
+ sub_owner = re.sub(r'[^a-z0-9\-]+', '-', ui_owner_name_part.lower()).strip('-')
630
+ sub_repo = re.sub(r'[^a-z0-9\-]+', '-', ui_space_name_part.lower()).strip('-')
631
+ iframe_url = f"https://{sub_owner}-{sub_repo}{'.static.hf.space' if space_sdk_ui == 'static' else '.hf.space'}"
632
+ _iframe_html = gr.update(value=f'<iframe src="{iframe_url}?__theme=light&embed=true" width="100%" height="700px"></iframe>', visible=True)
633
+ file_list, err = list_space_files_for_browsing(hf_api_key_ui, ui_space_name_part, ui_owner_name_part)
634
+ _file_browser_update = gr.update(visible=True, choices=sorted(file_list or []), value=None)
635
+ yield _build_status, _iframe_html, _file_browser_update, gr.update(value=ui_owner_name_part), gr.update(value=ui_space_name_part)
636
+
637
+ def handle_load_file_for_editing(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, selected_file_path):
638
+ if not selected_file_path:
639
+ yield gr.update(value=""), "Select a file.", gr.update(value=""), gr.update(language="plaintext")
640
+ return
641
+
642
+ content, err = get_space_file_content(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, selected_file_path)
643
+ if err:
644
+ yield f"Error: {err}", f"Error loading '{selected_file_path}': {err}", "", gr.update(language="plaintext")
645
+ return
646
+
647
+ lang = _infer_lang_from_filename(selected_file_path)
648
+ commit_msg = f"Update {selected_file_path}"
649
+ yield content, f"Loaded {selected_file_path}", commit_msg, gr.update(language=lang)
650
+
651
+ def handle_commit_file_changes(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, file_to_edit_path, edited_content, commit_message):
652
+ status_msg = update_space_file(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, file_to_edit_path, edited_content, commit_message)
653
+ file_list, _ = list_space_files_for_browsing(hf_api_key_ui, ui_space_name_part, ui_owner_name_part)
654
+ global parsed_code_blocks_state_cache
655
+ if "Successfully" in status_msg:
656
+ # Update cache
657
+ for block in parsed_code_blocks_state_cache:
658
+ if block["filename"] == file_to_edit_path:
659
+ block["code"] = edited_content
660
+ break
661
+ _formatted, _detected, _download = _generate_ui_outputs_from_cache(ui_owner_name_part, ui_space_name_part)
662
+ return status_msg, gr.update(choices=sorted(file_list or [])), _formatted, _detected, _download
663
+
664
+ def handle_delete_file(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, file_to_delete_path):
665
+ if not file_to_delete_path:
666
+ return "No file selected to delete.", gr.update(), "", "", "plaintext", gr.update(), gr.update(), gr.update()
667
+
668
+ status_msg = build_logic_delete_space_file(hf_api_key_ui, ui_space_name_part, ui_owner_name_part, file_to_delete_path)
669
+ file_list, _ = list_space_files_for_browsing(hf_api_key_ui, ui_space_name_part, ui_owner_name_part)
670
+ global parsed_code_blocks_state_cache
671
+ if "Successfully" in status_msg:
672
+ parsed_code_blocks_state_cache = [b for b in parsed_code_blocks_state_cache if b["filename"] != file_to_delete_path]
673
+ _formatted, _detected, _download = _generate_ui_outputs_from_cache(ui_owner_name_part, ui_space_name_part)
674
+ return status_msg, gr.update(choices=sorted(file_list or []), value=None), "", "", "plaintext", _formatted, _detected, _download
675
+
676
+ def handle_refresh_space_status(hf_api_key_ui, ui_owner_name, ui_space_name):
677
+ if not ui_owner_name or not ui_space_name:
678
+ return "Owner and Space Name must be provided to get status."
679
+
680
+ status, err = get_space_runtime_status(hf_api_key_ui, ui_space_name, ui_owner_name)
681
+ if err: return f"**Error:** {err}"
682
+ if not status: return "Could not retrieve status."
683
+
684
+ md = f"### Status for {ui_owner_name}/{ui_space_name}\n"
685
+ for key, val in status.items():
686
+ md += f"- **{key.replace('_', ' ').title()}:** `{val}`\n"
687
+ return md
688
+
689
+ # --- UI Theming and CSS (Unchanged) ---
690
+ custom_theme = gr.themes.Base(primary_hue="teal", secondary_hue="purple", neutral_hue="zinc", text_size="sm", spacing_size="md", radius_size="sm", font=["System UI", "sans-serif"])
691
+ custom_css = """
692
+ body { background: linear-gradient(to bottom right, #2c3e50, #34495e); color: #ecf0f1; }
693
+ .gradio-container { background: transparent !important; }
694
+ .gr-box, .gr-panel, .gr-pill { background-color: rgba(44, 62, 80, 0.8) !important; border-color: rgba(189, 195, 199, 0.2) !important; }
695
+ .gr-textbox, .gr-dropdown, .gr-button, .gr-code, .gr-chat-message { border-color: rgba(189, 195, 199, 0.3) !important; background-color: rgba(52, 73, 94, 0.9) !important; color: #ecf0f1 !important; }
696
+ .gr-button.gr-button-primary { background-color: #1abc9c !important; color: white !important; border-color: #16a085 !important; }
697
+ .gr-button.gr-button-secondary { background-color: #9b59b6 !important; color: white !important; border-color: #8e44ad !important; }
698
+ .gr-button.gr-button-stop { background-color: #e74c3c !important; color: white !important; border-color: #c0392b !important; }
699
+ .gr-markdown { background-color: rgba(44, 62, 80, 0.7) !important; padding: 10px; border-radius: 5px; }
700
+ .gr-markdown h1, .gr-markdown h2, .gr-markdown h3, .gr-markdown h4, .gr-markdown h5, .gr-markdown h6 { color: #ecf0f1 !important; border-bottom-color: rgba(189, 195, 199, 0.3) !important; }
701
+ .gr-markdown pre code { background-color: rgba(52, 73, 94, 0.95) !important; border-color: rgba(189, 195, 199, 0.3) !important; }
702
+ .gr-chatbot { background-color: rgba(44, 62, 80, 0.7) !important; border-color: rgba(189, 195, 199, 0.2) !important; }
703
+ .gr-chatbot .message { background-color: rgba(52, 73, 94, 0.9) !important; color: #ecf0f1 !important; border-color: rgba(189, 195, 199, 0.3) !important; }
704
+ .gr-chatbot .message.user { background-color: rgba(46, 204, 113, 0.9) !important; color: black !important; }
705
+ """
706
+
707
+ # --- Gradio UI Definition ---
708
+ with gr.Blocks(theme=custom_theme, css=custom_css) as demo:
709
+ # --- NEW: State to hold the plan ---
710
+ changeset_state = gr.State([])
711
+
712
+ gr.Markdown("# πŸ€– AI-Powered Hugging Face Space Builder")
713
+ gr.Markdown("Use an AI assistant to create, modify, build, and manage your Hugging Face Spaces directly from this interface.")
714
+
715
+ with gr.Row():
716
+ with gr.Column(scale=1):
717
+ with gr.Accordion("βš™οΈ Configuration", open=True):
718
+ hf_api_key_input = gr.Textbox(label="Hugging Face Token", type="password", placeholder="hf_... (uses env var HF_TOKEN if empty)")
719
+ owner_name_input = gr.Textbox(label="HF Owner Name", placeholder="e.g., your-username")
720
+ space_name_input = gr.Textbox(label="HF Space Name", value="my-ai-space")
721
+ load_space_button = gr.Button("πŸ”„ Load Existing Space", variant="secondary")
722
+
723
+ with gr.Accordion("πŸ€– AI Model Settings", open=True):
724
+ provider_select = gr.Dropdown(label="AI Provider", choices=get_available_providers(), value=get_default_model_for_provider(get_available_providers()[0] if get_available_providers() else None))
725
+ model_select = gr.Dropdown(label="AI Model", choices=[])
726
+ system_prompt_input = gr.Textbox(label="System Prompt", lines=10, value=DEFAULT_SYSTEM_PROMPT, elem_id="system-prompt")
727
+
728
+ with gr.Column(scale=2):
729
+ gr.Markdown("## πŸ’¬ AI Assistant Chat")
730
+ chatbot_display = gr.Chatbot(label="AI Chat", height=500, bubble_full_width=False, avatar_images=(None, "https://huggingface.co/datasets/huggingface/badges/resolve/main/huggingface-bot-avatar.svg"))
731
+ with gr.Row():
732
+ chat_message_input = gr.Textbox(show_label=False, placeholder="Your Message...", scale=7)
733
+ send_chat_button = gr.Button("Send", variant="primary", scale=1)
734
+ status_output = gr.Textbox(label="Last Action Status", interactive=False, value="Ready.")
735
+
736
+ # --- NEW: Confirmation Accordion ---
737
+ with gr.Accordion("πŸ“ Proposed Changes (Pending Confirmation)", visible=False) as confirm_accordion:
738
+ changeset_display = gr.Markdown("No changes proposed.")
739
+ with gr.Row():
740
+ confirm_button = gr.Button("βœ… Confirm & Apply Changes", variant="primary", visible=False)
741
+ cancel_button = gr.Button("❌ Cancel", variant="stop", visible=False)
742
+
743
+ with gr.Tabs():
744
+ with gr.TabItem("πŸ“ Generated Markdown & Build"):
745
+ with gr.Row():
746
+ with gr.Column(scale=2):
747
+ formatted_space_output_display = gr.Textbox(label="Current Space Definition (Editable)", lines=20, interactive=True, value="*Load or create a space to see its definition.*")
748
+ download_button = gr.DownloadButton(label="Download .md", interactive=False)
749
+ with gr.Column(scale=1):
750
+ gr.Markdown("### Build Controls")
751
+ space_sdk_select = gr.Dropdown(label="Space SDK", choices=["gradio", "streamlit", "docker", "static"], value="gradio")
752
+ space_private_checkbox = gr.Checkbox(label="Make Space Private", value=False)
753
+ build_space_button = gr.Button("πŸš€ Build / Update Space from Manual Edit", variant="primary")
754
+ build_status_display = gr.Textbox(label="Build Operation Status", interactive=False)
755
+ refresh_status_button = gr.Button("πŸ”„ Refresh Runtime Status")
756
+ space_runtime_status_display = gr.Markdown("*Runtime status will appear here.*")
757
+
758
+ with gr.TabItem("πŸ” Files Preview"):
759
+ detected_files_preview = gr.Markdown(value="*A preview of the latest file versions will appear here.*")
760
+
761
+ with gr.TabItem("✏️ Live File Editor & Preview"):
762
+ with gr.Row():
763
+ with gr.Column(scale=1):
764
+ gr.Markdown("### Live Editor")
765
+ file_browser_dropdown = gr.Dropdown(label="Select File in Space", choices=[], interactive=True)
766
+ file_content_editor = gr.Code(label="File Content Editor", language="python", lines=15, interactive=True)
767
+ commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Updated app.py")
768
+ with gr.Row():
769
+ update_file_button = gr.Button("Commit Changes", variant="primary")
770
+ delete_file_button = gr.Button("πŸ—‘οΈ Delete Selected File", variant="stop")
771
+ edit_status_display = gr.Textbox(label="File Edit/Delete Status", interactive=False)
772
+ with gr.Column(scale=1):
773
+ gr.Markdown("### Live Space Preview")
774
+ space_iframe_display = gr.HTML(value="", visible=True)
775
+
776
+ # --- Event Listeners ---
777
+ provider_select.change(update_models_dropdown, inputs=provider_select, outputs=model_select)
778
+
779
+ chat_inputs = [chat_message_input, chatbot_display, hf_api_key_input, provider_select, model_select, system_prompt_input, owner_name_input, space_name_input]
780
+ chat_outputs = [
781
+ chat_message_input, chatbot_display, status_output,
782
+ detected_files_preview, formatted_space_output_display, download_button,
783
+ changeset_state, changeset_display, confirm_accordion, confirm_button, cancel_button
784
+ ]
785
+ send_chat_button.click(handle_chat_submit, inputs=chat_inputs, outputs=chat_outputs)
786
+ chat_message_input.submit(handle_chat_submit, inputs=chat_inputs, outputs=chat_outputs)
787
+
788
+ # --- NEW: Confirmation Button Listeners ---
789
+ confirm_inputs = [hf_api_key_input, owner_name_input, space_name_input, changeset_state]
790
+ confirm_outputs = [
791
+ status_output, formatted_space_output_display, detected_files_preview, download_button,
792
+ confirm_accordion, confirm_button, cancel_button, changeset_state
793
+ ]
794
+ confirm_button.click(handle_confirm_changes, inputs=confirm_inputs, outputs=confirm_outputs)
795
+
796
+ cancel_outputs = [
797
+ status_output, changeset_state, changeset_display,
798
+ confirm_accordion, confirm_button, cancel_button
799
+ ]
800
+ cancel_button.click(handle_cancel_changes, inputs=None, outputs=cancel_outputs)
801
+
802
+
803
+ load_space_outputs = [formatted_space_output_display, detected_files_preview, status_output, file_browser_dropdown, owner_name_input, space_name_input, space_iframe_display, download_button, build_status_display, edit_status_display, space_runtime_status_display, chatbot_display]
804
+ load_space_button.click(fn=handle_load_existing_space, inputs=[hf_api_key_input, owner_name_input, space_name_input], outputs=load_space_outputs)
805
+
806
+ build_outputs = [build_status_display, space_iframe_display, file_browser_dropdown, owner_name_input, space_name_input]
807
+ build_inputs = [hf_api_key_input, space_name_input, owner_name_input, space_sdk_select, space_private_checkbox, formatted_space_output_display]
808
+ build_space_button.click(fn=handle_build_space_button, inputs=build_inputs, outputs=build_outputs)
809
+
810
+ file_edit_load_outputs = [file_content_editor, edit_status_display, commit_message_input, file_content_editor] # last one updates language
811
+ file_browser_dropdown.change(fn=handle_load_file_for_editing, inputs=[hf_api_key_input, space_name_input, owner_name_input, file_browser_dropdown], outputs=file_edit_load_outputs)
812
+
813
+ commit_file_outputs = [edit_status_display, file_browser_dropdown, formatted_space_output_display, detected_files_preview, download_button]
814
+ update_file_button.click(fn=handle_commit_file_changes, inputs=[hf_api_key_input, space_name_input, owner_name_input, file_browser_dropdown, file_content_editor, commit_message_input], outputs=commit_file_outputs)
815
+
816
+ delete_file_outputs = [edit_status_display, file_browser_dropdown, file_content_editor, commit_message_input, file_content_editor, formatted_space_output_display, detected_files_preview, download_button]
817
+ delete_file_button.click(fn=handle_delete_file, inputs=[hf_api_key_input, space_name_input, owner_name_input, file_browser_dropdown], outputs=delete_file_outputs)
818
+
819
+ refresh_status_button.click(fn=handle_refresh_space_status, inputs=[hf_api_key_input, owner_name_input, space_name_input], outputs=[space_runtime_status_display])
820
+
821
+ if __name__ == "__main__":
822
+ demo.launch(debug=True)