File size: 2,505 Bytes
1b5e165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import platform
import logging
from pathlib import Path
from huggingface_hub import login
from utils.logging_utils import setup_logging

# Configure logger
logger = setup_logging(logger_name="HuggingFaceAuth", log_filename="auth_utils.log")

def authenticate_huggingface():
    """
    Authenticate with Hugging Face API based on environment and platform.
    Returns: tuple (API key, headers dict for API requests) or (None, None) if failed
    """
    try:
        # Check if running in Docker
        in_docker = os.path.exists('/.dockerenv')
        
        # Try environment variables first
        env_api_key = os.environ.get("HF_API_KEY") or os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
        
        if env_api_key:
            logger.info("Using Hugging Face API key from environment variable")
            try:
                login(token=env_api_key)
                logger.info("Successfully authenticated with Hugging Face Hub")
            except Exception as e:
                logger.error(f"Failed to authenticate with environment variable: {e}")
                return None, None
                
            return env_api_key, {"Authorization": f"Bearer {env_api_key}", "Content-Type": "application/json"}
        
        # If not in Docker and on macOS, try keyring
        if not in_docker and platform.system() == 'Darwin':
            logger.info("Trying keyring authentication on macOS")
            try:
                import keyring
                hf_api_key = keyring.get_password("HF_API_KEY", "rressler")
                if hf_api_key:
                    logger.info("Found API key in keyring")
                    try:
                        login(token=hf_api_key)
                        logger.info("Successfully authenticated with Hugging Face Hub using keyring")
                    except Exception as e:
                        logger.error(f"Failed to authenticate with keyring: {e}")
                        return None, None
                        
                    return hf_api_key, {"Authorization": f"Bearer {hf_api_key}", "Content-Type": "application/json"}
            except Exception as e:
                logger.warning(f"Error accessing keyring: {e}")
        
        # If we got here, authentication failed
        logger.warning("No valid Hugging Face API key found")
        return None, None
        
    except Exception as e:
        logger.error(f"Authentication error: {e}")
        return None, None