broadfield-dev commited on
Commit
0da8126
·
verified ·
1 Parent(s): 8005c0d

Update app_logic.py

Browse files
Files changed (1) hide show
  1. app_logic.py +188 -119
app_logic.py CHANGED
@@ -1,65 +1,151 @@
1
  import os
2
  import re
3
  import tempfile
4
- import shutil
5
- import git
6
  from huggingface_hub import (
7
  create_repo,
8
  upload_folder,
9
  list_repo_files,
10
- # delete_file, # Not used
11
- Repository,
12
  whoami,
13
  )
14
  import logging
15
  from pathlib import Path
 
16
 
17
- # Configure logging
18
- logging.basicConfig(level=logging.INFO)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  logger = logging.getLogger(__name__)
 
 
 
20
 
21
- # Function to parse markdown input
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  def parse_markdown(markdown_input):
23
  """Parse markdown input to extract space details and file structure."""
24
  space_info = {"repo_name_md": "", "owner_md": "", "files": []}
25
  current_file = None
26
  file_content = []
27
- in_file_content = False # Tracks if we are inside a ### File: block content
28
- in_code_block = False # Tracks if we are inside a ``` code block ```
29
 
30
  lines = markdown_input.strip().split("\n")
31
  for line_idx, line_content_orig in enumerate(lines):
32
  line_content_stripped = line_content_orig.strip()
33
 
34
- # Handle file content collection, especially for code blocks
35
  if in_file_content:
36
  if line_content_stripped.startswith("```"):
37
- if in_code_block: # Closing ```
38
- file_content.append(line_content_orig) # Keep the closing backticks as part of content
39
  in_code_block = False
40
- # Don't immediately save here, let the next ### File or end of input handle it
41
- # This allows for text after a code block but before the next file.
42
- else: # Opening ```
43
  in_code_block = True
44
  file_content.append(line_content_orig)
45
- elif in_code_block: # Inside a code block
46
  file_content.append(line_content_orig)
47
- elif not in_code_block: # Plain text line within ### File: block but outside ```
48
- # Check if this line is a new file marker, if so, current file ends.
49
  if line_content_stripped.startswith("### File:") or line_content_stripped.startswith("## File Structure") or line_content_stripped.startswith("# Space:"):
50
  if current_file and file_content:
51
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
52
- current_file = None # Reset
53
  file_content = []
54
- in_file_content = False # Current file ended
55
- # Reprocess this line if it's a new file marker (will be handled by outer ifs)
56
- else: # Regular content line
57
  file_content.append(line_content_orig)
58
 
59
-
60
- # Detect major structural elements
61
  if line_content_stripped.startswith("# Space:"):
62
- if current_file and file_content: # Save previous file if any
63
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
64
  full_space_name_md = line_content_stripped.replace("# Space:", "").strip()
65
  if "/" in full_space_name_md:
@@ -72,58 +158,55 @@ def parse_markdown(markdown_input):
72
  in_code_block = False
73
 
74
  elif line_content_stripped.startswith("## File Structure"):
75
- if current_file and file_content: # Save previous file if any
76
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
77
  current_file = None
78
  file_content = []
79
  in_file_content = False
80
  in_code_block = False
81
- continue # Just a section header
82
 
83
  elif line_content_stripped.startswith("### File:"):
84
- if current_file and file_content: # Save content of the previous file
85
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
86
 
87
  current_file = line_content_stripped.replace("### File:", "").strip()
88
- file_content = [] # Reset for new file
89
- in_file_content = True # Start collecting content lines for this file
90
- in_code_block = False # Reset code block state for new file
91
-
92
- # Note: 📄 and 📁 are ignored if ### File: is the primary mechanism as implemented.
93
- # If they are meant to define empty files, that logic would need to be added.
94
- # Current parser prioritizes ### File: sections for content.
95
-
96
- # Append the last file's content if any
97
  if current_file and file_content:
98
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
99
 
