Spaces:
Running
Running
File size: 13,365 Bytes
60d3ef3 0ba847f 60d3ef3 e69109f b0d467a 8bd1285 7add58d 60d3ef3 407e564 9eb0165 e69109f 60d3ef3 0ba847f b0d467a f558e4b e69109f f558e4b 0ba847f f558e4b bf97231 ae75d50 f558e4b 0ba847f e69109f 0ba847f f558e4b 0ba847f edfea02 996229b edfea02 996229b edfea02 0dbf77b 3c21868 0dbf77b edfea02 f558e4b 60d3ef3 0ba847f 60d3ef3 e69109f ae75d50 0ba847f 60d3ef3 0ba847f 60d3ef3 0ba847f 60d3ef3 e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f f558e4b 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f e69109f 0ba847f 60d3ef3 e69109f 0ba847f e69109f 60d3ef3 6866628 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
import gradio as gr
# No os needed here now for file paths unless for basename for display
from app_logic import (
create_space,
update_space_file,
load_token_from_image_and_set_env,
KEYLOCK_DECODE_AVAILABLE,
list_space_files_for_browsing,
get_space_file_content,
)
KEYLOCK_DECODE_AVAILABLE = False
# Gradio interface
def main_ui():
with gr.Blocks(theme=gr.themes.Soft(primary_hue=gr.themes.colors.blue, secondary_hue=gr.themes.colors.sky), title="Hugging Face Space Builder") as demo:
gr.Markdown(
"""
# π οΈ Hugging Face Space Builder
## Build Huggingface Space from a standardized string that models can be prompted to export.
Create, view, and manage Hugging Face Spaces.
Provide your Hugging Face API token directly or load it from a KeyLock Wallet image.
"""
)
# --- Authentication Section (Unchanged) ---
with gr.Accordion("π Authentication Methods", open=False):
gr.Markdown(
"""
**Token Precedence:**
1. If a token is successfully loaded from a KeyLock Wallet image, it will be used.
2. Otherwise, the token entered in the 'Enter API Token Directly' textbox will be used.
"""
)
gr.Markdown("---")
gr.Markdown("### Method 1: Enter API Token Directly")
api_token_ui_input = gr.Textbox(label="Hugging Face API Token (hf_xxx)", type="password", placeholder="Enter token OR load from Wallet image")
if KEYLOCK_DECODE_AVAILABLE:
gr.Markdown("---")
gr.Markdown("### Method 2: Load API Token to this sytem environment from KeyLock Wallet Image")
gr.Markdown("### Get a KeyLock Wallet Image Here: [/spaces/broadfield-dev/KeyLock-API-Wallet](https://huggingface.co/spaces/broadfield-dev/KeyLock-API-Wallet)")
with gr.Row():
keylock_image_input = gr.Image(label="KeyLock Wallet Image (PNG)", type="pil", image_mode="RGBA")
keylock_password_input = gr.Textbox(label="Image Password", type="password")
keylock_decode_button = gr.Button("Load Token from Wallet Image", variant="secondary")
keylock_status_output = gr.Markdown(label="Wallet Image Decoding Status", value="Status...")
keylock_decode_button.click(load_token_from_image_and_set_env, [keylock_image_input, keylock_password_input], [keylock_status_output])
else:
gr.Markdown("_(KeyLock Wallet image decoding disabled: library not found.)_")
with gr.Accordion("π£ Example Prompt", open=False):
gr.Markdown("""```plaintext
# Prompt:
Generate program files for a project as a single plain text string, strictly adhering to the markdown format below. **Every single line**, including backticks, language identifiers, file content, and empty lines, **must** be prefixed with '# ' to comment it out. This is critical to avoid code box interference. The output must include a complete file structure and the contents of each file, with all necessary code and configurations for a functional project. **Do not deviate from this format under any circumstances.**
# Format (exact return format with single leading "# "):
# # Space: [owner/project-name]
# ## File Structure
# ```
# π Root
# π [file1]
# π [file2]
# ...
#
#
# Below are the contents of all files in the space:
#
# ### File: [file1]
# ```[language]
# [content]
# ```
#
# ### File: [file2]
# ```[language]
# [content]
# ```
#
# ... (repeat for each file)
# Correct Example Output (exact, every line prefixed with '# '):
# # Space: user/my-app
# ## File Structure
# ```
# π Root
# π app.py
# π requirements.txt
# ```
#
# # Below are the contents of all files in the space:
#
# ### File: app.py
# ```python
# print("Hello, World!")
# ```
#
# ### File: requirements.txt
# ```text
# gradio==4.44.0
# ```
# Incorrect Example Output:
## ## File Structure <- INCORRECT: AI used "## " instead of "# "
## ```text <- INCORRECT
## π Root <- INCORRECT (missing "# ")
# # # π Root <- INCORRECT: AI used "# # #" instead of "# "
# Instructions:
- Use exactly `# # Space: [owner/project-name]` as the header (e.g., `user/my-app`).
- Under `## File Structure`, start with `# π Root` followed by `# π` for each file, using exact icons and spacing.
- For each file, use `# ### File: [filename]` followed by a code block where every line, including backticks (e.g., `# ```), language identifier (e.g., `# python`), and content (e.g., `# print("Hello")`), is prefixed with `# `.
- For binary files, use `# [Binary file - size in bytes]` as content with no language identifier.
- **Every line** must start with `# `, no exceptions, including empty lines within code blocks.
- Provide accurate, functional code or content for each file, suitable for the projectβs purpose.
- Ensure the output is concise, complete, and parseable to extract file structure and contents.
- Output everything as a single plain text string within one code box.
```
"""
)
# --- Main Application Tabs ---
with gr.Tabs():
with gr.TabItem("π Create New Space"):
# (Create Space UI Unchanged)
with gr.Row():
space_name_create_input = gr.Textbox(label="Space Name", placeholder="my-awesome-app (no slashes)", scale=2)
owner_create_input = gr.Textbox(label="Owner Username/Org", placeholder="Leave blank for your HF username", scale=1)
sdk_create_input = gr.Dropdown(label="Space SDK", choices=["gradio", "streamlit", "docker", "static"], value="gradio")
gr.Markdown("### Example Source: [/spaces/broadfield-dev/repo_to_md](https://huggingface.co/spaces/broadfield-dev/repo_to_md)")
markdown_input_create = gr.Textbox(label="Markdown File Structure & Content", placeholder="Example:\n### File: app.py\n# ```python\nprint(\"Hello\")\n# ```", lines=15, interactive=True)
create_btn = gr.Button("Create Space", variant="primary")
create_output_md = gr.Markdown(label="Result")
create_btn.click(create_space, [api_token_ui_input, space_name_create_input, owner_create_input, sdk_create_input, markdown_input_create], create_output_md)
# --- "Browse & Edit Files" Tab (Hub-based) ---
with gr.TabItem("π Browse & Edit Space Files"):
gr.Markdown("Browse, view, and edit files directly on a Hugging Face Space.")
with gr.Row():
browse_space_name_input = gr.Textbox(label="Space Name", placeholder="my-target-app", scale=2)
browse_owner_input = gr.Textbox(label="Owner Username/Org", placeholder="Leave blank if it's your space", scale=1)
browse_load_files_button = gr.Button("Load Files List from Space", variant="secondary")
browse_status_output = gr.Markdown(label="File List Status")
gr.Markdown("---")
gr.Markdown("### Select File to View/Edit")
# Using Radio for file list. Could be Dropdown for many files.
# `choices` will be updated dynamically.
file_selector_radio = gr.Radio(
label="Files in Space",
choices=[],
interactive=True,
info="Select a file to load its content below."
)
gr.Markdown("---")
gr.Markdown("### File Editor")
file_editor_textbox = gr.Textbox(
label="File Content (Editable)", lines=20, interactive=True,
placeholder="Select a file from the list above to view/edit its content."
)
edit_commit_message_input = gr.Textbox(label="Commit Message for Update", placeholder="e.g., Update app.py content")
update_edited_file_button = gr.Button("Update File in Space", variant="primary")
edit_update_status_output = gr.Markdown(label="File Update Result")
# --- Event Handlers for Browse & Edit Tab (Hub-based) ---
def handle_load_space_files_list(token_from_ui, space_name, owner_name):
if not space_name:
return {
browse_status_output: gr.Markdown("Error: Space Name cannot be empty."),
file_selector_radio: gr.Radio(choices=[], value=None), # Clear radio
file_editor_textbox: gr.Textbox(value=""), # Clear editor
}
files_list, error_msg = list_space_files_for_browsing(token_from_ui, space_name, owner_name)
if error_msg and files_list is None: # Indicates a hard error
return {
browse_status_output: gr.Markdown(f"Error: {error_msg}"),
file_selector_radio: gr.Radio(choices=[], value=None),
file_editor_textbox: gr.Textbox(value=""),
}
if error_msg and not files_list: # Info message like "no files found"
return {
browse_status_output: gr.Markdown(error_msg), # Show "No files found"
file_selector_radio: gr.Radio(choices=[], value=None),
file_editor_textbox: gr.Textbox(value=""),
}
return {
browse_status_output: gr.Markdown(f"Files loaded for '{owner_name}/{space_name}'. Select a file to edit."),
file_selector_radio: gr.Radio(choices=files_list, value=None, label=f"Files in {owner_name}/{space_name}"),
file_editor_textbox: gr.Textbox(value=""), # Clear editor on new list load
}
browse_load_files_button.click(
fn=handle_load_space_files_list,
inputs=[api_token_ui_input, browse_space_name_input, browse_owner_input],
outputs=[browse_status_output, file_selector_radio, file_editor_textbox]
)
def handle_file_selected_for_editing(token_from_ui, space_name, owner_name, selected_filepath_evt: gr.SelectData):
if not selected_filepath_evt or not selected_filepath_evt.value:
# This might happen if the radio is cleared or has no selection
return {
file_editor_textbox: gr.Textbox(value=""),
browse_status_output: gr.Markdown("No file selected or selection cleared.")
}
selected_filepath = selected_filepath_evt.value # The value of the selected radio button
if not space_name: # Should not happen if file list is populated
return {
file_editor_textbox: gr.Textbox(value="Error: Space name is missing."),
browse_status_output: gr.Markdown("Error: Space context lost. Please reload file list.")
}
content, error_msg = get_space_file_content(token_from_ui, space_name, owner_name, selected_filepath)
if error_msg:
return {
file_editor_textbox: gr.Textbox(value=f"Error loading file content: {error_msg}"),
browse_status_output: gr.Markdown(f"Failed to load '{selected_filepath}': {error_msg}")
}
return {
file_editor_textbox: gr.Textbox(value=content),
browse_status_output: gr.Markdown(f"Content loaded for: {selected_filepath}")
}
# Use .select event for gr.Radio
file_selector_radio.select(
fn=handle_file_selected_for_editing,
inputs=[api_token_ui_input, browse_space_name_input, browse_owner_input], # Pass space context again
outputs=[file_editor_textbox, browse_status_output]
)
update_edited_file_button.click(
fn=update_space_file,
inputs=[
api_token_ui_input,
browse_space_name_input,
browse_owner_input,
file_selector_radio, # Pass the selected file path from the radio
file_editor_textbox,
edit_commit_message_input
],
outputs=[edit_update_status_output]
)
return demo
if __name__ == "__main__":
demo = main_ui()
demo.launch(mcp_server=True,show_error=True) |