File size: 2,593 Bytes
a77a138
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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")