Spaces:
Sleeping
Sleeping
File size: 10,347 Bytes
8bd1285 |
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 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
import gradio as gr
import os
import re
import tempfile
import shutil
import git
from huggingface_hub import (
create_repo,
upload_folder,
list_repo_files,
delete_file,
Repository,
whoami,
)
from huggingface_hub.utils import HfHubHTTPError
import logging
from pathlib import Path
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Function to parse markdown input
def parse_markdown(markdown_input):
"""Parse markdown input to extract space details and file structure."""
space_info = {"repo_name": "", "owner": "", "sdk": "gradio", "files": []}
current_file = None
file_content = []
in_file_content = False
lines = markdown_input.strip().split("\n")
for line in lines:
line = line.strip()
# Extract space name
if line.startswith("# Space:"):
space_info["repo_name"] = line.replace("# Space:", "").strip()
if "/" in space_info["repo_name"]:
space_info["owner"], space_info["repo_name"] = space_info["repo_name"].split("/", 1)
# Detect file structure section
elif line.startswith("## File Structure"):
continue
# Detect file in structure
elif line.startswith("๐") or line.startswith("๐"):
if current_file and file_content:
space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
file_content = []
current_file = line[2:].strip()
in_file_content = False
# Detect file content section
elif line.startswith("### File:"):
if current_file and file_content:
space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
file_content = []
current_file = line.replace("### File:", "").strip()
in_file_content = True
# Handle file content
elif in_file_content and line.startswith("```"):
if file_content:
space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
file_content = []
in_file_content = False
else:
in_file_content = True
elif in_file_content:
file_content.append(line)
# Append the last file
if current_file and file_content:
space_info["files"].append({"path": current_file, "content": "\n".join(file_content)})
return space_info
# Function to create and populate a Space
def create_space(api_token, space_name, owner, sdk, markdown_input):
"""Create a Hugging Face Space and populate it with files from markdown input."""
try:
# Authenticate with Hugging Face Hub
if not api_token:
return "Error: Please provide a valid Hugging Face API token."
# Get user info
user_info = whoami(token=api_token)
if not owner:
owner = user_info["name"]
repo_id = f"{owner}/{space_name}"
# Create temporary directory
with tempfile.TemporaryDirectory() as temp_dir:
repo_path = os.path.join(temp_dir, space_name)
os.makedirs(repo_path, exist_ok=True)
# Parse markdown input
space_info = parse_markdown(markdown_input)
if space_info["repo_name"] != f"{owner}/{space_name}":
return "Error: Space name in markdown does not match provided owner/space_name."
# Write files to temporary directory
for file_info in space_info["files"]:
file_path = os.path.join(repo_path, file_info["path"])
os.makedirs(os.path.dirname(file_path), exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
f.write(file_info["content"])
logger.info(f"Wrote file: {file_path}")
# Create repository on Hugging Face
try:
create_repo(
repo_id=repo_id,
token=api_token,
repo_type="space",
space_sdk=sdk,
private=False,
)
logger.info(f"Created Space: {repo_id}")
except HfHubHTTPError as e:
if "already exists" in str(e):
logger.info(f"Space {repo_id} already exists, proceeding to update.")
else:
return f"Error creating Space: {str(e)}"
# Initialize Git repository
repo = git.Repo.init(repo_path)
repo.git.add(all=True)
repo.index.commit("Initial commit from Gradio app")
# Push to Hugging Face Space
upload_folder(
repo_id=repo_id,
folder_path=repo_path,
path_in_repo=".",
token=api_token,
commit_message="Initial Space setup",
)
return f"Successfully created Space: https://huggingface.co/spaces/{repo_id}"
except Exception as e:
logger.error(f"Error: {str(e)}")
return f"Error: {str(e)}"
# Function to view Space files
def view_space_files(api_token, space_name, owner):
"""List files in a Hugging Face Space."""
try:
if not api_token:
return "Error: Please provide a valid Hugging Face API token."
repo_id = f"{owner}/{space_name}" if owner else space_name
files = list_repo_files(repo_id=repo_id, token=api_token, repo_type="space")
return "\n".join(files) or "No files found in the Space."
except Exception as e:
return f"Error: {str(e)}"
# Function to update a Space file
def update_space_file(api_token, space_name, owner, file_path, file_content, commit_message):
"""Update a file in a Hugging Face Space with a commit."""
try:
if not api_token:
return "Error: Please provide a valid Hugging Face API token."
repo_id = f"{owner}/{space_name}" if owner else space_name
# Create temporary directory for cloning
with tempfile.TemporaryDirectory() as temp_dir:
repo_path = os.path.join(temp_dir, space_name)
repo = Repository(
local_dir=repo_path,
clone_from=f"https://huggingface.co/spaces/{repo_id}",
repo_type="space",
use_auth_token=api_token,
)
# Write updated file
full_path = os.path.join(repo_path, file_path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
with open(full_path, "w", encoding="utf-8") as f:
f.write(file_content)
# Commit and push changes
repo.git_add(file_path)
repo.git_commit(commit_message or f"Update {file_path}")
repo.git_push()
return f"Successfully updated {file_path} in Space: https://huggingface.co/spaces/{repo_id}"
except Exception as e:
return f"Error: {str(e)}"
# Gradio interface
def main():
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown("# Hugging Face Space Builder")
gr.Markdown("Create, view, and update Hugging Face Spaces with a custom file structure.")
# Authentication
with gr.Group():
gr.Markdown("## Authentication")
api_token = gr.Textbox(
label="Hugging Face API Token",
type="password",
placeholder="Enter your Hugging Face API token",
)
# Create Space
with gr.Group():
gr.Markdown("## Create a New Space")
space_name = gr.Textbox(label="Space Name", placeholder="my-space")
owner = gr.Textbox(
label="Owner (optional)", placeholder="Leave blank for current user"
)
sdk = gr.Dropdown(
label="SDK", choices=["gradio", "streamlit", "docker", "static"], value="gradio"
)
markdown_input = gr.Textbox(
label="Markdown File Structure",
placeholder="Paste markdown with file structure and contents",
lines=10,
)
create_btn = gr.Button("Create Space")
create_output = gr.Textbox(label="Result")
# View Space Files
with gr.Group():
gr.Markdown("## View Space Files")
view_space_name = gr.Textbox(label="Space Name", placeholder="my-space")
view_owner = gr.Textbox(
label="Owner (optional)", placeholder="Leave blank for current user"
)
view_btn = gr.Button("List Files")
view_output = gr.Textbox(label="Files in Space")
# Update Space File
with gr.Group():
gr.Markdown("## Update Space File")
update_space_name = gr.Textbox(label="Space Name", placeholder="my-space")
update_owner = gr.Textbox(
label="Owner (optional)", placeholder="Leave blank for current user"
)
file_path = gr.Textbox(label="File Path", placeholder="path/to/file.py")
file_content = gr.Textbox(
label="File Content", placeholder="Enter new file content", lines=10
)
commit_message = gr.Textbox(
label="Commit Message", placeholder="Update file content"
)
update_btn = gr.Button("Update File")
update_output = gr.Textbox(label="Result")
# Event handlers
create_btn.click(
fn=create_space,
inputs=[api_token, space_name, owner, sdk, markdown_input],
outputs=create_output,
)
view_btn.click(
fn=view_space_files,
inputs=[api_token, view_space_name, view_owner],
outputs=view_output,
)
update_btn.click(
fn=update_space_file,
inputs=[
api_token,
update_space_name,
update_owner,
file_path,
file_content,
commit_message,
],
outputs=update_output,
)
return demo
if __name__ == "__main__":
demo = main()
demo.launch() |