Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -93,16 +93,16 @@ def _clean_filename(filename_line_content):
|
|
93 |
path_match = re.match(r'^([\w\-\.\s\/\\]+)', text) # Adjusted to be more general
|
94 |
if path_match:
|
95 |
# Further clean if it looks like "path/to/file (description)"
|
96 |
-
return re.split(r'\s*\(', path_match.group(1).strip(), 1).strip()
|
97 |
|
98 |
# Fallback for more complex lines, like "### File: `src/app.py` (main application)"
|
99 |
backtick_match = re.search(r'`([^`]+)`', text)
|
100 |
if backtick_match:
|
101 |
potential_fn = backtick_match.group(1).strip()
|
102 |
-
cleaned_fn = re.split(r'\s*\(|\s{2,}', potential_fn, 1).strip()
|
103 |
if cleaned_fn: return cleaned_fn
|
104 |
|
105 |
-
filename_candidate = re.split(r'\s*\(|\s{2,}', text, 1).strip()
|
106 |
filename_candidate = filename_candidate.strip('`\'":;,') # Clean common wrapping chars
|
107 |
return filename_candidate if filename_candidate else text # Fallback to original if all else fails
|
108 |
|
@@ -200,8 +200,7 @@ def _convert_gr_history_to_api_messages(system_prompt, gr_history, current_user_
|
|
200 |
return messages
|
201 |
|
202 |
def get_latest_bot_message_as_json(gr_history):
|
203 |
-
|
204 |
-
if not gr_history or not gr_history[-1] or len(gr_history[-1]) < 2 or not gr_history[-1]:
|
205 |
return json.dumps([])
|
206 |
return json.dumps([{"role": BOT_ROLE_NAME, "content": gr_history[-1]}], indent=2)
|
207 |
|
@@ -233,7 +232,7 @@ def _generate_ui_outputs_from_cache(owner, space_name):
|
|
233 |
formatted_md_val = f"# Space: {owner or 'owner'}/{space_name or 'space'}\n## File Structure\n{bbb}\nπ Root\n{bbb}\n\n*No files found or defined for this Space.*" if owner and space_name else "*Load or define a Space to see its Markdown structure.*"
|
234 |
return formatted_md_val, preview_md_val, gr.update(value=download_file, interactive=download_file is not None)
|
235 |
|
236 |
-
def handle_groq_chat_submit(user_message, chat_history, api_key_input, model_select, system_prompt, hf_owner_name, hf_repo_name, _current_formatted_markdown):
|
237 |
global parsed_code_blocks_state_cache
|
238 |
_chat_msg_in, _chat_hist, _status = "", list(chat_history), "Initializing..."
|
239 |
_detected_files_update, _formatted_output_update, _download_btn_update = gr.update(), gr.update(), gr.update(interactive=False, value=None)
|
@@ -253,27 +252,35 @@ def handle_groq_chat_submit(user_message, chat_history, api_key_input, model_sel
|
|
253 |
_status = f"Waiting for {model_select}..."; yield (_chat_msg_in, _chat_hist, _status, _detected_files_update, _formatted_output_update, _download_btn_update)
|
254 |
response = requests.post(GROQ_API_ENDPOINT, headers=headers, json=payload, timeout=180); response.raise_for_status()
|
255 |
api_resp_json = response.json()
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
272 |
_chat_hist[-1] = (user_message, error_msg); _status = error_msg
|
273 |
except requests.exceptions.HTTPError as e: error_msg = f"API HTTP Error: {e} - {e.response.text if e.response else 'No details'}"
|
274 |
except requests.exceptions.RequestException as e: error_msg = f"API Request Error: {e}"
|
275 |
except Exception as e: error_msg = f"Unexpected error in chat submit: {e}"
|
276 |
-
|
|
|
|
|
277 |
_status = error_msg
|
278 |
yield (_chat_msg_in, _chat_hist, _status, _detected_files_update, _formatted_output_update, _download_btn_update)
|
279 |
|
@@ -464,7 +471,7 @@ with gr.Blocks(theme=gr.themes.Soft(primary_hue="teal", secondary_hue="orange"))
|
|
464 |
with gr.TabItem("βοΈ Edit Space Files"):
|
465 |
gr.Markdown("Select a file to view, edit, or delete. Changes are committed to HF Hub.")
|
466 |
file_browser_dropdown = gr.Dropdown(label="Select File in Space", choices=[], interactive=True, visible=False, info="Load/build Space first.")
|
467 |
-
file_content_editor = gr.Code(label="File Content Editor", language="python", lines=15, interactive=True)
|
468 |
commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Updated app.py", value="Update via AI Space Editor")
|
469 |
with gr.Row(): update_file_button = gr.Button("Commit Changes", variant="primary", scale=2); delete_file_button = gr.Button("ποΈ Delete Selected File", variant="stop", scale=1)
|
470 |
edit_status_display = gr.Textbox(label="File Edit/Delete Status", interactive=False, lines=2, value="*Select file...*")
|
|
|
93 |
path_match = re.match(r'^([\w\-\.\s\/\\]+)', text) # Adjusted to be more general
|
94 |
if path_match:
|
95 |
# Further clean if it looks like "path/to/file (description)"
|
96 |
+
return re.split(r'\s*\(', path_match.group(1).strip(), 1).strip() # Corrected split index
|
97 |
|
98 |
# Fallback for more complex lines, like "### File: `src/app.py` (main application)"
|
99 |
backtick_match = re.search(r'`([^`]+)`', text)
|
100 |
if backtick_match:
|
101 |
potential_fn = backtick_match.group(1).strip()
|
102 |
+
cleaned_fn = re.split(r'\s*\(|\s{2,}', potential_fn, 1).strip() # Corrected split index
|
103 |
if cleaned_fn: return cleaned_fn
|
104 |
|
105 |
+
filename_candidate = re.split(r'\s*\(|\s{2,}', text, 1).strip() # Corrected split index
|
106 |
filename_candidate = filename_candidate.strip('`\'":;,') # Clean common wrapping chars
|
107 |
return filename_candidate if filename_candidate else text # Fallback to original if all else fails
|
108 |
|
|
|
200 |
return messages
|
201 |
|
202 |
def get_latest_bot_message_as_json(gr_history):
|
203 |
+
if not gr_history or not gr_history[-1] or len(gr_history[-1]) < 2 or not gr_history[-1]: # Check bot message at index 1
|
|
|
204 |
return json.dumps([])
|
205 |
return json.dumps([{"role": BOT_ROLE_NAME, "content": gr_history[-1]}], indent=2)
|
206 |
|
|
|
232 |
formatted_md_val = f"# Space: {owner or 'owner'}/{space_name or 'space'}\n## File Structure\n{bbb}\nπ Root\n{bbb}\n\n*No files found or defined for this Space.*" if owner and space_name else "*Load or define a Space to see its Markdown structure.*"
|
233 |
return formatted_md_val, preview_md_val, gr.update(value=download_file, interactive=download_file is not None)
|
234 |
|
235 |
+
def handle_groq_chat_submit(user_message, chat_history, api_key_input, model_select, system_prompt, hf_owner_name, hf_repo_name, _current_formatted_markdown):
|
236 |
global parsed_code_blocks_state_cache
|
237 |
_chat_msg_in, _chat_hist, _status = "", list(chat_history), "Initializing..."
|
238 |
_detected_files_update, _formatted_output_update, _download_btn_update = gr.update(), gr.update(), gr.update(interactive=False, value=None)
|
|
|
252 |
_status = f"Waiting for {model_select}..."; yield (_chat_msg_in, _chat_hist, _status, _detected_files_update, _formatted_output_update, _download_btn_update)
|
253 |
response = requests.post(GROQ_API_ENDPOINT, headers=headers, json=payload, timeout=180); response.raise_for_status()
|
254 |
api_resp_json = response.json()
|
255 |
+
|
256 |
+
bot_response_actual = None
|
257 |
+
if api_resp_json.get("choices") and len(api_resp_json["choices"]) > 0:
|
258 |
+
message_obj = api_resp_json["choices"].get("message")
|
259 |
+
if message_obj and isinstance(message_obj, dict): # Check if message_obj is a dict
|
260 |
+
bot_response_actual = message_obj.get("content")
|
261 |
+
|
262 |
+
if bot_response_actual:
|
263 |
+
_chat_hist[-1] = (user_message, bot_response_actual); _status = "AI response received. Processing files..."
|
264 |
+
yield (_chat_msg_in, _chat_hist, _status, _detected_files_update, _formatted_output_update, _download_btn_update)
|
265 |
+
latest_bot_message_json = get_latest_bot_message_as_json(_chat_hist)
|
266 |
+
parsing_res = _parse_chat_stream_logic(latest_bot_message_json, existing_files_state=parsed_code_blocks_state_cache)
|
267 |
+
if parsing_res["error_message"]:
|
268 |
+
_status = f"Parsing Error: {parsing_res['error_message']}"
|
269 |
+
_detected_files_update = gr.Markdown(f"## Parsing Error\n`{escape_html_for_markdown(parsing_res['error_message'])}`")
|
270 |
+
else:
|
271 |
+
_formatted_output_update, _detected_files_update, _download_btn_update = _generate_ui_outputs_from_cache(hf_owner_name, hf_repo_name)
|
272 |
+
_status = "Processing complete. Previews updated."
|
273 |
+
yield (_chat_msg_in, _chat_hist, _status, _detected_files_update, _formatted_output_update, _download_btn_update); return
|
274 |
+
else:
|
275 |
+
error_msg = f"API Error: Unexpected response structure or empty message content. Response: {json.dumps(api_resp_json)}"
|
276 |
+
|
277 |
_chat_hist[-1] = (user_message, error_msg); _status = error_msg
|
278 |
except requests.exceptions.HTTPError as e: error_msg = f"API HTTP Error: {e} - {e.response.text if e.response else 'No details'}"
|
279 |
except requests.exceptions.RequestException as e: error_msg = f"API Request Error: {e}"
|
280 |
except Exception as e: error_msg = f"Unexpected error in chat submit: {e}"
|
281 |
+
|
282 |
+
if _chat_hist and len(_chat_hist[-1]) == 2 and _chat_hist[-1] is None:
|
283 |
+
_chat_hist[-1] = (user_message, error_msg)
|
284 |
_status = error_msg
|
285 |
yield (_chat_msg_in, _chat_hist, _status, _detected_files_update, _formatted_output_update, _download_btn_update)
|
286 |
|
|
|
471 |
with gr.TabItem("βοΈ Edit Space Files"):
|
472 |
gr.Markdown("Select a file to view, edit, or delete. Changes are committed to HF Hub.")
|
473 |
file_browser_dropdown = gr.Dropdown(label="Select File in Space", choices=[], interactive=True, visible=False, info="Load/build Space first.")
|
474 |
+
file_content_editor = gr.Code(label="File Content Editor", language="python", lines=15, interactive=True) # Changed language to python from plaintext
|
475 |
commit_message_input = gr.Textbox(label="Commit Message", placeholder="e.g., Updated app.py", value="Update via AI Space Editor")
|
476 |
with gr.Row(): update_file_button = gr.Button("Commit Changes", variant="primary", scale=2); delete_file_button = gr.Button("ποΈ Delete Selected File", variant="stop", scale=1)
|
477 |
edit_status_display = gr.Textbox(label="File Edit/Delete Status", interactive=False, lines=2, value="*Select file...*")
|