import gradio as gr import subprocess import os def clone_repo(repo_id: str) -> str: """ Clones a Hugging Face repository into the Space's local storage. Args: repo_id: The ID of the repository to clone (e.g., 'meta-llama/Llama-2-7b-hf'). Returns: A string indicating the status of the clone operation. """ if not repo_id or len(repo_id.strip()) == 0: return "āŒ Error: Repository ID cannot be empty. Please enter a valid ID." # Construct the full repository URL repo_url = f"https://huggingface.co/{repo_id}" # Use the repo name as the local directory name local_dir_name = repo_id.split('/')[-1] # Prevent cloning into an existing directory if os.path.exists(local_dir_name): return f"āš ļø Warning: Directory '{local_dir_name}' already exists. The repository may have been cloned already." try: # Execute the 'git clone' command # The '--depth 1' flag does a shallow clone to save time and space # Remove it if you need the full commit history process = subprocess.run( ["git", "clone", "--depth", "1", repo_url], capture_output=True, text=True, check=True ) # Combine stdout and stderr for a complete log log_output = f"STDOUT:\n{process.stdout}\n\nSTDERR:\n{process.stderr}" return f"āœ… Success! Cloned '{repo_id}' into '/{local_dir_name}'.\n\nšŸ“œ **Log:**\n```\n{log_output}\n```" except subprocess.CalledProcessError as e: # Handle errors from the git command (e.g., repo not found) error_output = f"STDOUT:\n{e.stdout}\n\nSTDERR:\n{e.stderr}" return f"āŒ **Error:** Failed to clone repository '{repo_id}'.\nIt might be private or spelled incorrectly.\n\nšŸ“œ **Log:**\n```\n{error_output}\n```" except Exception as e: # Catch any other unexpected errors return f"An unexpected error occurred: {str(e)}" # --- Gradio Interface --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown( """ # šŸ¤— Hugging Face Repository Cloner Enter a repository ID to clone it into this Space's persistent storage. """ ) with gr.Row(): repo_id_input = gr.Textbox( label="HF Repository ID", placeholder="e.g., meta-llama/Llama-2-7b-chat-hf", scale=4 ) clone_button = gr.Button("Clone Repository", variant="primary", scale=1) output_status = gr.Markdown(label="Clone Status") clone_button.click( fn=clone_repo, inputs=repo_id_input, outputs=output_status ) gr.Examples( ["gradio-app/gradio", "CompVis/stable-diffusion-v1-4", "facebook/dino"], inputs=repo_id_input ) demo.launch()