Spaces:
Sleeping
Sleeping
import os | |
from dotenv import load_dotenv | |
from huggingface_hub import HfApi | |
from pathlib import Path | |
class TokenHandler: | |
def __init__(self): | |
# Load environment variables from .env file if it exists | |
self.load_environment() | |
self.token = self._get_token() | |
self.api = HfApi() | |
def load_environment(self): | |
"""Load environment variables from .env file""" | |
env_path = Path('.env') | |
if env_path.exists(): | |
load_dotenv(env_path) | |
def _get_token(self) -> str: | |
"""Get HuggingFace token from environment variables""" | |
token = os.getenv("HF_TOKEN") | |
if not token: | |
raise EnvironmentError( | |
"HF_TOKEN not found in environment variables. " | |
"Please set it up using one of these methods:\n" | |
"1. Create a .env file with HF_TOKEN=your_token\n" | |
"2. Set environment variable HF_TOKEN=your_token\n" | |
"3. Add HF_TOKEN to your HuggingFace Space secrets" | |
) | |
return token | |
def verify_token(self) -> bool: | |
"""Verify if the token is valid by making a test API call""" | |
try: | |
# Try to get user information using the token | |
self.api.whoami(token=self.token) | |
return True | |
except Exception as e: | |
print(f"Token verification failed: {e}") | |
return False | |
def get_verified_token(self) -> str: | |
"""Get token and verify it's working""" | |
if not self.verify_token(): | |
raise ValueError( | |
"Invalid or expired HuggingFace token. " | |
"Please check your token at https://huggingface.co/settings/tokens" | |
) | |
return self.token | |
# Usage example | |
def initialize_hf_token(): | |
"""Initialize and verify HuggingFace token""" | |
try: | |
handler = TokenHandler() | |
token = handler.get_verified_token() | |
print("β HuggingFace token successfully verified") | |
return token | |
except Exception as e: | |
print(f"β Error initializing HuggingFace token: {e}") | |
return None | |
# Example of how to use in your main code | |
if __name__ == "__main__": | |
# Create .env file if it doesn't exist | |
if not Path('.env').exists(): | |
print("Creating .env file template...") | |
with open('.env', 'w') as f: | |
f.write("HF_TOKEN=your_token_here\n") | |
print("Please edit .env file and add your HuggingFace token") | |
# Initialize token | |
token = initialize_hf_token() | |
if token: | |
print("Ready to use HuggingFace API") |