100
- space_info["files"] = [f for f in space_info["files"] if f.get("path")] # Filter out empty path entries
101
  return space_info
102
 
103
 
104
- def _determine_repo_id(api_token, space_name_ui, owner_ui):
105
- """
106
- Determines the final owner and constructs the repo_id.
107
- space_name_ui should be just the name, not 'owner/name'.
108
- owner_ui is the value from the UI's owner field.
109
- Returns (repo_id, error_message)
110
- """
111
  if not space_name_ui:
112
  return None, "Error: Space Name cannot be empty."
113
- if "/" in space_name_ui: # User should not put slash in space name field
114
  return None, "Error: Space Name should not contain '/'. Please use the Owner field for the namespace."
115
 
116
  final_owner = owner_ui
117
  error_message = None
118
 
119
  if not final_owner:
120
- if not api_token:
121
- return None, "Error: API token is required to automatically determine owner when Owner field is empty."
 
 
 
 
 
 
 
122
  try:
123
- user_info = whoami(token=api_token)
124
  if user_info and 'name' in user_info:
125
  final_owner = user_info['name']
126
- logger.info(f"Determined owner: {final_owner} from API token.")
127
  else:
128
  logger.error(f"whoami(token=...) returned: {user_info} - 'name' field missing or user_info is None.")
129
  error_message = "Error: Could not retrieve username from API token. Ensure token is valid and has 'Read profile' permissions. Or, specify Owner manually."
@@ -134,132 +217,118 @@ def _determine_repo_id(api_token, space_name_ui, owner_ui):
134
  if error_message:
135
  return None, error_message
136
 
137
- if not final_owner:
138
  return None, "Error: Owner could not be determined. Please provide an owner or ensure your API token is valid."
139
 
140
  return f"{final_owner}/{space_name_ui}", None
141
 
142
- # Function to create and populate a Space
143
- def create_space(api_token, space_name_ui, owner_ui, sdk_ui, markdown_input):
144
- """Create a Hugging Face Space and populate it with files from markdown input."""
 
 
145
  try:
146
- if not api_token:
147
- return "Error: Please provide a valid Hugging Face API token."
 
148
 
149
- repo_id, err = _determine_repo_id(api_token, space_name_ui, owner_ui)
 
150
  if err:
151
  return err
 
152
 
153
  space_info = parse_markdown(markdown_input)
154
  if not space_info["files"]:
155
- return "Error: No files found in the markdown input. Ensure '### File: path/to/file.ext' markers are used correctly with content."
156
 
157
- # Create temporary directory
158
  with tempfile.TemporaryDirectory() as temp_dir:
159
- repo_local_path = Path(temp_dir) / "repo_content_for_upload"
160
  repo_local_path.mkdir(exist_ok=True)
161
 
162
- # Write files to temporary directory
163
  for file_info in space_info["files"]:
164
- if not file_info.get("path"):
165
- logger.warning(f"Skipping file with no path: {file_info}")
166
- continue
167
  file_path_abs = repo_local_path / file_info["path"]
168
  file_path_abs.parent.mkdir(parents=True, exist_ok=True)
169
- with open(file_path_abs, "w", encoding="utf-8") as f:
170
- f.write(file_info["content"])
171
  logger.info(f"Wrote file: {file_path_abs}")
172
 
173
- # Create repository on Hugging Face
174
  try:
175
  create_repo(
176
- repo_id=repo_id,
177
- token=api_token,
178
- repo_type="space", # Correctly set
179
- space_sdk=sdk_ui,
180
- private=False,
181
  )
182
  logger.info(f"Created Space repo: {repo_id}")
183
  except Exception as e:
184
  err_str = str(e).lower()
185
- if "already exists" in err_str or "you already created this repo" in err_str or "exists" in err_str: # More robust check
186
- logger.info(f"Space {repo_id} already exists, proceeding to upload/update files.")
187
  else:
