Spaces:
Running
Running
Update app_logic.py
Browse files- app_logic.py +49 -18
app_logic.py
CHANGED
@@ -1,13 +1,12 @@
|
|
1 |
import os
|
2 |
-
import re
|
3 |
import tempfile
|
4 |
-
import
|
5 |
from huggingface_hub import create_repo, upload_folder, whoami
|
6 |
import logging
|
7 |
from pathlib import Path
|
8 |
from PIL import Image
|
9 |
-
|
10 |
from keylock import core as keylock_core
|
|
|
11 |
|
12 |
logging.basicConfig(
|
13 |
level=logging.INFO,
|
@@ -15,27 +14,20 @@ logging.basicConfig(
|
|
15 |
)
|
16 |
logger = logging.getLogger(__name__)
|
17 |
|
18 |
-
# --- NEW FUNCTION TO GET USERNAME ---
|
19 |
def get_username_from_token(api_token: str):
|
20 |
-
"""
|
21 |
-
Fetches the username associated with a Hugging Face API token.
|
22 |
-
Returns the username on success, or an empty string on failure.
|
23 |
-
"""
|
24 |
if not api_token:
|
25 |
logger.info("API token is empty, cannot fetch username.")
|
26 |
return ""
|
27 |
-
|
28 |
try:
|
29 |
logger.info("Attempting to fetch username from provided API token.")
|
30 |
user_info = whoami(token=api_token)
|
31 |
username = user_info.get('name')
|
32 |
-
|
33 |
if username:
|
34 |
logger.info(f"Successfully fetched username: {username}")
|
35 |
return username
|
36 |
else:
|
37 |
logger.warning("Token was valid, but no username found in whoami() response.")
|
38 |
-
return ""
|
39 |
except Exception as e:
|
40 |
logger.error(f"Failed to validate token and fetch username: {e}")
|
41 |
return ""
|
@@ -57,12 +49,12 @@ def extract_markdown_from_image(repo_image: Image.Image, image_password: str):
|
|
57 |
if not markdown_content:
|
58 |
return None, "Error: Extraction succeeded, but no markdown content was found in the image."
|
59 |
logger.info("Successfully extracted markdown content.")
|
60 |
-
return markdown_content,
|
61 |
except Exception as e:
|
62 |
logger.error(f"Failed to extract from image: {e}")
|
63 |
return None, f"Error during extraction: {e}"
|
64 |
|
65 |
-
def
|
66 |
space_info = {"files": []}
|
67 |
current_file_path = None; current_file_content_lines = []
|
68 |
in_file_definition = False; in_code_block = False
|
@@ -106,7 +98,7 @@ def create_space(ui_api_token_from_textbox, space_name_ui, owner_ui, sdk_ui, mar
|
|
106 |
try:
|
107 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
108 |
if token_err: return token_err
|
109 |
-
space_info =
|
110 |
if not space_info["files"]: return "Error: No files were found after parsing the markdown from the image."
|
111 |
with tempfile.TemporaryDirectory() as temp_dir:
|
112 |
repo_staging_path = Path(temp_dir) / "repo_staging"
|
@@ -131,8 +123,47 @@ def create_space(ui_api_token_from_textbox, space_name_ui, owner_ui, sdk_ui, mar
|
|
131 |
return f"Error during Space creation: {str(e)}"
|
132 |
|
133 |
def build_space_from_image(api_token, repo_image, image_password, new_space_name, owner, sdk):
|
134 |
-
markdown_string,
|
135 |
-
if
|
136 |
-
return
|
137 |
result = create_space(api_token, new_space_name, owner, sdk, markdown_string)
|
138 |
-
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
2 |
import tempfile
|
3 |
+
import gradio as gr
|
4 |
from huggingface_hub import create_repo, upload_folder, whoami
|
5 |
import logging
|
6 |
from pathlib import Path
|
7 |
from PIL import Image
|
|
|
8 |
from keylock import core as keylock_core
|
9 |
+
from repo_to_md.core import markdown_to_files
|
10 |
|
11 |
logging.basicConfig(
|
12 |
level=logging.INFO,
|
|
|
14 |
)
|
15 |
logger = logging.getLogger(__name__)
|
16 |
|
|
|
17 |
def get_username_from_token(api_token: str):
|
|
|
|
|
|
|
|
|
18 |
if not api_token:
|
19 |
logger.info("API token is empty, cannot fetch username.")
|
20 |
return ""
|
|
|
21 |
try:
|
22 |
logger.info("Attempting to fetch username from provided API token.")
|
23 |
user_info = whoami(token=api_token)
|
24 |
username = user_info.get('name')
|
|
|
25 |
if username:
|
26 |
logger.info(f"Successfully fetched username: {username}")
|
27 |
return username
|
28 |
else:
|
29 |
logger.warning("Token was valid, but no username found in whoami() response.")
|
30 |
+
return ""
|
31 |
except Exception as e:
|
32 |
logger.error(f"Failed to validate token and fetch username: {e}")
|
33 |
return ""
|
|
|
49 |
if not markdown_content:
|
50 |
return None, "Error: Extraction succeeded, but no markdown content was found in the image."
|
51 |
logger.info("Successfully extracted markdown content.")
|
52 |
+
return markdown_content, result.get('status', "Extraction successful.")
|
53 |
except Exception as e:
|
54 |
logger.error(f"Failed to extract from image: {e}")
|
55 |
return None, f"Error during extraction: {e}"
|
56 |
|
57 |
+
def parse_markdown_for_build(markdown_input):
|
58 |
space_info = {"files": []}
|
59 |
current_file_path = None; current_file_content_lines = []
|
60 |
in_file_definition = False; in_code_block = False
|
|
|
98 |
try:
|
99 |
resolved_api_token, token_err = _get_api_token(ui_api_token_from_textbox)
|
100 |
if token_err: return token_err
|
101 |
+
space_info = parse_markdown_for_build(markdown_input)
|
102 |
if not space_info["files"]: return "Error: No files were found after parsing the markdown from the image."
|
103 |
with tempfile.TemporaryDirectory() as temp_dir:
|
104 |
repo_staging_path = Path(temp_dir) / "repo_staging"
|
|
|
123 |
return f"Error during Space creation: {str(e)}"
|
124 |
|
125 |
def build_space_from_image(api_token, repo_image, image_password, new_space_name, owner, sdk):
|
126 |
+
markdown_string, status_msg = extract_markdown_from_image(repo_image, image_password)
|
127 |
+
if not markdown_string:
|
128 |
+
return status_msg
|
129 |
result = create_space(api_token, new_space_name, owner, sdk, markdown_string)
|
130 |
+
return result
|
131 |
+
|
132 |
+
def preview_image_contents(repo_image, image_password):
|
133 |
+
markdown_string, status_msg = extract_markdown_from_image(repo_image, image_password)
|
134 |
+
if not markdown_string:
|
135 |
+
return status_msg, gr.update(visible=False), gr.update(choices=[], value=None), "", []
|
136 |
+
try:
|
137 |
+
file_data, _ = markdown_to_files(markdown_string)
|
138 |
+
if isinstance(file_data, str) or not file_data:
|
139 |
+
raise ValueError("Markdown parsing failed or returned no files.")
|
140 |
+
|
141 |
+
filenames = [f['filename'] for f in file_data]
|
142 |
+
if not filenames:
|
143 |
+
status = "✅ Preview generated, but no files were found in the markdown structure."
|
144 |
+
return status, gr.update(visible=False), gr.update(choices=[], value=None), "", []
|
145 |
+
|
146 |
+
first_filename = filenames
|
147 |
+
first_content = file_data[0]['content']
|
148 |
+
|
149 |
+
status = f"✅ Preview generated successfully. Found {len(filenames)} file(s)."
|
150 |
+
|
151 |
+
return (
|
152 |
+
status,
|
153 |
+
gr.update(visible=True),
|
154 |
+
gr.update(choices=filenames, value=first_filename),
|
155 |
+
first_content,
|
156 |
+
file_data
|
157 |
+
)
|
158 |
+
except Exception as e:
|
159 |
+
logger.error(f"Error parsing markdown for preview: {e}", exc_info=True)
|
160 |
+
error_msg = f"❌ Error: Could not parse files from the image's content. {e}"
|
161 |
+
return error_msg, gr.update(visible=False), gr.update(choices=[], value=None), "", []
|
162 |
+
|
163 |
+
def update_file_preview(selected_filename, all_file_data):
|
164 |
+
if not selected_filename or not all_file_data:
|
165 |
+
return ""
|
166 |
+
selected_file = next((f for f in all_file_data if f['filename'] == selected_filename), None)
|
167 |
+
if selected_file:
|
168 |
+
return selected_file.get('content', 'File content not found.')
|
169 |
+
return f"Select file to view contents."
|