# @title Hugging Face to GitHub Transfer import sys import os import shutil import subprocess from pathlib import Path import gradio as gr import requests from dotenv import load_dotenv def install(package): try: __import__(package) except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", package]) install("gradio") install("python-dotenv") install("requests") def run(cmd): result = subprocess.run(cmd, shell=True, capture_output=True, text=True) log = f"$ {cmd}\n" if result.stdout: log += result.stdout if result.stderr: log += result.stderr if result.returncode != 0: raise RuntimeError(log) return log def create_github_repo(token, username, repo_name, private): url = "https://api.github.com/user/repos" headers = { "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json" } data = { "name": repo_name, "private": private == "private", "auto_init": False } response = requests.post(url, headers=headers, json=data) if response.status_code == 201: return f"✅ GitHub repository '{repo_name}' created.\n" elif response.status_code == 422 and "already exists" in response.text: return f"⚠️ Repo '{repo_name}' already exists. Continuing...\n" else: error_msg = response.json().get("message", "Unknown error") docs_url = response.json().get("documentation_url", "") raise RuntimeError(f"❌ GitHub repo creation failed: {error_msg}\nDocumentation: {docs_url}") def validate_github_token(token): """Validate the GitHub token with detailed error handling""" url = "https://api.github.com/user" headers = { "Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json" } try: response = requests.get(url, headers=headers, timeout=10) except requests.exceptions.RequestException as e: raise RuntimeError(f"❌ Network error during token validation: {str(e)}") if response.status_code == 200: # Check token scopes scopes = response.headers.get('X-OAuth-Scopes', '') if 'repo' not in scopes: return response.json()["login"], f"⚠️ Token missing 'repo' scope. Your scopes: {scopes}" return response.json()["login"], None else: # Handle specific GitHub error codes if response.status_code == 401: error_msg = "Token is invalid or expired" elif response.status_code == 403: # Check for rate limiting rate_limit = response.headers.get('X-RateLimit-Limit', '?') rate_remaining = response.headers.get('X-RateLimit-Remaining', '?') reset_time = response.headers.get('X-RateLimit-Reset', '?') error_msg = (f"API rate limit exceeded (Remaining: {rate_remaining}/{rate_limit}, " f"Resets at: {reset_time})") else: try: error_json = response.json() error_msg = error_json.get('message', f"HTTP error {response.status_code}") if 'documentation_url' in error_json: error_msg += f"\nDocumentation: {error_json['documentation_url']}" except: error_msg = f"HTTP error {response.status_code}" # Provide troubleshooting tips tips = ( "\n\n🔧 Troubleshooting Tips:\n" "1. Verify token has 'repo' scope: https://github.com/settings/tokens\n" "2. Check token expiration: https://github.com/settings/tokens\n" "3. For classic tokens, ensure 'repo' scope is selected\n" "4. Try regenerating your token" ) raise RuntimeError(f"❌ Invalid GitHub token: {error_msg}{tips}") def transfer_repo( hf_repo_url, github_username, github_repo_name, github_token, git_user_name, git_user_email, branch, token_file, visibility): try: # Load from token.env if uploaded if token_file: env_path = Path("token.env") shutil.copy(token_file.name, env_path) load_dotenv(dotenv_path=env_path) github_token = os.getenv("GITHUB_TOKEN", github_token) github_username = os.getenv("GITHUB_USERNAME", github_username) git_user_name = os.getenv("GIT_USER_NAME", git_user_name) git_user_email = os.getenv("GIT_USER_EMAIL", git_user_email) visibility = os.getenv("REPO_VISIBILITY", visibility) branch = os.getenv("GIT_BRANCH", branch) # Strip any accidental whitespace from token github_token = github_token.strip() # Validate GitHub token before proceeding try: validated_username, scope_warning = validate_github_token(github_token) if github_username and github_username != validated_username: return (f"❌ Token username mismatch! Token belongs to '{validated_username}' " f"but you entered '{github_username}'", None) github_username = validated_username except Exception as e: return f"❌ Token validation failed: {str(e)}", None # Save token.env - WITHOUT COMMENTS token_env_path = "token.env" with open(token_env_path, "w") as f: f.write(f"GITHUB_TOKEN={github_token}\n") f.write(f"GITHUB_USERNAME={github_username}\n") f.write(f"GIT_USER_NAME={git_user_name}\n") f.write(f"GIT_USER_EMAIL={git_user_email}\n") f.write(f"REPO_VISIBILITY={visibility}\n") f.write(f"GIT_BRANCH={branch}\n") hf_repo_url = hf_repo_url.strip().replace("git clone", "").strip().rstrip("/") repo_name = hf_repo_url.split("/")[-1].replace(".git", "") github_repo_name = github_repo_name.strip().lower().replace(" ", "-") github_repo_url = f"https://{github_token}@github.com/{github_username}/{github_repo_name}.git" log = "" log += scope_warning + "\n" if scope_warning else "" log += create_github_repo(github_token, github_username, github_repo_name, visibility) if os.path.exists(repo_name): shutil.rmtree(repo_name) log += run(f"git clone {hf_repo_url}") os.chdir(repo_name) log += run(f'git config user.name "{git_user_name}"') log += run(f'git config user.email "{git_user_email}"') log += run("git remote rename origin hf-origin") log += run(f"git remote add origin {github_repo_url}") try: log += run(f"git pull --rebase origin {branch}") except RuntimeError as e: if "couldn't find remote ref" in str(e): log += f"⚠️ Remote branch '{branch}' not found. Skipping pull.\n" else: raise log += run(f"git push -u origin {branch}") os.chdir("..") # Success summary with minimal details summary = ( "✅ Transfer complete!\n\n" f"**Hugging Face URL:** {hf_repo_url}\n" f"**New GitHub Repo:** {github_repo_name}\n" f"**GitHub URL:** https://github.com/{github_username}/{github_repo_name}\n" f"**Branch:** {branch}\n" f"**Visibility:** {visibility}\n\n" "⬇️ Download your token.env file below for future use." ) return summary, token_env_path except Exception as e: return f"❌ Error: {str(e)}", None def toggle_inputs(token_file): if token_file: return ( gr.update(visible=True), # hf_repo_url gr.update(visible=True), # github_repo_name gr.update(visible=False), # github_username gr.update(visible=False), # github_token gr.update(visible=False), # git_user_name gr.update(visible=False), # git_user_email gr.update(visible=True), # branch gr.update(visible=True) # visibility ) else: return tuple([gr.update(visible=True)] * 8) def launch_app(): with gr.Blocks(title="Hugging Face to GitHub Transfer", theme=gr.themes.Soft()) as demo: gr.Markdown("# Hugging Face → GitHub Transfer Tool") gr.Markdown( "Transfer a Hugging Face model repo to GitHub.\n\n" "**Your credentials are only stored locally in a `.env` file.**\n\n" "### 🔐 Create a `token.env` file manually (optional)\n" "```ini\n" "GITHUB_TOKEN=your_github_token\n" "GITHUB_USERNAME=your_username\n" "GIT_USER_NAME=Your Name\n" "GIT_USER_EMAIL=you@example.com\n" "REPO_VISIBILITY=public\n" "GIT_BRANCH=main\n" "```\n\n" "### 🔑 GitHub Token Requirements\n" "- Create at: https://github.com/settings/tokens\n" "- Must be a **classic token** with **repo scope**\n" "- Token must start with `ghp_` (40 characters)\n" "- Required permissions: `repo` (full control)\n" "- Never share your token with anyone!\n" "- Token expires after 30 days by default (set expiration to 'No expiration')" ) with gr.Row(): token_file = gr.File(label="Upload token.env (optional)", file_types=[".env"]) with gr.Column(): hf_repo_url = gr.Textbox(label="Hugging Face Repo URL (.git)", placeholder="https://huggingface.co/username/repo_name") github_repo_name = gr.Textbox(label="New GitHub Repo Name", placeholder="my-new-repo") with gr.Row(): github_username = gr.Textbox(label="GitHub Username", placeholder="your-github-username") github_token = gr.Textbox(label="GitHub Token", type="password", placeholder="ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") with gr.Row(): git_user_name = gr.Textbox(label="Git Commit Author Name", value="Your Name") git_user_email = gr.Textbox(label="Git Commit Author Email", value="you@example.com") with gr.Row(): branch = gr.Dropdown(["main", "dev", "test", "custom"], label="GitHub Branch", value="main") visibility = gr.Dropdown(["public", "private"], label="Visibility", value="public") run_btn = gr.Button("Start Transfer", variant="primary") with gr.Column(): output = gr.Textbox(label="Transfer Log", lines=10, interactive=False, show_copy_button=True) token_download = gr.File(label="Download token.env", visible=False, interactive=True) token_file.change( fn=toggle_inputs, inputs=[token_file], outputs=[ hf_repo_url, github_repo_name, github_username, github_token, git_user_name, git_user_email, branch, visibility ] ) run_btn.click( fn=transfer_repo, inputs=[ hf_repo_url, github_username, github_repo_name, github_token, git_user_name, git_user_email, branch, token_file, visibility ], outputs=[output, token_download] ) # Display the token.env download link immediately after transfer token_download.change( lambda x: gr.update(visible=x is not None), inputs=[token_download], outputs=[token_download] ) demo.launch() if __name__ == "__main__": launch_app()