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