chaaim123 commited on
Commit
bb09f1a
·
verified ·
1 Parent(s): 6e9148c

Create utils/auth_utils.py

Browse files
Files changed (1) hide show
  1. utils/auth_utils.py +59 -0
utils/auth_utils.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import platform
3
+ import logging
4
+ from pathlib import Path
5
+ from huggingface_hub import login
6
+ from utils.logging_utils import setup_logging
7
+
8
+ # Configure logger
9
+ logger = setup_logging(logger_name="HuggingFaceAuth", log_filename="auth_utils.log")
10
+
11
+ def authenticate_huggingface():
12
+ """
13
+ Authenticate with Hugging Face API based on environment and platform.
14
+ Returns: tuple (API key, headers dict for API requests) or (None, None) if failed
15
+ """
16
+ try:
17
+ # Check if running in Docker
18
+ in_docker = os.path.exists('/.dockerenv')
19
+
20
+ # Try environment variables first
21
+ env_api_key = os.environ.get("HF_API_KEY") or os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_TOKEN")
22
+
23
+ if env_api_key:
24
+ logger.info("Using Hugging Face API key from environment variable")
25
+ try:
26
+ login(token=env_api_key)
27
+ logger.info("Successfully authenticated with Hugging Face Hub")
28
+ except Exception as e:
29
+ logger.error(f"Failed to authenticate with environment variable: {e}")
30
+ return None, None
31
+
32
+ return env_api_key, {"Authorization": f"Bearer {env_api_key}", "Content-Type": "application/json"}
33
+
34
+ # If not in Docker and on macOS, try keyring
35
+ if not in_docker and platform.system() == 'Darwin':
36
+ logger.info("Trying keyring authentication on macOS")
37
+ try:
38
+ import keyring
39
+ hf_api_key = keyring.get_password("HF_API_KEY", "rressler")
40
+ if hf_api_key:
41
+ logger.info("Found API key in keyring")
42
+ try:
43
+ login(token=hf_api_key)
44
+ logger.info("Successfully authenticated with Hugging Face Hub using keyring")
45
+ except Exception as e:
46
+ logger.error(f"Failed to authenticate with keyring: {e}")
47
+ return None, None
48
+
49
+ return hf_api_key, {"Authorization": f"Bearer {hf_api_key}", "Content-Type": "application/json"}
50
+ except Exception as e:
51
+ logger.warning(f"Error accessing keyring: {e}")
52
+
53
+ # If we got here, authentication failed
54
+ logger.warning("No valid Hugging Face API key found")
55
+ return None, None
56
+
57
+ except Exception as e:
58
+ logger.error(f"Authentication error: {e}")
59
+ return None, None