lemms commited on
Commit
1cb5d9f
Β·
verified Β·
1 Parent(s): 57d76cc

Add Space authentication setup script

Browse files
Files changed (1) hide show
  1. setup_hf_space_auth.py +404 -0
setup_hf_space_auth.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hugging Face Space Authentication Setup (GitHub Secrets)
4
+
5
+ This script helps set up proper authentication for Hugging Face Spaces
6
+ using GitHub secrets to ensure training and model uploads work correctly.
7
+
8
+ Features:
9
+ - Sets up authentication for Hugging Face Spaces using GitHub secrets
10
+ - Tests repository creation and upload capabilities
11
+ - Provides configuration for Space environments
12
+ - Validates authentication before training
13
+
14
+ Usage:
15
+ python setup_hf_space_auth.py
16
+
17
+ Author: Louis Chua Bean Chong
18
+ License: GPLv3
19
+ """
20
+
21
+ import os
22
+ import sys
23
+ import json
24
+ from pathlib import Path
25
+
26
+ try:
27
+ from huggingface_hub import HfApi, login, whoami, create_repo
28
+ from huggingface_hub.utils import HfHubHTTPError
29
+ HF_AVAILABLE = True
30
+ except ImportError:
31
+ HF_AVAILABLE = False
32
+ print("❌ huggingface_hub not installed")
33
+ sys.exit(1)
34
+
35
+
36
+ class HuggingFaceSpaceAuthSetup:
37
+ """
38
+ Sets up authentication for Hugging Face Spaces training and upload using GitHub secrets.
39
+ """
40
+
41
+ def __init__(self):
42
+ """Initialize the Space authentication setup."""
43
+ self.api = None
44
+ self.username = None
45
+ self.is_authenticated = False
46
+ self.space_config = {}
47
+
48
+ def setup_space_authentication(self) -> bool:
49
+ """
50
+ Set up authentication specifically for Hugging Face Spaces using GitHub secrets.
51
+
52
+ Returns:
53
+ True if authentication successful, False otherwise
54
+ """
55
+ print("πŸš€ Hugging Face Space Authentication Setup (GitHub Secrets)")
56
+ print("=" * 65)
57
+
58
+ # Check if we're in a Hugging Face Space
59
+ is_space = self._check_if_in_space()
60
+
61
+ if is_space:
62
+ print("βœ… Running in Hugging Face Space environment")
63
+ return self._setup_space_env_auth()
64
+ else:
65
+ print("ℹ️ Running in local environment")
66
+ return self._setup_local_auth()
67
+
68
+ def _check_if_in_space(self) -> bool:
69
+ """Check if we're running in a Hugging Face Space."""
70
+ space_env_vars = [
71
+ "SPACE_ID",
72
+ "SPACE_HOST",
73
+ "SPACE_REPO_ID",
74
+ "HF_HUB_ENABLE_HF_TRANSFER"
75
+ ]
76
+
77
+ for var in space_env_vars:
78
+ if os.getenv(var):
79
+ print(f" - Found Space environment variable: {var}")
80
+ return True
81
+
82
+ return False
83
+
84
+ def _setup_space_env_auth(self) -> bool:
85
+ """Set up authentication in Hugging Face Space environment using GitHub secrets."""
86
+ print("\nπŸ” Setting up Space Environment Authentication (GitHub Secrets)")
87
+ print("-" * 60)
88
+
89
+ # In Spaces with GitHub integration, authentication is handled via HF_TOKEN from GitHub secrets
90
+ token = os.getenv("HF_TOKEN")
91
+ if not token:
92
+ print("❌ HF_TOKEN not found in Space environment")
93
+ print(" - This should be set in your GitHub repository secrets")
94
+ print(" - Go to your GitHub repository β†’ Settings β†’ Secrets and variables β†’ Actions")
95
+ print(" - Add HF_TOKEN with your Hugging Face token")
96
+ print(" - The Space will automatically have access to this secret")
97
+ return False
98
+
99
+ try:
100
+ # Login with the token
101
+ login(token=token)
102
+
103
+ # Test authentication
104
+ self.api = HfApi()
105
+ user_info = whoami()
106
+
107
+ self.username = user_info["name"]
108
+ self.is_authenticated = True
109
+
110
+ print(f"βœ… Space authentication successful!")
111
+ print(f" - Username: {self.username}")
112
+ print(f" - Token: {token[:8]}...{token[-4:]}")
113
+ print(f" - Source: GitHub secrets")
114
+
115
+ # Store Space configuration
116
+ self.space_config = {
117
+ "is_space": True,
118
+ "username": self.username,
119
+ "space_id": os.getenv("SPACE_ID"),
120
+ "space_host": os.getenv("SPACE_HOST"),
121
+ "space_repo_id": os.getenv("SPACE_REPO_ID"),
122
+ "auth_source": "github_secrets"
123
+ }
124
+
125
+ return True
126
+
127
+ except Exception as e:
128
+ print(f"❌ Space authentication failed: {e}")
129
+ return False
130
+
131
+ def _setup_local_auth(self) -> bool:
132
+ """Set up authentication in local environment."""
133
+ print("\nπŸ” Setting up Local Environment Authentication")
134
+ print("-" * 45)
135
+
136
+ try:
137
+ # Try to get current user info first
138
+ user_info = whoami()
139
+ self.username = user_info["name"]
140
+ self.api = HfApi()
141
+ self.is_authenticated = True
142
+
143
+ print(f"βœ… Already authenticated as: {self.username}")
144
+ return True
145
+
146
+ except Exception as e:
147
+ print(f"❌ Not authenticated: {e}")
148
+ print("πŸ”„ Attempting to authenticate...")
149
+
150
+ # Try environment variable
151
+ token = os.getenv("HUGGING_FACE_HUB_TOKEN") or os.getenv("HF_TOKEN")
152
+ if token:
153
+ try:
154
+ login(token=token)
155
+ user_info = whoami()
156
+ self.username = user_info["name"]
157
+ self.api = HfApi()
158
+ self.is_authenticated = True
159
+
160
+ print(f"βœ… Authenticated with token as: {self.username}")
161
+ return True
162
+
163
+ except Exception as token_error:
164
+ print(f"❌ Token authentication failed: {token_error}")
165
+
166
+ print("❌ Authentication failed")
167
+ return False
168
+
169
+ def test_repository_creation(self) -> bool:
170
+ """
171
+ Test repository creation capabilities.
172
+
173
+ Returns:
174
+ True if successful, False otherwise
175
+ """
176
+ if not self.is_authenticated:
177
+ print("❌ Not authenticated")
178
+ return False
179
+
180
+ print(f"\nπŸ§ͺ Testing Repository Creation")
181
+ print("-" * 35)
182
+
183
+ try:
184
+ # Create test repository
185
+ repo_name = "test-openllm-space-auth"
186
+ repo_id = f"{self.username}/{repo_name}"
187
+
188
+ print(f"πŸ”„ Creating test repository: {repo_id}")
189
+ create_repo(
190
+ repo_id=repo_id,
191
+ repo_type="model",
192
+ exist_ok=True,
193
+ private=True
194
+ )
195
+
196
+ print(f"βœ… Test repository created successfully")
197
+
198
+ # Clean up - delete the test repository
199
+ from huggingface_hub import delete_repo
200
+ print(f"πŸ”„ Cleaning up test repository...")
201
+ delete_repo(repo_id=repo_id, repo_type="model")
202
+ print(f"βœ… Test repository deleted")
203
+
204
+ return True
205
+
206
+ except Exception as e:
207
+ print(f"❌ Repository creation test failed: {e}")
208
+ return False
209
+
210
+ def test_model_upload(self) -> bool:
211
+ """
212
+ Test model upload capabilities.
213
+
214
+ Returns:
215
+ True if successful, False otherwise
216
+ """
217
+ if not self.is_authenticated:
218
+ print("❌ Not authenticated")
219
+ return False
220
+
221
+ print(f"\nπŸ“€ Testing Model Upload")
222
+ print("-" * 25)
223
+
224
+ try:
225
+ # Create test file
226
+ test_file = "test_upload.txt"
227
+ with open(test_file, "w") as f:
228
+ f.write("This is a test file for Hugging Face Space upload verification.\n")
229
+ f.write("Generated by setup_hf_space_auth.py (GitHub Secrets)\n")
230
+
231
+ # Create test repository
232
+ repo_name = "test-upload-openllm-space"
233
+ repo_id = f"{self.username}/{repo_name}"
234
+
235
+ from huggingface_hub import create_repo, delete_repo
236
+
237
+ create_repo(
238
+ repo_id=repo_id,
239
+ repo_type="model",
240
+ exist_ok=True,
241
+ private=True
242
+ )
243
+
244
+ # Upload test file
245
+ print(f"πŸ”„ Uploading test file to {repo_id}...")
246
+ self.api.upload_file(
247
+ path_or_fileobj=test_file,
248
+ path_in_repo="test_file.txt",
249
+ repo_id=repo_id,
250
+ repo_type="model",
251
+ commit_message="Test upload from OpenLLM Space auth setup (GitHub Secrets)"
252
+ )
253
+
254
+ print(f"βœ… Test upload successful!")
255
+
256
+ # Clean up
257
+ print(f"πŸ”„ Cleaning up...")
258
+ delete_repo(repo_id=repo_id, repo_type="model")
259
+ os.remove(test_file)
260
+ print(f"βœ… Cleanup completed")
261
+
262
+ return True
263
+
264
+ except Exception as e:
265
+ print(f"❌ Upload test failed: {e}")
266
+ # Clean up test file if it exists
267
+ if os.path.exists("test_upload.txt"):
268
+ os.remove("test_upload.txt")
269
+ return False
270
+
271
+ def create_space_config(self) -> bool:
272
+ """
273
+ Create configuration file for Hugging Face Space.
274
+
275
+ Returns:
276
+ True if successful, False otherwise
277
+ """
278
+ if not self.is_authenticated:
279
+ print("❌ Not authenticated")
280
+ return False
281
+
282
+ print(f"\nπŸ“ Creating Space Configuration")
283
+ print("-" * 30)
284
+
285
+ config = {
286
+ "authentication": {
287
+ "username": self.username,
288
+ "authenticated": self.is_authenticated,
289
+ "method": "github_secrets" if self.space_config.get("auth_source") == "github_secrets" else "local_token"
290
+ },
291
+ "space_config": self.space_config,
292
+ "model_upload": {
293
+ "default_repo_prefix": f"{self.username}/openllm",
294
+ "supported_sizes": ["small", "medium", "large"],
295
+ "upload_enabled": True
296
+ },
297
+ "training": {
298
+ "checkpoint_upload": True,
299
+ "final_model_upload": True,
300
+ "create_model_card": True
301
+ }
302
+ }
303
+
304
+ # Save configuration
305
+ config_path = ".hf_space_config.json"
306
+ with open(config_path, "w") as f:
307
+ json.dump(config, f, indent=2)
308
+
309
+ print(f"βœ… Space configuration saved to: {config_path}")
310
+ return True
311
+
312
+ def generate_space_instructions(self) -> str:
313
+ """Generate instructions for setting up Hugging Face Space with GitHub secrets."""
314
+ instructions = f"""
315
+ 🎯 Hugging Face Space Setup Instructions (GitHub Secrets)
316
+
317
+ 1. **Set up GitHub Repository Secrets:**
318
+ - Go to your GitHub repository: https://github.com/your-username/your-repo
319
+ - Click on "Settings" tab
320
+ - Click on "Secrets and variables" β†’ "Actions"
321
+ - Click "New repository secret"
322
+ - Add a new secret:
323
+ - Name: HF_TOKEN
324
+ - Value: Your Hugging Face token (get from https://huggingface.co/settings/tokens)
325
+
326
+ 2. **Verify Authentication:**
327
+ - Run this script in your Space to verify authentication works
328
+ - The script will test repository creation and upload capabilities
329
+ - GitHub secrets are automatically available in Hugging Face Spaces
330
+
331
+ 3. **Training Configuration:**
332
+ - Your training script should use the authentication setup
333
+ - Model uploads will go to: https://huggingface.co/{self.username}/openllm-*
334
+ - Checkpoints will be saved during training
335
+
336
+ 4. **Expected Results:**
337
+ - Training will complete successfully
338
+ - Model will be uploaded to Hugging Face Hub
339
+ - Repository will be created with proper model files
340
+ - Model card and configuration will be generated
341
+
342
+ 5. **Troubleshooting:**
343
+ - If upload fails, check HF_TOKEN is set correctly in GitHub secrets
344
+ - Verify token has "Write" permissions
345
+ - Check Space logs for detailed error messages
346
+ - Ensure your Space is connected to the GitHub repository
347
+ """
348
+ return instructions
349
+
350
+
351
+ def main():
352
+ """Main function to run the Space authentication setup."""
353
+ print("πŸš€ OpenLLM - Hugging Face Space Authentication Setup (GitHub Secrets)")
354
+ print("=" * 70)
355
+
356
+ # Initialize setup
357
+ auth_setup = HuggingFaceSpaceAuthSetup()
358
+
359
+ # Set up authentication
360
+ if not auth_setup.setup_space_authentication():
361
+ print("\n❌ Authentication setup failed")
362
+ print("\nπŸ”§ Troubleshooting:")
363
+ print("1. Get a Hugging Face token from https://huggingface.co/settings/tokens")
364
+ print("2. In GitHub: Set HF_TOKEN in Repository secrets (Settings β†’ Secrets and variables β†’ Actions)")
365
+ print("3. Locally: Set HUGGING_FACE_HUB_TOKEN environment variable")
366
+ sys.exit(1)
367
+
368
+ print(f"\nβœ… Authentication successful!")
369
+ print(f" - Username: {auth_setup.username}")
370
+
371
+ # Test repository creation
372
+ repo_success = auth_setup.test_repository_creation()
373
+
374
+ # Test model upload
375
+ upload_success = auth_setup.test_model_upload()
376
+
377
+ # Create configuration
378
+ config_success = auth_setup.create_space_config()
379
+
380
+ # Summary
381
+ print(f"\nπŸ“Š Setup Results")
382
+ print("-" * 20)
383
+ print(f"βœ… Authentication: PASSED")
384
+ print(f"{'βœ…' if repo_success else '❌'} Repository Creation: {'PASSED' if repo_success else 'FAILED'}")
385
+ print(f"{'βœ…' if upload_success else '❌'} Model Upload: {'PASSED' if upload_success else 'FAILED'}")
386
+ print(f"{'βœ…' if config_success else '❌'} Configuration: {'PASSED' if config_success else 'FAILED'}")
387
+
388
+ if repo_success and upload_success:
389
+ print(f"\nπŸŽ‰ Space authentication setup completed successfully!")
390
+ print(f" - You can now run training in Hugging Face Spaces")
391
+ print(f" - Model uploads will work correctly")
392
+ print(f" - Your models will be uploaded to: https://huggingface.co/{auth_setup.username}")
393
+
394
+ # Show Space instructions
395
+ print(auth_setup.generate_space_instructions())
396
+ else:
397
+ print(f"\n⚠️ Some tests failed. Check the error messages above.")
398
+ sys.exit(1)
399
+
400
+ return True
401
+
402
+
403
+ if __name__ == "__main__":
404
+ main()