Spaces:
Running
Running
Refactor app.py and settings.py: Enhance Hugging Face token handling with improved validation and logging
Browse files- app.py +9 -0
- config/settings.py +9 -27
app.py
CHANGED
@@ -160,6 +160,15 @@ logger = logging.getLogger(__name__)
|
|
160 |
if not HF_TOKEN:
|
161 |
raise ValueError("HUGGINGFACE_TOKEN not found in environment variables")
|
162 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
# Global variables
|
164 |
client = None
|
165 |
context_store = {}
|
|
|
160 |
if not HF_TOKEN:
|
161 |
raise ValueError("HUGGINGFACE_TOKEN not found in environment variables")
|
162 |
|
163 |
+
# Test API connection
|
164 |
+
api = HfApi(token=HF_TOKEN)
|
165 |
+
try:
|
166 |
+
api.whoami()
|
167 |
+
logger.info("Successfully authenticated with Hugging Face")
|
168 |
+
except Exception as e:
|
169 |
+
logger.error(f"Authentication failed: {e}")
|
170 |
+
raise
|
171 |
+
|
172 |
# Global variables
|
173 |
client = None
|
174 |
context_store = {}
|
config/settings.py
CHANGED
@@ -9,36 +9,18 @@ logging.basicConfig(level=logging.INFO)
|
|
9 |
logger = logging.getLogger(__name__)
|
10 |
|
11 |
# Load environment variables
|
12 |
-
|
13 |
-
load_dotenv(env_path)
|
14 |
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
"HUGGINGFACE_TOKEN"
|
19 |
-
"HF_TOKEN",
|
20 |
-
"HF_API_TOKEN"
|
21 |
-
]
|
22 |
|
23 |
-
|
24 |
-
|
25 |
-
token
|
26 |
-
if token:
|
27 |
-
HF_TOKEN = token
|
28 |
-
logger.info(f"Using token from {token_var}")
|
29 |
-
break
|
30 |
|
31 |
-
|
32 |
-
error_msg = (
|
33 |
-
"No valid API token found. Please set one of the following environment variables:\n"
|
34 |
-
"- pro_api_token_2\n"
|
35 |
-
"- HUGGINGFACE_TOKEN\n"
|
36 |
-
"- HF_TOKEN\n"
|
37 |
-
"- HF_API_TOKEN\n"
|
38 |
-
"You can set it in your .env file or as a system environment variable."
|
39 |
-
)
|
40 |
-
logger.error(error_msg)
|
41 |
-
raise ValueError(error_msg)
|
42 |
|
43 |
# API Configuration
|
44 |
API_CONFIG = {
|
|
|
9 |
logger = logging.getLogger(__name__)
|
10 |
|
11 |
# Load environment variables
|
12 |
+
load_dotenv()
|
|
|
13 |
|
14 |
+
# Get token with fallback
|
15 |
+
HF_TOKEN = os.getenv('HUGGINGFACE_TOKEN')
|
16 |
+
if not HF_TOKEN:
|
17 |
+
raise ValueError("HUGGINGFACE_TOKEN not found in environment variables")
|
|
|
|
|
|
|
18 |
|
19 |
+
# Validate token format
|
20 |
+
if not HF_TOKEN.startswith('hf_'):
|
21 |
+
raise ValueError("Invalid Hugging Face token format")
|
|
|
|
|
|
|
|
|
22 |
|
23 |
+
print(f"Token loaded successfully: {HF_TOKEN[:5]}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
# API Configuration
|
26 |
API_CONFIG = {
|