188
  return f"Error creating Space '{repo_id}': {str(e)}"
189
 
190
- # Push to Hugging Face Space
191
  upload_folder(
192
- repo_id=repo_id,
193
- folder_path=str(repo_local_path), # upload_folder expects string path
194
- path_in_repo=".",
195
- token=api_token,
196
- repo_type="space", # ***** ADD THIS LINE *****
197
  commit_message=f"Initial Space setup of {repo_id} via Builder",
198
- # allow_patterns=["*.py", "*.md", "*.txt", "Dockerfile", ".gitattributes", "*.json", "*.yaml", "*.yml"], # Example: be more specific if needed
199
- # ignore_patterns=["*.git/*", ".*", "__pycache__/*"], # Example
200
  )
201
  logger.info(f"Uploaded files to Space: {repo_id}")
202
  return f"Successfully created/updated Space: [{repo_id}](https://huggingface.co/spaces/{repo_id})"
203
 
204
  except Exception as e:
205
- logger.exception(f"Error in create_space for {repo_id if 'repo_id' in locals() else 'unknown repo'}:") # Log full traceback
206
  return f"Error during Space creation/update: {str(e)}"
207
 
208
- # Function to view Space files
209
- def view_space_files(api_token, space_name_ui, owner_ui):
210
- """List files in a Hugging Face Space."""
211
- repo_id_for_error = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
212
  try:
213
- if not api_token:
214
- return "Error: Please provide a valid Hugging Face API token."
 
215
 
216
- repo_id, err = _determine_repo_id(api_token, space_name_ui, owner_ui)
217
  if err:
218
  return err
219
-
220
- files = list_repo_files(repo_id=repo_id, token=api_token, repo_type="space") # Correctly set
 
221
  if files:
222
  return f"Files in `{repo_id}`:\n\n" + "\n".join([f"- `{f}`" for f in files])
223
- else:
224
- return f"No files found in the Space `{repo_id}`."
225
  except Exception as e:
226
- logger.exception(f"Error in view_space_files for {repo_id_for_error}:")
227
- return f"Error listing files for `{repo_id_for_error}`: {str(e)}"
 
228
 
229
- # Function to update a Space file
230
- def update_space_file(api_token, space_name_ui, owner_ui, file_path_in_repo, file_content, commit_message_ui):
231
- """Update a file in a Hugging Face Space with a commit."""
232
- repo_id_for_error = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
233
  try:
234
- if not api_token:
235
- return "Error: Please provide a valid Hugging Face API token."
 
236
 
237
- repo_id, err = _determine_repo_id(api_token, space_name_ui, owner_ui)
238
  if err:
239
  return err
 
240
 
241
- if not file_path_in_repo:
242
- return "Error: File Path cannot be empty."
243
- if not commit_message_ui:
244
- commit_message_ui = f"Update {file_path_in_repo} via Space Builder"
245
 
246
  with tempfile.TemporaryDirectory() as temp_dir:
247
- repo_local_clone_path = Path(temp_dir) / "cloned_space_repo"
248
 
249
  cloned_repo = Repository(
250
- local_dir=str(repo_local_clone_path), # Repository expects string path
251
- clone_from=f"https://huggingface.co/spaces/{repo_id}", # Ensure this URL is correct
252
- repo_type="space", # Correctly set
253
- use_auth_token=api_token,
254
- git_user="Space Builder Bot",
255
- git_email="[email protected]"
256
  )
257
  logger.info(f"Cloned Space {repo_id} to {repo_local_clone_path}")
258
 
259
- full_local_file_path = cloned_repo.local_dir / file_path_in_repo # Path object arithmetic
260
  full_local_file_path.parent.mkdir(parents=True, exist_ok=True)
261
- with open(full_local_file_path, "w", encoding="utf-8") as f:
262
- f.write(file_content)
263
  logger.info(f"Wrote updated file {file_path_in_repo} locally.")
264
 
