Spaces:
Running
Running
File size: 6,567 Bytes
c417358 40fd629 c417358 40fd629 c417358 |
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 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
# Username Extraction Fix
This document outlines the fix for the "Invalid user token" error that occurred during Trackio Space deployment.
## π **Problem Description**
The error occurred in the `deploy_trackio_space.py` script when trying to extract the username from the HF token:
```
β Failed to get user info from token: Invalid user token.
```
This happened because:
1. The `whoami()` API method was being called incorrectly
2. The response format wasn't handled properly
3. No fallback mechanism was in place
## β
**Solution Implemented**
### **1. Improved Username Extraction Function**
Created a robust username extraction function that handles multiple scenarios:
```python
def get_username_from_token(token: str) -> str:
"""Get username from HF token with fallback to CLI"""
try:
# Try API first
api = HfApi(token=token)
user_info = api.whoami()
# Handle different possible response formats
if isinstance(user_info, dict):
# Try different possible keys for username
username = (
user_info.get('name') or
user_info.get('username') or
user_info.get('user') or
None
)
elif isinstance(user_info, str):
# If whoami returns just the username as string
username = user_info
else:
username = None
if username:
print(f"β
Got username from API: {username}")
return username
else:
print("β οΈ Could not get username from API, trying CLI...")
return get_username_from_cli(token)
except Exception as e:
print(f"β οΈ API whoami failed: {e}")
print("β οΈ Trying CLI fallback...")
return get_username_from_cli(token)
```
### **2. CLI Fallback Method**
Added a robust CLI fallback method:
```python
def get_username_from_cli(token: str) -> str:
"""Fallback method to get username using CLI"""
try:
# Set HF token for CLI
os.environ['HF_TOKEN'] = token
# Get username using CLI
result = subprocess.run(
["hf", "whoami"],
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
username = result.stdout.strip()
if username:
print(f"β
Got username from CLI: {username}")
return username
else:
print("β οΈ CLI returned empty username")
return None
else:
print(f"β οΈ CLI whoami failed: {result.stderr}")
return None
except Exception as e:
print(f"β οΈ CLI fallback failed: {e}")
return None
```
## π§ **Files Updated**
### **1. `scripts/trackio_tonic/deploy_trackio_space.py`**
- β
Added `_get_username_from_cli()` method
- β
Updated `__init__()` to use improved username extraction
- β
Better error handling and fallback mechanisms
- β
Handles different response formats from `whoami()`
### **2. `scripts/dataset_tonic/setup_hf_dataset.py`**
- β
Added `get_username_from_token()` and `get_username_from_cli()` functions
- β
Updated main function to use improved username extraction
- β
Better error handling and user feedback
### **3. `scripts/trackio_tonic/configure_trackio.py`**
- β
Added same username extraction functions
- β
Updated configuration function to use improved method
- β
Consistent error handling across all scripts
## π― **Key Improvements**
### **β
Robust Error Handling**
- API method fails β CLI fallback
- CLI fails β Clear error message
- Multiple response format handling
### **β
Better User Feedback**
- Clear status messages for each step
- Indicates which method is being used (API vs CLI)
- Helpful error messages with suggestions
### **β
Multiple Response Format Support**
- Handles dictionary responses with different key names
- Handles string responses
- Handles unexpected response formats
### **β
Timeout Protection**
- 30-second timeout for CLI operations
- Prevents hanging on network issues
## π **Response Format Handling**
The fix handles different possible response formats from the `whoami()` API:
### **Dictionary Response:**
```python
{
"name": "username",
"username": "username",
"user": "username"
}
```
### **String Response:**
```python
"username"
```
### **Unknown Format:**
- Falls back to CLI method
- Provides clear error messages
## π§ͺ **Testing Results**
All tests pass with the updated scripts:
```
π Test Results Summary
========================================
β
PASS: Import Tests
β
PASS: Script Existence
β
PASS: Script Syntax
β
PASS: Environment Variables
β
PASS: API Connection
β
PASS: Script Functions
β
PASS: Template Files
π― Overall: 7/7 tests passed
π All tests passed! The fixes are working correctly.
```
## π **Usage**
The fix is transparent to users. The workflow remains the same:
```bash
# 1. Set HF token
export HF_TOKEN=your_token_here
# 2. Run deployment (username auto-detected)
python scripts/trackio_tonic/deploy_trackio_space.py
# 3. Or use the launch script
bash launch.sh
```
## π **Benefits**
1. **β
Reliable Username Detection**: Works with different API response formats
2. **β
Robust Fallback**: CLI method as backup when API fails
3. **β
Better Error Messages**: Clear feedback about what's happening
4. **β
Consistent Behavior**: Same method across all scripts
5. **β
No User Impact**: Transparent to end users
6. **β
Future-Proof**: Handles different API response formats
## π§ **Troubleshooting**
If username extraction still fails:
1. **Check Token**: Ensure HF_TOKEN is valid and has proper permissions
2. **Check Network**: Ensure internet connection is stable
3. **Check CLI**: Ensure `hf` is installed and working
4. **Manual Override**: Can manually set username in scripts if needed
## π **Summary**
The username extraction fix resolves the "Invalid user token" error by:
- β
Implementing robust API response handling
- β
Adding CLI fallback mechanism
- β
Providing better error messages
- β
Ensuring consistent behavior across all scripts
- β
Maintaining backward compatibility
The fix ensures that username extraction works reliably across different environments and API response formats, providing a smooth user experience for the Trackio deployment pipeline. |