File size: 6,066 Bytes
dfb73fe
 
 
 
2654698
 
dfb73fe
2654698
 
dfb73fe
 
 
 
8789093
dfb73fe
 
8789093
dfb73fe
 
 
 
 
 
8789093
dfb73fe
2654698
 
 
8789093
2654698
8789093
2654698
8789093
ea6d9d6
 
8789093
ef76768
dfb73fe
ef76768
2654698
dfb73fe
ef76768
2654698
8789093
2654698
 
8789093
2654698
8789093
2654698
 
 
8789093
2654698
 
8789093
2654698
8789093
2654698
 
 
8789093
2654698
 
 
8789093
2654698
dfb73fe
8789093
dfb73fe
ef76768
 
8789093
ef76768
8789093
ef76768
 
 
8789093
ef76768
 
 
8789093
ef76768
 
 
 
 
 
 
 
 
8789093
ef76768
8789093
ef76768
 
 
8789093
ef76768
 
 
8789093
ef76768
 
 
 
 
 
 
 
 
8789093
ef76768
 
 
 
 
 
 
8789093
ef76768
 
 
 
 
8789093
ef76768
 
 
 
 
8789093
ef76768
 
 
 
 
8789093
ef76768
dfb73fe
8789093
dfb73fe
2654698
 
 
8789093
2654698
 
 
8789093
2654698
dfb73fe
8789093
dfb73fe
2654698
 
 
dfb73fe
2654698
ea6d9d6
dfb73fe
 
8789093
dfb73fe
 
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
#!/usr/bin/env python3
"""
Space Authentication Test for OpenLLM Training

This script verifies that authentication is working correctly in a Hugging Face Space
environment. It uses the Space's own access token for authentication.

Author: Louis Chua Bean Chong
License: GPLv3
"""

import os
import sys

try:
    from huggingface_hub import HfApi, login, whoami, create_repo, delete_repo

    HF_AVAILABLE = True
except ImportError:
    HF_AVAILABLE = False
    print("❌ huggingface_hub not installed")
    sys.exit(1)


def test_space_authentication():
    """Test authentication using Space's access token."""
    print("πŸ” Testing Space Authentication")
    print("=" * 40)

    # Check if we're in a Space environment
    space_id = os.environ.get("SPACE_ID", "lemms/openllm")
    print(f"πŸ“ Space ID: {space_id}")

    # Check for various authentication methods
    print(f"\nπŸ” Checking authentication methods...")

    # Method 1: Check for Space's built-in authentication (primary method)
    try:
        # Try to get current user info (this will use Space's built-in access token)
        api = HfApi()
        user_info = whoami()
        print(f"βœ… Space built-in authentication successful!")
        print(f"πŸ‘€ User: {user_info}")

        # Test API access by listing Space files
        print(f"\nπŸ“ Testing Space file access...")
        files = api.list_repo_files(repo_id=space_id, repo_type="space")
        print(f"βœ… Successfully listed {len(files)} files in Space")

        # Test repository creation/deletion (temporary test)
        test_repo_name = f"test-repo-{os.getpid()}"
        print(f"\nπŸ§ͺ Testing repository operations...")

        try:
            # Create a temporary test repository
            api.create_repo(repo_id=test_repo_name, repo_type="model", private=True, exist_ok=True)
            print(f"βœ… Successfully created test repository: {test_repo_name}")

            # Delete the test repository
            api.delete_repo(repo_id=test_repo_name, repo_type="model")
            print(f"βœ… Successfully deleted test repository: {test_repo_name}")

        except Exception as e:
            print(f"⚠️ Repository operations test failed: {e}")
            print("   This is normal if the token doesn't have full permissions")

        print(f"\nπŸŽ‰ Space authentication test completed successfully!")
        return True

    except Exception as e:
        print(f"❌ Space built-in authentication failed: {e}")
        print(f"\nπŸ”„ Trying alternative authentication methods...")

    # Method 2: Check for HF access token environment variable (fallback)
    hf_token = os.environ.get("HF_TOKEN")
    if hf_token:
        print(f"βœ… HF access token found in environment")
        print(f"   Token: {hf_token[:8]}...{hf_token[-4:]}")

        try:
            # Try to use the HF_TOKEN
            from huggingface_hub import login

            login(token=hf_token)
            user_info = whoami()
            print(f"βœ… HF access token authentication successful!")
            print(f"πŸ‘€ User: {user_info}")
            return True
        except Exception as e:
            print(f"❌ HF access token authentication failed: {e}")
    else:
        print(f"⚠️ HF access token not found in environment")

    # Method 3: Check for HUGGING_FACE_HUB_TOKEN (fallback)
    hf_hub_token = os.environ.get("HUGGING_FACE_HUB_TOKEN")
    if hf_hub_token:
        print(f"βœ… HUGGING_FACE_HUB_TOKEN found in environment")
        print(f"   Token: {hf_hub_token[:8]}...{hf_hub_token[-4:]}")

        try:
            # Try to use the HUGGING_FACE_HUB_TOKEN
            from huggingface_hub import login

            login(token=hf_hub_token)
            user_info = whoami()
            print(f"βœ… HUGGING_FACE_HUB_TOKEN authentication successful!")
            print(f"πŸ‘€ User: {user_info}")
            return True
        except Exception as e:
            print(f"❌ HUGGING_FACE_HUB_TOKEN authentication failed: {e}")
    else:
        print(f"⚠️ HUGGING_FACE_HUB_TOKEN not found in environment")

    # If all authentication methods failed
    print(f"\n❌ All authentication methods failed")
    print(f"\nπŸ”§ TROUBLESHOOTING STEPS:")
    print(f"1. Check Space Built-in Authentication:")
    print(f"   - Ensure the Space has proper access to Hugging Face Hub")
    print(f"   - Check Space settings for authentication configuration")
    print(f"   - Verify the Space has necessary permissions")

    print(f"\n2. Alternative: Set HF Access Token in Space Settings:")
    print(f"   - Go to https://huggingface.co/spaces/{space_id}/settings")
    print(f"   - Navigate to 'Repository secrets' section")
    print(f"   - Add HF_TOKEN with your HF access token")
    print(f"   - Token should have 'Write' permissions")

    print(f"\n3. Create HF Access Token:")
    print(f"   - Go to https://huggingface.co/settings/tokens")
    print(f"   - Create a new token with 'Write' permissions")
    print(f"   - Copy the token (starts with 'hf_')")
    print(f"   - Add it to Space secrets as HF_TOKEN")

    print(f"\n4. Verify HF Access Token:")
    print(f"   - Token must start with 'hf_' (Hugging Face format)")
    print(f"   - Token must have 'Write' access to repositories")
    print(f"   - Token must be valid and not expired")
    print(f"   - Token must be associated with the correct HF account")

    return False


def main():
    """Main function to run authentication tests."""
    print("πŸš€ OpenLLM Space Authentication Test")
    print("=" * 50)

    if not HF_AVAILABLE:
        print("❌ Required dependencies not available")
        sys.exit(1)

    # Run authentication test
    success = test_space_authentication()

    if success:
        print(f"\nβœ… All authentication tests passed!")
        print(f"πŸš€ Ready for OpenLLM training!")
        sys.exit(0)
    else:
        print(f"\n❌ Authentication tests failed!")
        print(f"πŸ”§ Please follow the troubleshooting steps above.")
        sys.exit(1)


if __name__ == "__main__":
    main()