265
  cloned_repo.push_to_hub(commit_message=commit_message_ui)
@@ -268,5 +337,5 @@ def update_space_file(api_token, space_name_ui, owner_ui, file_path_in_repo, fil
268
  return f"Successfully updated `{file_path_in_repo}` in Space [{repo_id}](https://huggingface.co/spaces/{repo_id})"
269
 
270
  except Exception as e:
271
- logger.exception(f"Error in update_space_file for {repo_id_for_error}:")
272
- return f"Error updating file for `{repo_id_for_error}`: {str(e)}"
 
1
  import os
2
  import re
3
  import tempfile
4
+ import git # Used by Repository
 
5
  from huggingface_hub import (
6
  create_repo,
7
  upload_folder,
8
  list_repo_files,
9
+ Repository, # Used in update_space_file
 
10
  whoami,
11
  )
12
  import logging
13
  from pathlib import Path
14
+ from PIL import Image # For type hinting from gr.Image(type="pil")
15
 
16
+ # Attempt to import keylock_decode
17
+ try:
18
+ from keylock_decode import decode_from_image_pil
19
+ KEYLOCK_DECODE_AVAILABLE = True
20
+ except ImportError:
21
+ KEYLOCK_DECODE_AVAILABLE = False
22
+ decode_from_image_pil = None # Placeholder
23
+ logging.warning("keylock-decode library not found. Image decoding feature will be disabled.")
24
+
25
+
26
+ # Configure logging (ensure this is suitable for your environment, might be set in app.py too)
27
+ # If keylock-decode uses its own logger (e.g., logging.getLogger('keylock_decode')),
28
+ # you might need to adjust its level separately if you want more/less verbose output from it.
29
+ logging.basicConfig(
30
+ level=logging.INFO,
31
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
32
+ )
33
  logger = logging.getLogger(__name__)
34
+ if KEYLOCK_DECODE_AVAILABLE: # Example: Set keylock_decode's logger to DEBUG if you want its verbose output
35
+ # logging.getLogger('keylock_decode.decoder').setLevel(logging.DEBUG) # Check actual logger name in keylock-decode
36
+ pass
37
 
38
+
39
+ # --- New Helper Function to Get API Token ---
40
+ def _get_api_token(ui_token_from_textbox=None):
41
+ """
42
+ Retrieves the Hugging Face API token.
43
+ Prioritizes HF_TOKEN from environment variables (potentially set by KeyLock-Decode),
44
+ then falls back to UI input.
45
+ Returns (token, error_message)
46
+ """
47
+ env_token = os.getenv('HF_TOKEN')
48
+ if env_token:
49
+ logger.info("Using HF_TOKEN from environment.")
50
+ return env_token, None
51
+
52
+ if ui_token_from_textbox:
53
+ logger.info("Using API token from UI textbox.")
54
+ return ui_token_from_textbox, None
55
+
56
+ logger.warning("HF API token not found in environment or UI textbox.")
57
+ return None, "Error: Hugging Face API token not provided. Please enter it in the textbox or load it from an image."
58
+
59
+
60
+ # --- New Function for KeyLock-Decode Integration ---
61
+ def load_token_from_image_and_set_env(image_pil_object: Image.Image, password: str):
62
+ """
63
+ Decodes data from a PIL Image object using keylock-decode, sets environment variables,
64
+ and returns status messages.
65
+ """
66
+ if not KEYLOCK_DECODE_AVAILABLE:
67
+ return "Error: KeyLock-Decode library is not installed. This feature is disabled."
68
+
69
+ if image_pil_object is None:
70
+ return "Error: No image provided for decoding."
71
+ if not password:
72
+ return "Error: Password cannot be empty for image decoding."
73
+
74
+ status_messages_display = []
75
+
76
+ try:
77
+ logger.info(f"Attempting to decode from image using KeyLock-Decode...")
78
+ # decode_from_image_pil expects a PIL Image object
79
+ decoded_data, status_msgs_from_lib = decode_from_image_pil(
80
+ image_pil_object,
81
+ password,
82
+ set_environment_variables=True # CRITICAL: This sets os.environ
83
+ )
84
+
85
+ status_messages_display.extend(status_msgs_from_lib)
86
+
87
+ if decoded_data:
88
+ status_messages_display.append("\n**Decoded Data Summary (sensitive values masked):**")
89
+ for key, value in decoded_data.items():
90
+ display_value = '********' if any(k_word in key.upper() for k_word in ['TOKEN', 'KEY', 'SECRET', 'PASS']) else value
91
+ status_messages_display.append(f"- {key}: {display_value}")
92
+
93
+ if os.getenv('HF_TOKEN'):
94
+ status_messages_display.append(f"\n**SUCCESS: HF_TOKEN was found and has been set in the current process environment.** It will be prioritized for operations.")
95
+ elif 'HF_TOKEN' in decoded_data: # Should be rare if set_env_vars=True
96
+ status_messages_display.append(f"\nWarning: HF_TOKEN was in decoded data but os.getenv('HF_TOKEN') is not picking it up. This is unexpected if 'set_environment_variables=True' worked.")
97
+ else:
98
+ status_messages_display.append("\nNote: HF_TOKEN was not specifically found in the decoded data from the image.")
99
+ else:
100
+ # This case is often covered by status_msgs_from_lib, but good to have a fallback.
101
+ if not any("No payload data found" in msg for msg in status_msgs_from_lib):
102
+ status_messages_display.append("No data was decoded, or the decoded data was empty.")
103
+
104
+ except ValueError as e: # Specific errors from keylock-decode (e.g., bad password, corrupted data)
105
+ logger.error(f"KeyLock-Decode ValueError: {e}")
106
+ status_messages_display.append(f"**Decoding Error:** {e}")
107
+ except Exception as e:
108
+ logger.exception("An unexpected error occurred during image decoding with KeyLock-Decode:")
109
+ status_messages_display.append(f"**An unexpected error occurred:** {str(e)}")
110
+
111
+ return "\n".join(status_messages_display)
112
+
113
+
114
+ # --- Original `parse_markdown` function (unchanged) ---
115
  def parse_markdown(markdown_input):
116
  """Parse markdown input to extract space details and file structure."""
117
  space_info = {"repo_name_md": "", "owner_md": "", "files": []}
118
  current_file = None
119
  file_content = []
120
+ in_file_content = False
121
+ in_code_block = False
122
 
123
  lines = markdown_input.strip().split("\n")
124
  for line_idx, line_content_orig in enumerate(lines):
125
  line_content_stripped = line_content_orig.strip()
126
 
 
127
  if in_file_content:
128
  if line_content_stripped.startswith("```"):
129
+ if in_code_block:
130
+ file_content.append(line_content_orig)
131
  in_code_block = False
132
+ else:
 
 
133
  in_code_block = True
134
  file_content.append(line_content_orig)
135
+ elif in_code_block:
136
  file_content.append(line_content_orig)
137
+ elif not in_code_block:
 
138
  if line_content_stripped.startswith("### File:") or line_content_stripped.startswith("## File Structure") or line_content_stripped.startswith("# Space:"):
139
  if current_file and file_content:
140
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
141
+ current_file = None
142
  file_content = []
143
+ in_file_content = False
144
+ else:
 
145
  file_content.append(line_content_orig)
146
 
 
 
147
  if line_content_stripped.startswith("# Space:"):
148
+ if current_file and file_content:
149
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
150
  full_space_name_md = line_content_stripped.replace("# Space:", "").strip()
151
  if "/" in full_space_name_md:
 
158
  in_code_block = False
159
 
160
  elif line_content_stripped.startswith("## File Structure"):
161
+ if current_file and file_content:
162
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
163
  current_file = None
164
  file_content = []
165
  in_file_content = False
166
  in_code_block = False
167
+ continue
168
 
169
  elif line_content_stripped.startswith("### File:"):
170
+ if current_file and file_content:
171
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
172
 
173
  current_file = line_content_stripped.replace("### File:", "").strip()
174
+ file_content = []
175
+ in_file_content = True
176
+ in_code_block = False
177
+
 
 
 
 
 
178
  if current_file and file_content:
179
  space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
180
 
181
+ space_info["files"] = [f for f in space_info["files"] if f.get("path")]
182
  return space_info
183
 
184
 
185
+ # --- Updated `_determine_repo_id` to use `_get_api_token` ---
186
+ def _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui):
 
 
 
 
 
