Spaces:
Sleeping
Sleeping
Update app_logic.py
Browse files- app_logic.py +176 -67
app_logic.py
CHANGED
@@ -11,90 +11,202 @@ from huggingface_hub import (
|
|
11 |
list_repo_files,
|
12 |
Repository,
|
13 |
whoami,
|
14 |
-
hf_hub_download,
|
15 |
)
|
16 |
import logging
|
17 |
from pathlib import Path
|
18 |
-
from PIL import Image
|
19 |
|
|
|
20 |
try:
|
21 |
-
from keylock_decode import
|
|
|
|
|
|
|
|
|
22 |
KEYLOCK_DECODE_AVAILABLE = True
|
23 |
except ImportError:
|
24 |
KEYLOCK_DECODE_AVAILABLE = False
|
25 |
-
|
26 |
-
|
|
|
|
|
|
|
27 |
|
28 |
logging.basicConfig(
|
29 |
-
level=logging.INFO,
|
30 |
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
31 |
)
|
32 |
logger = logging.getLogger(__name__)
|
33 |
|
34 |
-
# ---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
def _get_api_token(ui_token_from_textbox=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
36 |
env_token = os.getenv('HF_TOKEN')
|
37 |
-
if env_token:
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
39 |
return None, "Error: Hugging Face API token not provided."
|
40 |
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
if not password: return "Error: Password cannot be empty."
|
46 |
status_messages_display = []
|
47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
48 |
try:
|
49 |
logger.info(f"Attempting to decode from KeyLock Wallet image...")
|
50 |
-
decoded_data, status_msgs_from_lib =
|
51 |
status_messages_display.extend(status_msgs_from_lib)
|
|
|
52 |
if decoded_data:
|
53 |
status_messages_display.append("\n**Decoded Data Summary (sensitive values masked):**")
|
54 |
for key, value in decoded_data.items():
|
55 |
display_value = '********' if any(k_word in key.upper() for k_word in ['TOKEN', 'KEY', 'SECRET', 'PASS']) else value
|
56 |
status_messages_display.append(f"- {key}: {display_value}")
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
return "\n".join(status_messages_display)
|
62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
|
|
64 |
|
65 |
-
'''def process_commented_markdown(commented_input):
|
66 |
-
"""Process a commented markdown string by stripping '# ' from each line if '# # Space:' is present."""
|
67 |
-
lines = commented_input.strip().split("\n")
|
68 |
-
print(type(lines))
|
69 |
-
# Check for '# # Space:' or variations (e.g., '# Space:') in any line
|
70 |
-
if any( "# # Space:" in line.strip() for line in lines):
|
71 |
-
print("YES")
|
72 |
-
cleaned_lines = [line.lstrip("# ") for line in lines]
|
73 |
-
return cleaned_lines
|
74 |
-
return lines'''
|
75 |
|
|
|
76 |
def process_commented_markdown(commented_input):
|
77 |
-
|
78 |
lines = commented_input.strip().split("\n")
|
79 |
-
print(type(lines)) # Original debug print
|
80 |
-
# Check for '# # Space:' or variations (e.g., '# Space:') in any line
|
81 |
if any( "# # Space:" in line.strip() for line in lines):
|
82 |
-
print("YES") # Original debug print
|
83 |
-
|
84 |
cleaned_lines = [line[2:] if line.startswith("# ") else line for line in lines]
|
85 |
-
|
86 |
return cleaned_lines
|
87 |
return lines
|
88 |
|
89 |
def parse_markdown(markdown_input):
|
|
|
90 |
space_info = {"repo_name_md": "", "owner_md": "", "files": []}
|
91 |
current_file_path = None; current_file_content_lines = []
|
92 |
in_file_definition = False; in_code_block = False
|
93 |
-
print(markdown_input)
|
94 |
lines = process_commented_markdown(markdown_input)
|
95 |
-
|
96 |
-
#lines = markdown_input.strip().split("\n")
|
97 |
-
|
98 |
for line_content_orig in lines:
|
99 |
line_content_stripped = line_content_orig.strip()
|
100 |
if line_content_stripped.startswith("### File:"):
|
@@ -119,41 +231,39 @@ def parse_markdown(markdown_input):
|
|
119 |
space_info["files"] = [f for f in space_info["files"] if f.get("path")]
|
120 |
return space_info
|
121 |
|
122 |
-
|
123 |
-
|
124 |
-
# --- `_determine_repo_id` (Unchanged) ---
|
125 |
def _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui):
|
|
|
126 |
if not space_name_ui: return None, "Error: Space Name cannot be empty."
|
127 |
if "/" in space_name_ui: return None, "Error: Space Name should not contain '/'. Use Owner field."
|
128 |
final_owner = owner_ui; error_message = None
|
129 |
if not final_owner:
|
130 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
131 |
-
if token_err: return None, token_err
|
132 |
if not resolved_api_token: return None, "Error: API token required for auto owner determination."
|
133 |
try:
|
134 |
user_info = whoami(token=resolved_api_token)
|
135 |
if user_info and 'name' in user_info: final_owner = user_info['name']
|
136 |
-
else: error_message = "Error: Could not retrieve username. Check token/permissions
|
137 |
-
except Exception as e: error_message = f"Error retrieving username: {str(e)}.
|
138 |
if error_message: return None, error_message
|
139 |
if not final_owner: return None, "Error: Owner could not be determined."
|
140 |
return f"{final_owner}/{space_name_ui}", None
|
141 |
|
142 |
-
|
143 |
-
# --- New Function to Fetch File Content from Hub ---
|
144 |
def get_space_file_content(ui_api_token_from_textbox, space_name_ui, owner_ui, file_path_in_repo):
|
145 |
-
|
146 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
147 |
try:
|
148 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
149 |
if token_err:
|
150 |
-
return None, token_err
|
151 |
|
152 |
repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
|
153 |
if err:
|
154 |
return None, err
|
155 |
repo_id_for_error_logging = repo_id
|
156 |
-
|
157 |
if not file_path_in_repo:
|
158 |
return None, "Error: File path cannot be empty."
|
159 |
|
@@ -163,45 +273,42 @@ def get_space_file_content(ui_api_token_from_textbox, space_name_ui, owner_ui, f
|
|
163 |
filename=file_path_in_repo,
|
164 |
repo_type="space",
|
165 |
token=resolved_api_token,
|
166 |
-
# revision="main", # Optional: specify a branch/commit
|
167 |
-
# cache_dir=... # Optional: manage cache
|
168 |
)
|
169 |
-
|
170 |
content = Path(downloaded_file_path).read_text(encoding="utf-8")
|
171 |
-
logger.info(f"Successfully downloaded and read file: {file_path_in_repo}
|
172 |
-
return content, None
|
173 |
-
|
174 |
except Exception as e:
|
175 |
-
# Catch specific huggingface_hub.utils.HFValidationError for not found etc.
|
176 |
if "404" in str(e) or "not found" in str(e).lower():
|
177 |
logger.warning(f"File not found {file_path_in_repo} in {repo_id_for_error_logging}: {e}")
|
178 |
return None, f"Error: File '{file_path_in_repo}' not found in Space '{repo_id_for_error_logging}'."
|
179 |
-
logger.exception(f"Error fetching file content for {file_path_in_repo}
|
180 |
return None, f"Error fetching file content: {str(e)}"
|
181 |
|
182 |
-
# --- Function
|
183 |
def list_space_files_for_browsing(ui_api_token_from_textbox, space_name_ui, owner_ui):
|
184 |
-
|
185 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
186 |
try:
|
187 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
188 |
if token_err: return None, token_err
|
189 |
-
|
190 |
repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
|
191 |
if err: return None, err
|
192 |
repo_id_for_error_logging = repo_id
|
193 |
-
|
194 |
files = list_repo_files(repo_id=repo_id, token=resolved_api_token, repo_type="space")
|
195 |
if not files:
|
196 |
-
return [], f"No files found in Space `{repo_id}`."
|
197 |
-
return files, None
|
198 |
except Exception as e:
|
199 |
logger.exception(f"Error listing files for {repo_id_for_error_logging}:")
|
200 |
return None, f"Error listing files for `{repo_id_for_error_logging}`: {str(e)}"
|
201 |
|
202 |
-
|
203 |
-
# --- Core Functions: `create_space`, `update_space_file` (Unchanged from previous correct versions) ---
|
204 |
def create_space(ui_api_token_from_textbox, space_name_ui, owner_ui, sdk_ui, markdown_input):
|
|
|
205 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
206 |
try:
|
207 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
@@ -231,7 +338,9 @@ def create_space(ui_api_token_from_textbox, space_name_ui, owner_ui, sdk_ui, mar
|
|
231 |
logger.exception(f"Error in create_space for {repo_id_for_error_logging}:")
|
232 |
return f"Error during Space creation/update: {str(e)}"
|
233 |
|
|
|
234 |
def update_space_file(ui_api_token_from_textbox, space_name_ui, owner_ui, file_path_in_repo, file_content, commit_message_ui):
|
|
|
235 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
236 |
try:
|
237 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
|
|
11 |
list_repo_files,
|
12 |
Repository,
|
13 |
whoami,
|
14 |
+
hf_hub_download,
|
15 |
)
|
16 |
import logging
|
17 |
from pathlib import Path
|
18 |
+
from PIL import Image
|
19 |
|
20 |
+
# --- Import functions from keylock_decode ---
|
21 |
try:
|
22 |
+
from keylock_decode import (
|
23 |
+
decode_data_from_image_pil,
|
24 |
+
save_decoded_data_locally_encrypted,
|
25 |
+
load_decoded_data_locally_encrypted
|
26 |
+
)
|
27 |
KEYLOCK_DECODE_AVAILABLE = True
|
28 |
except ImportError:
|
29 |
KEYLOCK_DECODE_AVAILABLE = False
|
30 |
+
decode_data_from_image_pil = None
|
31 |
+
save_decoded_data_locally_encrypted = None
|
32 |
+
load_decoded_data_locally_encrypted = None
|
33 |
+
logging.warning("keylock-decode library not available or missing functions. KeyLock Wallet features will be disabled.")
|
34 |
+
|
35 |
|
36 |
logging.basicConfig(
|
37 |
+
level=logging.INFO,
|
38 |
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
39 |
)
|
40 |
logger = logging.getLogger(__name__)
|
41 |
|
42 |
+
# --- Global variable for in-memory keys and local storage path ---
|
43 |
+
_loaded_local_keys = {}
|
44 |
+
LOCAL_KEYS_FILE = "/data/.space_keys.enc" # Persistent storage in Hugging Face Spaces
|
45 |
+
|
46 |
+
# --- Helper Function: Load Local Keys into Memory ---
|
47 |
+
def _load_keys_into_memory(password: str) -> list[str]:
|
48 |
+
# Loads and decrypts keys from the local file into memory
|
49 |
+
global _loaded_local_keys
|
50 |
+
status_messages = []
|
51 |
+
|
52 |
+
if not KEYLOCK_DECODE_AVAILABLE or not load_decoded_data_locally_encrypted:
|
53 |
+
status_messages.append("KeyLock-Decode library not available for local loading.")
|
54 |
+
_loaded_local_keys = {}
|
55 |
+
return status_messages
|
56 |
+
|
57 |
+
if not password:
|
58 |
+
status_messages.append("Error: Password required to load local keys.")
|
59 |
+
_loaded_local_keys = {}
|
60 |
+
return status_messages
|
61 |
+
|
62 |
+
if not Path(LOCAL_KEYS_FILE).exists():
|
63 |
+
status_messages.append(f"Info: Local key file not found at `{LOCAL_KEYS_FILE}`. No keys loaded.")
|
64 |
+
_loaded_local_keys = {}
|
65 |
+
return status_messages
|
66 |
+
|
67 |
+
try:
|
68 |
+
_loaded_local_keys = load_decoded_data_locally_encrypted(password, LOCAL_KEYS_FILE)
|
69 |
+
|
70 |
+
if _loaded_local_keys:
|
71 |
+
status_messages.append(f"Successfully loaded {len(_loaded_local_keys)} keys from local storage.")
|
72 |
+
masked_keys = {k: ('********' if any(k_word in k.upper() for k_word in ['TOKEN', 'KEY', 'SECRET', 'PASS']) else v) for k, v in _loaded_local_keys.items()}
|
73 |
+
status_messages.append(f"Loaded keys: {masked_keys}")
|
74 |
+
logger.info(f"Keys loaded into memory from {LOCAL_KEYS_FILE}")
|
75 |
+
else:
|
76 |
+
status_messages.append(f"Info: Local key file `{LOCAL_KEYS_FILE}` was empty or contained no valid data after decryption.")
|
77 |
+
_loaded_local_keys = {}
|
78 |
+
|
79 |
+
except FileNotFoundError:
|
80 |
+
status_messages.append(f"Info: Local key file not found at {LOCAL_KEYS_FILE}. No keys loaded.")
|
81 |
+
_loaded_local_keys = {}
|
82 |
+
except ValueError as e:
|
83 |
+
status_messages.append(f"Error loading local keys: {e}. Password may be incorrect.")
|
84 |
+
_loaded_local_keys = {}
|
85 |
+
except IOError as e:
|
86 |
+
status_messages.append(f"IO Error loading local keys: {e}")
|
87 |
+
_loaded_local_keys = {}
|
88 |
+
except Exception as e:
|
89 |
+
logger.exception(f"Unexpected error loading local keys from {LOCAL_KEYS_FILE}:")
|
90 |
+
status_messages.append(f"Unexpected error loading local keys: {str(e)}")
|
91 |
+
_loaded_local_keys = {}
|
92 |
+
|
93 |
+
return status_messages
|
94 |
+
|
95 |
+
|
96 |
+
# --- Helper Function: Get API Token ---
|
97 |
def _get_api_token(ui_token_from_textbox=None):
|
98 |
+
# Retrieves token from in-memory keys, env vars, or textbox
|
99 |
+
in_memory_token = _loaded_local_keys.get('HF_TOKEN')
|
100 |
+
if in_memory_token:
|
101 |
+
logger.info("Using HF_TOKEN from in-memory loaded keys.")
|
102 |
+
return in_memory_token, None
|
103 |
+
|
104 |
env_token = os.getenv('HF_TOKEN')
|
105 |
+
if env_token:
|
106 |
+
logger.info("Using HF_TOKEN from environment variable.")
|
107 |
+
return env_token, None
|
108 |
+
|
109 |
+
if ui_token_from_textbox:
|
110 |
+
logger.info("Using HF_TOKEN from UI textbox.")
|
111 |
+
return ui_token_from_textbox, None
|
112 |
+
|
113 |
return None, "Error: Hugging Face API token not provided."
|
114 |
|
115 |
+
|
116 |
+
# --- Main Function: Process KeyLock Image and Store Locally ---
|
117 |
+
def process_keylock_image_and_store_locally(image_pil_object: Image.Image, password: str):
|
118 |
+
# Decodes image, saves data encrypted locally, and loads into memory
|
|
|
119 |
status_messages_display = []
|
120 |
+
|
121 |
+
if not KEYLOCK_DECODE_AVAILABLE or not decode_data_from_image_pil or \
|
122 |
+
not save_decoded_data_locally_encrypted or not load_decoded_data_locally_encrypted:
|
123 |
+
status_messages_display.append("Error: KeyLock-Decode library not available.")
|
124 |
+
global _loaded_local_keys
|
125 |
+
_loaded_local_keys = {}
|
126 |
+
return "\n".join(status_messages_display)
|
127 |
+
|
128 |
+
if image_pil_object is None:
|
129 |
+
status_messages_display.append("Error: No KeyLock Wallet image provided.")
|
130 |
+
return "\n".join(status_messages_display)
|
131 |
+
|
132 |
+
if not password:
|
133 |
+
status_messages_display.append("Error: Password cannot be empty.")
|
134 |
+
return "\n".join(status_messages_display)
|
135 |
+
|
136 |
+
decoded_data = None
|
137 |
try:
|
138 |
logger.info(f"Attempting to decode from KeyLock Wallet image...")
|
139 |
+
decoded_data, status_msgs_from_lib = decode_data_from_image_pil(image_pil_object, password)
|
140 |
status_messages_display.extend(status_msgs_from_lib)
|
141 |
+
|
142 |
if decoded_data:
|
143 |
status_messages_display.append("\n**Decoded Data Summary (sensitive values masked):**")
|
144 |
for key, value in decoded_data.items():
|
145 |
display_value = '********' if any(k_word in key.upper() for k_word in ['TOKEN', 'KEY', 'SECRET', 'PASS']) else value
|
146 |
status_messages_display.append(f"- {key}: {display_value}")
|
147 |
+
|
148 |
+
try:
|
149 |
+
save_decoded_data_locally_encrypted(decoded_data, password, LOCAL_KEYS_FILE)
|
150 |
+
status_messages_display.append(f"\n**SUCCESS: Decoded data saved to encrypted local file:** `{LOCAL_KEYS_FILE}`")
|
151 |
+
|
152 |
+
load_status = _load_keys_into_memory(password)
|
153 |
+
status_messages_display.extend(load_status)
|
154 |
+
if not _loaded_local_keys:
|
155 |
+
status_messages_display.append("Warning: No keys were loaded into memory after saving.")
|
156 |
+
|
157 |
+
|
158 |
+
except Exception as e:
|
159 |
+
status_messages_display.append(f"Error saving or loading data locally: {str(e)}")
|
160 |
+
logger.error(f"Error during local save/load after decoding: {e}")
|
161 |
+
global _loaded_local_keys
|
162 |
+
_loaded_local_keys = {}
|
163 |
+
|
164 |
+
elif not status_msgs_from_lib:
|
165 |
+
status_messages_display.append("Info: Decoding process completed, but no data was extracted.")
|
166 |
+
|
167 |
+
|
168 |
+
except ValueError as e:
|
169 |
+
status_messages_display.append(f"**Decoding Error:** {e}. Please check password and image.")
|
170 |
+
global _loaded_local_keys
|
171 |
+
_loaded_local_keys = {}
|
172 |
+
except Exception as e:
|
173 |
+
status_messages_display.append(f"**Unexpected error during processing:** {str(e)}")
|
174 |
+
logger.exception("Unexpected error during keylock image processing:")
|
175 |
+
global _loaded_local_keys
|
176 |
+
_loaded_local_keys = {}
|
177 |
+
|
178 |
+
|
179 |
return "\n".join(status_messages_display)
|
180 |
|
181 |
+
# --- Function: Load Keys from Local File ---
|
182 |
+
def load_keys_from_local_file(password: str) -> str:
|
183 |
+
# Triggers loading keys from the encrypted local file into memory
|
184 |
+
status_messages = _load_keys_into_memory(password)
|
185 |
+
if not status_messages:
|
186 |
+
if _loaded_local_keys:
|
187 |
+
return f"Keys successfully loaded from `{LOCAL_KEYS_FILE}`."
|
188 |
+
else:
|
189 |
+
return f"Attempted to load keys from `{LOCAL_KEYS_FILE}`, but no keys were loaded. Check password."
|
190 |
|
191 |
+
return "\n".join(status_messages)
|
192 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
193 |
|
194 |
+
# --- Markdown Processing Functions ---
|
195 |
def process_commented_markdown(commented_input):
|
196 |
+
# Processes markdown by stripping comments if a specific marker is present
|
197 |
lines = commented_input.strip().split("\n")
|
|
|
|
|
198 |
if any( "# # Space:" in line.strip() for line in lines):
|
|
|
|
|
199 |
cleaned_lines = [line[2:] if line.startswith("# ") else line for line in lines]
|
|
|
200 |
return cleaned_lines
|
201 |
return lines
|
202 |
|
203 |
def parse_markdown(markdown_input):
|
204 |
+
# Parses markdown input to extract space info and file content
|
205 |
space_info = {"repo_name_md": "", "owner_md": "", "files": []}
|
206 |
current_file_path = None; current_file_content_lines = []
|
207 |
in_file_definition = False; in_code_block = False
|
|
|
208 |
lines = process_commented_markdown(markdown_input)
|
209 |
+
|
|
|
|
|
210 |
for line_content_orig in lines:
|
211 |
line_content_stripped = line_content_orig.strip()
|
212 |
if line_content_stripped.startswith("### File:"):
|
|
|
231 |
space_info["files"] = [f for f in space_info["files"] if f.get("path")]
|
232 |
return space_info
|
233 |
|
234 |
+
# --- Helper Function: Determine Repository ID ---
|
|
|
|
|
235 |
def _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui):
|
236 |
+
# Determines the full repo ID (owner/space_name)
|
237 |
if not space_name_ui: return None, "Error: Space Name cannot be empty."
|
238 |
if "/" in space_name_ui: return None, "Error: Space Name should not contain '/'. Use Owner field."
|
239 |
final_owner = owner_ui; error_message = None
|
240 |
if not final_owner:
|
241 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
242 |
+
if token_err: return None, token_err
|
243 |
if not resolved_api_token: return None, "Error: API token required for auto owner determination."
|
244 |
try:
|
245 |
user_info = whoami(token=resolved_api_token)
|
246 |
if user_info and 'name' in user_info: final_owner = user_info['name']
|
247 |
+
else: error_message = "Error: Could not retrieve username. Check token/permissions."
|
248 |
+
except Exception as e: error_message = f"Error retrieving username: {str(e)}."
|
249 |
if error_message: return None, error_message
|
250 |
if not final_owner: return None, "Error: Owner could not be determined."
|
251 |
return f"{final_owner}/{space_name_ui}", None
|
252 |
|
253 |
+
# --- Function: Fetch File Content from Hub ---
|
|
|
254 |
def get_space_file_content(ui_api_token_from_textbox, space_name_ui, owner_ui, file_path_in_repo):
|
255 |
+
# Fetches content of a specific file from a Hugging Face Space
|
256 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
257 |
try:
|
258 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
259 |
if token_err:
|
260 |
+
return None, token_err
|
261 |
|
262 |
repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
|
263 |
if err:
|
264 |
return None, err
|
265 |
repo_id_for_error_logging = repo_id
|
266 |
+
|
267 |
if not file_path_in_repo:
|
268 |
return None, "Error: File path cannot be empty."
|
269 |
|
|
|
273 |
filename=file_path_in_repo,
|
274 |
repo_type="space",
|
275 |
token=resolved_api_token,
|
|
|
|
|
276 |
)
|
277 |
+
|
278 |
content = Path(downloaded_file_path).read_text(encoding="utf-8")
|
279 |
+
logger.info(f"Successfully downloaded and read file: {file_path_in_repo}")
|
280 |
+
return content, None
|
281 |
+
|
282 |
except Exception as e:
|
|
|
283 |
if "404" in str(e) or "not found" in str(e).lower():
|
284 |
logger.warning(f"File not found {file_path_in_repo} in {repo_id_for_error_logging}: {e}")
|
285 |
return None, f"Error: File '{file_path_in_repo}' not found in Space '{repo_id_for_error_logging}'."
|
286 |
+
logger.exception(f"Error fetching file content for {file_path_in_repo}:")
|
287 |
return None, f"Error fetching file content: {str(e)}"
|
288 |
|
289 |
+
# --- Function: List Space Files ---
|
290 |
def list_space_files_for_browsing(ui_api_token_from_textbox, space_name_ui, owner_ui):
|
291 |
+
# Lists files in a Hugging Face Space
|
292 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
293 |
try:
|
294 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
295 |
if token_err: return None, token_err
|
296 |
+
|
297 |
repo_id, err = _determine_repo_id(ui_api_token_from_textbox, space_name_ui, owner_ui)
|
298 |
if err: return None, err
|
299 |
repo_id_for_error_logging = repo_id
|
300 |
+
|
301 |
files = list_repo_files(repo_id=repo_id, token=resolved_api_token, repo_type="space")
|
302 |
if not files:
|
303 |
+
return [], f"No files found in Space `{repo_id}`."
|
304 |
+
return files, None
|
305 |
except Exception as e:
|
306 |
logger.exception(f"Error listing files for {repo_id_for_error_logging}:")
|
307 |
return None, f"Error listing files for `{repo_id_for_error_logging}`: {str(e)}"
|
308 |
|
309 |
+
# --- Core Function: Create/Update Space ---
|
|
|
310 |
def create_space(ui_api_token_from_textbox, space_name_ui, owner_ui, sdk_ui, markdown_input):
|
311 |
+
# Creates or updates a Hugging Face Space with files from markdown
|
312 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
313 |
try:
|
314 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
|
|
338 |
logger.exception(f"Error in create_space for {repo_id_for_error_logging}:")
|
339 |
return f"Error during Space creation/update: {str(e)}"
|
340 |
|
341 |
+
# --- Core Function: Update Space File ---
|
342 |
def update_space_file(ui_api_token_from_textbox, space_name_ui, owner_ui, file_path_in_repo, file_content, commit_message_ui):
|
343 |
+
# Updates a specific file in a Hugging Face Space
|
344 |
repo_id_for_error_logging = f"{owner_ui}/{space_name_ui}" if owner_ui else space_name_ui
|
345 |
try:
|
346 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|