File size: 4,010 Bytes
0210a65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Hugging Face Hub & Space One-Click Publishing Script
Publishes:
  1. Model Checkpoints & Model Card to Hugging Face Model Hub
  2. Interactive Gradio Demo to Hugging Face Spaces
"""

import os
import sys
import argparse
from pathlib import Path

try:
    from huggingface_hub import HfApi, create_repo
except ImportError:
    print("[!] huggingface_hub not installed. Run: pip install huggingface_hub")
    sys.exit(1)


def get_authenticated_api(token: str = None) -> tuple[HfApi, str]:
    import huggingface_hub
    # Remove invalid environment variable if present
    if "HF_TOKEN" in os.environ and not token:
        try:
            api = HfApi(token=os.environ["HF_TOKEN"])
            user_info = api.whoami()
            username = user_info.get("name", user_info.get("username"))
            return api, username
        except Exception:
            os.environ.pop("HF_TOKEN", None)

    valid_token = token or huggingface_hub.get_token()
    api = HfApi(token=valid_token)
    user_info = api.whoami()
    username = user_info.get("name", user_info.get("username"))
    return api, username


def push_to_hub(repo_id: str = None, repo_type: str = "space", token: str = None):
    api, username = get_authenticated_api(token=token)
    print(f"[+] Authenticated as Hugging Face user: {username}")

    if not repo_id:
        repo_id = f"{username}/certified-safe-neural-control"

    print("=" * 70)
    print(f"HUGGING FACE PUBLISHER: {repo_id} ({repo_type})")
    print("=" * 70)

    # 1. Ensure repository exists
    print(f"[*] Ensuring repository exists: {repo_id}...")
    try:
        api.create_repo(
            repo_id=repo_id,
            repo_type=repo_type,
            exist_ok=True,
            space_sdk="gradio" if repo_type == "space" else None,
        )
        url_prefix = "spaces/" if repo_type == "space" else ""
        print(f"[+] Repository online: https://huggingface.co/{url_prefix}{repo_id}")
    except Exception as e:
        print(f"[*] Note: {e}")

    # 2. Upload workspace directory
    workspace_dir = Path(__file__).resolve().parent.parent
    ignore_patterns = [
        "__pycache__/*",
        ".pytest_cache/*",
        "*.pyc",
        ".git/*",
        "*.tmp",
        "*.swp",
        ".user_uploaded/*",
        "*.log",
    ]

    print(f"[*] Uploading files from {workspace_dir}...")
    api.upload_folder(
        folder_path=str(workspace_dir),
        repo_id=repo_id,
        repo_type=repo_type,
        ignore_patterns=ignore_patterns,
        commit_message=f"Release: Certified-Safe Neural Control {repo_type.upper()} v1.0",
    )

    # For model repositories, upload MODEL_CARD.md as the repository README.md
    if repo_type == "model":
        model_card_path = workspace_dir / "MODEL_CARD.md"
        if model_card_path.exists():
            print("[*] Publishing specialized Model Card to Model Hub...")
            api.upload_file(
                path_or_fileobj=str(model_card_path),
                path_in_repo="README.md",
                repo_id=repo_id,
                repo_type="model",
                commit_message="Update Model Card documentation and PyTorch metadata",
            )

    url_prefix = "spaces/" if repo_type == "space" else ""
    print("-" * 70)
    print(f"🎉 SUCCESS! Your {repo_type.upper()} is live at:")
    print(f"👉 https://huggingface.co/{url_prefix}{repo_id}")
    print("=" * 70)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Push Certified Neural Control to Hugging Face")
    parser.add_argument("--repo-id", type=str, default=None, help="HF repository ID (defaults to 'codewithyug/certified-safe-neural-control')")
    parser.add_argument("--type", type=str, default="space", choices=["model", "space"], help="Repository type: 'space' or 'model'")
    parser.add_argument("--token", type=str, default=None, help="Optional access token")
    args = parser.parse_args()

    push_to_hub(repo_id=args.repo_id, repo_type=args.type, token=args.token)