187
  if not space_name_ui:
188
  return None, "Error: Space Name cannot be empty."
189
+ if "/" in space_name_ui:
190
  return None, "Error: Space Name should not contain '/'. Please use the Owner field for the namespace."
191
 
192
  final_owner = owner_ui
193
  error_message = None
194
 
195
  if not final_owner:
196
+ # Get the actual token to use for whoami
197
+ resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
198
+ if token_err:
199
+ return None, token_err
200
+ # If resolved_api_token is None here but token_err is None, it means _get_api_token had an issue not returning error string
201
+ # which _get_api_token is designed not to do, it should always return error if no token.
202
+ if not resolved_api_token:
203
+ return None, "Error: API token is required to automatically determine owner when Owner field is empty (internal check failed)."
204
+
205
  try:
206
+ user_info = whoami(token=resolved_api_token)
207
  if user_info and 'name' in user_info:
208
  final_owner = user_info['name']
209
+ logger.info(f"Determined owner: {final_owner} using API token.")
210
  else:
211
  logger.error(f"whoami(token=...) returned: {user_info} - 'name' field missing or user_info is None.")
212
  error_message = "Error: Could not retrieve username from API token. Ensure token is valid and has 'Read profile' permissions. Or, specify Owner manually."
 
217
  if error_message:
218
  return None, error_message
219
 
220
+ if not final_owner:
221
  return None, "Error: Owner could not be determined. Please provide an owner or ensure your API token is valid."
222
 
223
  return f"{final_owner}/{space_name_ui}", None
224
 
225
+
226
+ # --- Updated Core Functions to use `_get_api_token` ---
227
+
228
+ def create_space(ui_api_token_from_textbox, space_name_ui, owner_ui, sdk_ui, markdown_input):
229
+ repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
230
  try:
231
+ resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
232
+ if token_err:
233
+ return token_err
234
 
235
+ # _determine_repo_id will also call _get_api_token internally if owner_ui is blank
236
+ repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
237
  if err:
238
  return err
239
+ repo_id_for_error_logging = repo_id # Update for more accurate logging if determination succeeds
240
 
241
  space_info = parse_markdown(markdown_input)
242
  if not space_info["files"]:
243
+ return "Error: No files found in the markdown input. Ensure '### File: path/to/file.ext' markers are used correctly."
244
 
 
245
  with tempfile.TemporaryDirectory() as temp_dir:
246
+ repo_local_path = Path(temp_dir) / "repo_upload_content"
247
  repo_local_path.mkdir(exist_ok=True)
248
 
 
249
  for file_info in space_info["files"]:
250
+ if not file_info.get("path"): continue
 
 
251
  file_path_abs = repo_local_path / file_info["path"]
252
  file_path_abs.parent.mkdir(parents=True, exist_ok=True)
253
+ with open(file_path_abs, "w", encoding="utf-8") as f: f.write(file_info["content"])
 
254
  logger.info(f"Wrote file: {file_path_abs}")
255
 
 
256
  try:
257
  create_repo(
258
+ repo_id=repo_id, token=resolved_api_token, repo_type="space",
259
+ space_sdk=sdk_ui, private=False,
 
 
 
260
  )
261
  logger.info(f"Created Space repo: {repo_id}")
262
  except Exception as e:
263
  err_str = str(e).lower()
264
+ if "already exists" in err_str or "you already created this repo" in err_str or "exists" in err_str:
265
+ logger.info(f"Space {repo_id} already exists. Proceeding to upload/update files.")
266
  else:
267
  return f"Error creating Space '{repo_id}': {str(e)}"
268
 
 
269
  upload_folder(
270
+ repo_id=repo_id, folder_path=str(repo_local_path), path_in_repo=".",
271
+ token=resolved_api_token, repo_type="space",
 
 
 
272
  commit_message=f"Initial Space setup of {repo_id} via Builder",
 
 
273
  )
274
  logger.info(f"Uploaded files to Space: {repo_id}")
275
  return f"Successfully created/updated Space: [{repo_id}](https://huggingface.co/spaces/{repo_id})"
276
 
277
  except Exception as e:
278
+ logger.exception(f"Error in create_space for {repo_id_for_error_logging}:")
279
  return f"Error during Space creation/update: {str(e)}"
280
 
281
+
282
+ def view_space_files(ui_api_token_from_textbox, space_name_ui, owner_ui):
283
+ repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
 
284
  try:
285
+ resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
286
+ if token_err:
287
+ return token_err
288
 
289
+ repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
290
  if err:
291
  return err
292
+ repo_id_for_error_logging = repo_id
293
+
294
+ files = list_repo_files(repo_id=repo_id, token=resolved_api_token, repo_type="space")
295
  if files:
296
  return f"Files in `{repo_id}`:\n\n" + "\n".join([f"- `{f}`" for f in files])
297
+ return f"No files found in the Space `{repo_id}`."
 
298
  except Exception as e:
299
+ logger.exception(f"Error in view_space_files for {repo_id_for_error_logging}:")
300
+ return f"Error listing files for `{repo_id_for_error_logging}`: {str(e)}"
301
+
302
 
303
+ def update_space_file(ui_api_token_from_textbox, space_name_ui, owner_ui, file_path_in_repo, file_content, commit_message_ui):
304
+ repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
 
 
305
  try:
306
+ resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
307
+ if token_err:
308
+ return token_err
309
 
310
+ repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
311
  if err:
312
  return err
313
+ repo_id_for_error_logging = repo_id
314
 
315
+ if not file_path_in_repo: return "Error: File Path cannot be empty."
316
+ commit_message_ui = commit_message_ui or f"Update {file_path_in_repo} via Space Builder"
 
 
317
 
318
  with tempfile.TemporaryDirectory() as temp_dir:
319
+ repo_local_clone_path = Path(temp_dir) / "cloned_space_repo_for_update"
320
 
321
  cloned_repo = Repository(
322
+ local_dir=str(repo_local_clone_path),
323
+ clone_from=f"https://huggingface.co/spaces/{repo_id}",
324
+ repo_type="space", use_auth_token=resolved_api_token,
325
+ git_user="Space Builder Bot", git_email="[email protected]"
 
 
326
  )
327
  logger.info(f"Cloned Space {repo_id} to {repo_local_clone_path}")
328
 
329
+ full_local_file_path = Path(cloned_repo.local_dir) / file_path_in_repo
330
  full_local_file_path.parent.mkdir(parents=True, exist_ok=True)
331
+ with open(full_local_file_path, "w", encoding="utf-8") as f: f.write(file_content)
 
332
  logger.info(f"Wrote updated file {file_path_in_repo} locally.")
333
 
334
  cloned_repo.push_to_hub(commit_message=commit_message_ui)
 
337
  return f"Successfully updated `{file_path_in_repo}` in Space [{repo_id}](https://huggingface.co/spaces/{repo_id})"
338
 
339
  except Exception as e:
340
+ logger.exception(f"Error in update_space_file for {repo_id_for_error_logging}:")
341
+ return f"Error updating file for `{repo_id_for_error_logging}`: {str(e)}"