Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
update token test
Browse files- .env.example +4 -3
- backend/main.py +12 -0
- backend/tasks/get_available_model_provider.py +104 -14
- backend/tests/check_hf_token.py +283 -0
.env.example
CHANGED
@@ -1,3 +1,4 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
1 |
+
ENVIRONEMENT=development
|
2 |
+
HF_ORGANIZATION=yourbench
|
3 |
+
HF_TOKEN=hf_xxx
|
4 |
+
OPENAI_API_KEY=sk-proj-xxxx
|
backend/main.py
CHANGED
@@ -44,14 +44,21 @@ async def startup_event():
|
|
44 |
hf_token = os.environ.get("HF_TOKEN")
|
45 |
if hf_token:
|
46 |
print("✅ HF_TOKEN AVAILABLE")
|
|
|
|
|
|
|
|
|
|
|
47 |
else:
|
48 |
print("❌ HF_TOKEN MISSING - HuggingFace models will not work correctly")
|
|
|
49 |
|
50 |
hf_organization = os.environ.get("HF_ORGANIZATION")
|
51 |
if hf_organization:
|
52 |
print(f"✅ HF_ORGANIZATION: {hf_organization}")
|
53 |
else:
|
54 |
print("❌ HF_ORGANIZATION MISSING")
|
|
|
55 |
|
56 |
print("\n===== Additional Environment Variables =====")
|
57 |
# Afficher d'autres variables utiles
|
@@ -69,6 +76,11 @@ async def startup_event():
|
|
69 |
print(f"✅ Found working model: {test_results['working_model']} with provider: {test_results['provider']}")
|
70 |
else:
|
71 |
print("❌ WARNING: No working models found. The application might not function correctly!")
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
# Enregistrer toutes les routes
|
74 |
for router in routers:
|
|
|
44 |
hf_token = os.environ.get("HF_TOKEN")
|
45 |
if hf_token:
|
46 |
print("✅ HF_TOKEN AVAILABLE")
|
47 |
+
|
48 |
+
# Basic format validation
|
49 |
+
if not hf_token.startswith("hf_"):
|
50 |
+
print("⚠️ WARNING: Your HF_TOKEN does not start with 'hf_' which is unusual.")
|
51 |
+
print(" Please verify its format and source.")
|
52 |
else:
|
53 |
print("❌ HF_TOKEN MISSING - HuggingFace models will not work correctly")
|
54 |
+
print(" Please set this environment variable for proper functionality.")
|
55 |
|
56 |
hf_organization = os.environ.get("HF_ORGANIZATION")
|
57 |
if hf_organization:
|
58 |
print(f"✅ HF_ORGANIZATION: {hf_organization}")
|
59 |
else:
|
60 |
print("❌ HF_ORGANIZATION MISSING")
|
61 |
+
print(" This may affect billing and access to certain models.")
|
62 |
|
63 |
print("\n===== Additional Environment Variables =====")
|
64 |
# Afficher d'autres variables utiles
|
|
|
76 |
print(f"✅ Found working model: {test_results['working_model']} with provider: {test_results['provider']}")
|
77 |
else:
|
78 |
print("❌ WARNING: No working models found. The application might not function correctly!")
|
79 |
+
print("\nPossible solutions:")
|
80 |
+
print("1. Check your HF_TOKEN is valid and has appropriate permissions")
|
81 |
+
print("2. Verify your internet connection")
|
82 |
+
print("3. Try again later as the API service might be temporarily unavailable")
|
83 |
+
print("4. Configure alternative models in config/models_config.py")
|
84 |
|
85 |
# Enregistrer toutes les routes
|
86 |
for router in routers:
|
backend/tasks/get_available_model_provider.py
CHANGED
@@ -36,7 +36,8 @@ def test_provider(model_name: str, provider: str, verbose: bool = False) -> bool
|
|
36 |
hf_token = os.environ.get("HF_TOKEN")
|
37 |
if not hf_token:
|
38 |
if verbose:
|
39 |
-
logger.warning("HF_TOKEN
|
|
|
40 |
# Essayer sans token (pour certains providers qui acceptent des requêtes anonymes)
|
41 |
return _test_provider_without_token(model_name, provider, verbose)
|
42 |
|
@@ -79,7 +80,8 @@ def test_provider(model_name: str, provider: str, verbose: bool = False) -> bool
|
|
79 |
if "status_code=429" in error_message:
|
80 |
logger.warning(f"Provider {provider} rate limited. You may need to wait or upgrade your plan.")
|
81 |
elif "status_code=401" in error_message or "status_code=403" in error_message:
|
82 |
-
logger.warning(f"Authentication failed for provider {provider}.
|
|
|
83 |
# Essayer sans token
|
84 |
if verbose:
|
85 |
logger.info(f"Trying provider {provider} without authentication")
|
@@ -93,7 +95,8 @@ def test_provider(model_name: str, provider: str, verbose: bool = False) -> bool
|
|
93 |
if "401" in str(auth_error) or "Unauthorized" in str(auth_error):
|
94 |
# En cas d'erreur d'authentification, essayer sans token
|
95 |
if verbose:
|
96 |
-
logger.warning(f"Authentication error with {provider}: {str(auth_error)}.
|
|
|
97 |
return _test_provider_without_token(model_name, provider, verbose)
|
98 |
else:
|
99 |
if verbose:
|
@@ -320,22 +323,99 @@ def test_models(verbose=True):
|
|
320 |
"unavailable_models": []
|
321 |
}
|
322 |
|
|
|
323 |
# Obtenez le jeton HF
|
324 |
hf_token = os.environ.get("HF_TOKEN")
|
325 |
if hf_token:
|
326 |
-
print("HF_TOKEN is available")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
327 |
else:
|
328 |
-
print("HF_TOKEN is missing")
|
|
|
329 |
|
330 |
# Obtenez l'organisation HF
|
331 |
hf_organization = os.environ.get("HF_ORGANIZATION")
|
332 |
if hf_organization:
|
333 |
-
print(f"HF_ORGANIZATION is available: {hf_organization}")
|
334 |
else:
|
335 |
-
print("HF_ORGANIZATION is
|
336 |
|
337 |
if verbose:
|
338 |
-
print(f"Testing main default model: {DEFAULT_BENCHMARK_MODEL}")
|
339 |
|
340 |
# Test du modèle par défaut
|
341 |
provider = get_available_model_provider(DEFAULT_BENCHMARK_MODEL, verbose=verbose)
|
@@ -367,6 +447,8 @@ def test_models(verbose=True):
|
|
367 |
else:
|
368 |
if verbose:
|
369 |
print("\n❌ ALL MODELS FAILED: No provider found for any model")
|
|
|
|
|
370 |
|
371 |
# Tester tous les modèles pour avoir une vue d'ensemble
|
372 |
models = [
|
@@ -380,7 +462,7 @@ def test_models(verbose=True):
|
|
380 |
]
|
381 |
|
382 |
if verbose:
|
383 |
-
print("\n
|
384 |
|
385 |
for model in models:
|
386 |
provider = get_available_model_provider(model, verbose)
|
@@ -391,14 +473,22 @@ def test_models(verbose=True):
|
|
391 |
results["unavailable_models"].append(model)
|
392 |
|
393 |
if verbose:
|
394 |
-
print("\n
|
395 |
-
|
396 |
-
print(
|
|
|
|
|
|
|
|
|
|
|
397 |
|
398 |
if results["unavailable_models"]:
|
399 |
-
print(
|
|
|
|
|
400 |
|
401 |
-
print(f"
|
|
|
402 |
|
403 |
return results
|
404 |
|
|
|
36 |
hf_token = os.environ.get("HF_TOKEN")
|
37 |
if not hf_token:
|
38 |
if verbose:
|
39 |
+
logger.warning("No HF_TOKEN found in environment variables. This will likely cause authentication failures.")
|
40 |
+
print("WARNING: HF_TOKEN is missing. Most model providers require valid authentication.")
|
41 |
# Essayer sans token (pour certains providers qui acceptent des requêtes anonymes)
|
42 |
return _test_provider_without_token(model_name, provider, verbose)
|
43 |
|
|
|
80 |
if "status_code=429" in error_message:
|
81 |
logger.warning(f"Provider {provider} rate limited. You may need to wait or upgrade your plan.")
|
82 |
elif "status_code=401" in error_message or "status_code=403" in error_message:
|
83 |
+
logger.warning(f"Authentication failed for provider {provider}. Your HF_TOKEN may be invalid or expired.")
|
84 |
+
print(f"Authentication error with provider {provider}. Please check your HF_TOKEN.")
|
85 |
# Essayer sans token
|
86 |
if verbose:
|
87 |
logger.info(f"Trying provider {provider} without authentication")
|
|
|
95 |
if "401" in str(auth_error) or "Unauthorized" in str(auth_error):
|
96 |
# En cas d'erreur d'authentification, essayer sans token
|
97 |
if verbose:
|
98 |
+
logger.warning(f"Authentication error with {provider}: {str(auth_error)}. Your HF_TOKEN may be invalid.")
|
99 |
+
print(f"Authentication error detected. Please verify your HF_TOKEN is valid and has appropriate permissions.")
|
100 |
return _test_provider_without_token(model_name, provider, verbose)
|
101 |
else:
|
102 |
if verbose:
|
|
|
323 |
"unavailable_models": []
|
324 |
}
|
325 |
|
326 |
+
print("\n===== Checking HuggingFace Authentication =====")
|
327 |
# Obtenez le jeton HF
|
328 |
hf_token = os.environ.get("HF_TOKEN")
|
329 |
if hf_token:
|
330 |
+
print("✅ HF_TOKEN is available")
|
331 |
+
|
332 |
+
# Vérifier si le token a un format valide (vérification simple)
|
333 |
+
if not hf_token.startswith("hf_"):
|
334 |
+
print("⚠️ WARNING: Your HF_TOKEN does not start with 'hf_' which is unusual. Please verify its format.")
|
335 |
+
|
336 |
+
# Masquer partiellement le token pour l'affichage
|
337 |
+
visible_chars = 4
|
338 |
+
masked_token = hf_token[:visible_chars] + "*" * (len(hf_token) - visible_chars * 2) + hf_token[-visible_chars:]
|
339 |
+
|
340 |
+
# Vérifier la validité du token en testant directement l'API d'inférence
|
341 |
+
import requests
|
342 |
+
try:
|
343 |
+
# Test avec un modèle public simple (gpt2)
|
344 |
+
test_model = "gpt2"
|
345 |
+
api_url = f"https://api-inference.huggingface.co/models/{test_model}"
|
346 |
+
|
347 |
+
print(f"Testing token {masked_token} with inference API on public model {test_model}...")
|
348 |
+
|
349 |
+
headers = {"Authorization": f"Bearer {hf_token}"}
|
350 |
+
payload = {"inputs": "Hello, how are you?"}
|
351 |
+
|
352 |
+
response = requests.post(api_url, headers=headers, json=payload, timeout=10)
|
353 |
+
|
354 |
+
if response.status_code in [200, 503]: # 503 = modèle en cours de chargement, mais le token est accepté
|
355 |
+
print(f"✅ HF_TOKEN validated - Token accepted by the inference API! Status: {response.status_code}")
|
356 |
+
if response.status_code == 503:
|
357 |
+
print("ℹ️ Model is loading, but token is valid")
|
358 |
+
|
359 |
+
# Si le token est valide pour l'API d'inférence, vérifions également si nous pouvons obtenir
|
360 |
+
# des informations sur l'utilisateur (mais ce n'est pas bloquant si ça échoue)
|
361 |
+
try:
|
362 |
+
whoami_response = requests.get(
|
363 |
+
"https://huggingface.co/api/whoami",
|
364 |
+
headers={"Authorization": f"Bearer {hf_token}"}
|
365 |
+
)
|
366 |
+
|
367 |
+
if whoami_response.status_code == 200:
|
368 |
+
user_info = whoami_response.json()
|
369 |
+
print(f"✅ Additional info - Authenticated as: {user_info.get('name', 'Unknown user')}")
|
370 |
+
|
371 |
+
# Vérifier si l'utilisateur a accès à des modèles payants
|
372 |
+
if user_info.get('canPay', False):
|
373 |
+
print("✅ Your account has payment methods configured - you may have access to premium models")
|
374 |
+
else:
|
375 |
+
print("ℹ️ Your account does not have payment methods configured - access to premium models may be limited")
|
376 |
+
except Exception:
|
377 |
+
# Ignorer les erreurs lors de la récupération des infos utilisateur
|
378 |
+
pass
|
379 |
+
else:
|
380 |
+
print(f"❌ HF_TOKEN validation failed with status code: {response.status_code}")
|
381 |
+
error_message = "Unknown error"
|
382 |
+
try:
|
383 |
+
error_data = response.json()
|
384 |
+
if "error" in error_data:
|
385 |
+
error_message = error_data["error"]
|
386 |
+
print(f"❌ Error message: {error_message}")
|
387 |
+
except:
|
388 |
+
print(f"❌ Error message: {response.text}")
|
389 |
+
|
390 |
+
print("⚠️ Most model providers will not work with invalid credentials")
|
391 |
+
|
392 |
+
# Test alternatif avec l'endpoint status
|
393 |
+
try:
|
394 |
+
print("Attempting alternative validation with status endpoint...")
|
395 |
+
status_url = "https://api-inference.huggingface.co/status"
|
396 |
+
status_response = requests.get(status_url, headers=headers, timeout=10)
|
397 |
+
|
398 |
+
if status_response.status_code == 200:
|
399 |
+
print("✅ Token can access the status endpoint. This is partially good news.")
|
400 |
+
else:
|
401 |
+
print(f"❌ Status endpoint test also failed: {status_response.status_code}")
|
402 |
+
except Exception as e:
|
403 |
+
print(f"❌ Alternative validation also failed: {str(e)}")
|
404 |
+
except Exception as e:
|
405 |
+
print(f"❌ Error validating HF_TOKEN with inference API: {str(e)}")
|
406 |
else:
|
407 |
+
print("❌ HF_TOKEN is missing - authentication to HuggingFace API will fail")
|
408 |
+
print("⚠️ Most models and providers require authentication")
|
409 |
|
410 |
# Obtenez l'organisation HF
|
411 |
hf_organization = os.environ.get("HF_ORGANIZATION")
|
412 |
if hf_organization:
|
413 |
+
print(f"✅ HF_ORGANIZATION is available: {hf_organization}")
|
414 |
else:
|
415 |
+
print("ℹ️ HF_ORGANIZATION is not set")
|
416 |
|
417 |
if verbose:
|
418 |
+
print(f"\n===== Testing main default model: {DEFAULT_BENCHMARK_MODEL} =====")
|
419 |
|
420 |
# Test du modèle par défaut
|
421 |
provider = get_available_model_provider(DEFAULT_BENCHMARK_MODEL, verbose=verbose)
|
|
|
447 |
else:
|
448 |
if verbose:
|
449 |
print("\n❌ ALL MODELS FAILED: No provider found for any model")
|
450 |
+
print("\n⚠️ This is likely due to authentication issues with your HF_TOKEN")
|
451 |
+
print("⚠️ Please check your token or try using models that don't require authentication")
|
452 |
|
453 |
# Tester tous les modèles pour avoir une vue d'ensemble
|
454 |
models = [
|
|
|
462 |
]
|
463 |
|
464 |
if verbose:
|
465 |
+
print("\n===== Testing all available models =====")
|
466 |
|
467 |
for model in models:
|
468 |
provider = get_available_model_provider(model, verbose)
|
|
|
473 |
results["unavailable_models"].append(model)
|
474 |
|
475 |
if verbose:
|
476 |
+
print("\n===== Results Summary =====")
|
477 |
+
if results["available_models"]:
|
478 |
+
print("Models with available providers:")
|
479 |
+
for model, provider in results["available_models"]:
|
480 |
+
print(f"✅ Model: {model}, Provider: {provider}")
|
481 |
+
else:
|
482 |
+
print("❌ No models with available providers found")
|
483 |
+
print("⚠️ Please check your HF_TOKEN and permissions")
|
484 |
|
485 |
if results["unavailable_models"]:
|
486 |
+
print("\nModels with no available providers:")
|
487 |
+
for model in results["unavailable_models"]:
|
488 |
+
print(f"❌ {model}")
|
489 |
|
490 |
+
print(f"\nTotal Available Models: {len(results['available_models'])}")
|
491 |
+
print(f"Total Unavailable Models: {len(results['unavailable_models'])}")
|
492 |
|
493 |
return results
|
494 |
|
backend/tests/check_hf_token.py
ADDED
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
|
4 |
+
"""
|
5 |
+
Script standalone pour vérifier et afficher les propriétés d'un token Hugging Face.
|
6 |
+
Ce script peut être exécuté séparément pour diagnostiquer les problèmes d'authentification.
|
7 |
+
"""
|
8 |
+
|
9 |
+
import os
|
10 |
+
import sys
|
11 |
+
import json
|
12 |
+
import requests
|
13 |
+
from datetime import datetime
|
14 |
+
from dotenv import load_dotenv
|
15 |
+
from argparse import ArgumentParser
|
16 |
+
|
17 |
+
|
18 |
+
def color_text(text, color_code):
|
19 |
+
"""Format text with color for terminal output."""
|
20 |
+
return f"\033[{color_code}m{text}\033[0m"
|
21 |
+
|
22 |
+
|
23 |
+
def success(text):
|
24 |
+
"""Format text as success message (green)."""
|
25 |
+
return color_text(f"✅ {text}", "92")
|
26 |
+
|
27 |
+
|
28 |
+
def warning(text):
|
29 |
+
"""Format text as warning message (yellow)."""
|
30 |
+
return color_text(f"⚠️ {text}", "93")
|
31 |
+
|
32 |
+
|
33 |
+
def error(text):
|
34 |
+
"""Format text as error message (red)."""
|
35 |
+
return color_text(f"❌ {text}", "91")
|
36 |
+
|
37 |
+
|
38 |
+
def info(text):
|
39 |
+
"""Format text as info message (blue)."""
|
40 |
+
return color_text(f"ℹ️ {text}", "94")
|
41 |
+
|
42 |
+
|
43 |
+
def check_token_via_inference_api(token=None, verbose=True):
|
44 |
+
"""
|
45 |
+
Vérifie la validité d'un token HF en testant directement l'API d'inférence.
|
46 |
+
L'API whoami ne fonctionne pas toujours correctement pour les tokens mais l'API d'inférence
|
47 |
+
est la priorité dans notre application.
|
48 |
+
|
49 |
+
Args:
|
50 |
+
token: Le token à vérifier
|
51 |
+
verbose: Afficher des informations détaillées
|
52 |
+
|
53 |
+
Returns:
|
54 |
+
dict: Résultats de la vérification
|
55 |
+
"""
|
56 |
+
results = {
|
57 |
+
"is_valid": False,
|
58 |
+
"token": None,
|
59 |
+
"error_message": None,
|
60 |
+
"can_access_inference": False
|
61 |
+
}
|
62 |
+
|
63 |
+
# 1. Obtenir le token
|
64 |
+
if token is None:
|
65 |
+
token = os.environ.get("HF_TOKEN")
|
66 |
+
|
67 |
+
if not token:
|
68 |
+
print(error("Aucun token trouvé. Veuillez spécifier un token avec --token ou définir la variable d'environnement HF_TOKEN."))
|
69 |
+
results["error_message"] = "No token provided"
|
70 |
+
return results
|
71 |
+
|
72 |
+
# Masquer une partie du token pour l'affichage
|
73 |
+
visible_chars = 4
|
74 |
+
masked_token = token[:visible_chars] + "*" * (len(token) - visible_chars * 2) + token[-visible_chars:]
|
75 |
+
results["token"] = masked_token
|
76 |
+
|
77 |
+
print(info(f"Token à vérifier: {masked_token}"))
|
78 |
+
|
79 |
+
# 2. Vérifier le format basique
|
80 |
+
if not token.startswith("hf_"):
|
81 |
+
print(warning("Le token ne commence pas par 'hf_' ce qui est inhabituel. Vérifiez son format."))
|
82 |
+
else:
|
83 |
+
print(success("Format du token valide (commence par 'hf_')"))
|
84 |
+
|
85 |
+
# 3. Tester l'API d'inférence directement - méthode recommandée pour valider un token
|
86 |
+
try:
|
87 |
+
# Test avec un modèle public simple
|
88 |
+
test_model = "gpt2"
|
89 |
+
api_url = f"https://api-inference.huggingface.co/models/{test_model}"
|
90 |
+
|
91 |
+
print(info(f"Test du token avec l'API d'inférence sur le modèle public {test_model}..."))
|
92 |
+
|
93 |
+
headers = {"Authorization": f"Bearer {token}"}
|
94 |
+
payload = {"inputs": "Hello, how are you?"}
|
95 |
+
|
96 |
+
response = requests.post(api_url, headers=headers, json=payload, timeout=10)
|
97 |
+
|
98 |
+
if response.status_code in [200, 503]: # 503 signifie que le modèle est en cours de chargement, mais le token est valide
|
99 |
+
print(success(f"Token valide pour l'API d'inférence! Status code: {response.status_code}"))
|
100 |
+
if response.status_code == 503:
|
101 |
+
print(info("Le modèle est en cours de chargement. Le token a bien été accepté par l'API."))
|
102 |
+
results["is_valid"] = True
|
103 |
+
results["can_access_inference"] = True
|
104 |
+
|
105 |
+
if verbose and response.status_code == 200:
|
106 |
+
print(info("Résultat de l'inférence:"))
|
107 |
+
print(json.dumps(response.json(), indent=2))
|
108 |
+
else:
|
109 |
+
print(error(f"Échec du test de l'API d'inférence. Status code: {response.status_code}"))
|
110 |
+
results["error_message"] = response.text
|
111 |
+
|
112 |
+
try:
|
113 |
+
error_data = response.json()
|
114 |
+
if "error" in error_data:
|
115 |
+
print(error(f"Message d'erreur: {error_data['error']}"))
|
116 |
+
results["error_message"] = error_data['error']
|
117 |
+
except:
|
118 |
+
print(error(f"Message d'erreur: {response.text}"))
|
119 |
+
|
120 |
+
# En cas d'échec, tester aussi l'endpoint de liste des modèles
|
121 |
+
try:
|
122 |
+
print(info("Test alternatif avec la liste des modèles déployés..."))
|
123 |
+
list_url = "https://api-inference.huggingface.co/status"
|
124 |
+
list_response = requests.get(list_url, headers=headers, timeout=10)
|
125 |
+
|
126 |
+
if list_response.status_code == 200:
|
127 |
+
print(success("Le token peut accéder à la liste des modèles déployés"))
|
128 |
+
results["can_access_inference"] = True
|
129 |
+
results["is_valid"] = True
|
130 |
+
else:
|
131 |
+
print(error(f"Échec de l'accès à la liste des modèles. Status code: {list_response.status_code}"))
|
132 |
+
except Exception as e:
|
133 |
+
print(error(f"Erreur lors du test alternatif: {str(e)}"))
|
134 |
+
|
135 |
+
except Exception as e:
|
136 |
+
print(error(f"Erreur lors du test de l'API d'inférence: {str(e)}"))
|
137 |
+
results["error_message"] = str(e)
|
138 |
+
|
139 |
+
# 4. Tests supplémentaires des permissions
|
140 |
+
if results["is_valid"]:
|
141 |
+
try:
|
142 |
+
print(info("\nTest des permissions du token..."))
|
143 |
+
|
144 |
+
# Tester si on peut accéder aux modèles privés de l'organisation
|
145 |
+
if os.environ.get("HF_ORGANIZATION"):
|
146 |
+
org = os.environ.get("HF_ORGANIZATION")
|
147 |
+
print(info(f"Test d'accès aux modèles de l'organisation {org}..."))
|
148 |
+
|
149 |
+
# On regarde juste si on peut accéder à la liste des modèles de l'organisation
|
150 |
+
org_url = f"https://huggingface.co/api/models?author={org}"
|
151 |
+
org_response = requests.get(org_url, headers=headers, timeout=10)
|
152 |
+
|
153 |
+
if org_response.status_code == 200:
|
154 |
+
print(success(f"Accès autorisé aux modèles de l'organisation {org}"))
|
155 |
+
else:
|
156 |
+
print(warning(f"Le token n'a pas accès aux modèles de l'organisation {org}"))
|
157 |
+
except Exception as e:
|
158 |
+
print(error(f"Erreur lors du test des permissions: {str(e)}"))
|
159 |
+
|
160 |
+
return results
|
161 |
+
|
162 |
+
|
163 |
+
def check_model_access(token, model, verbose=False):
|
164 |
+
"""
|
165 |
+
Vérifie si le token a accès à un modèle spécifique.
|
166 |
+
|
167 |
+
Args:
|
168 |
+
token: Token HF à vérifier
|
169 |
+
model: Nom du modèle à tester
|
170 |
+
verbose: Afficher des informations détaillées
|
171 |
+
|
172 |
+
Returns:
|
173 |
+
bool: True si le modèle est accessible, False sinon
|
174 |
+
"""
|
175 |
+
print(f"\n" + info(f"Test d'accès au modèle: {model}"))
|
176 |
+
|
177 |
+
headers = {
|
178 |
+
"Authorization": f"Bearer {token}"
|
179 |
+
}
|
180 |
+
|
181 |
+
# 1. Vérifier si le modèle existe et est accessible via l'API d'inférence
|
182 |
+
try:
|
183 |
+
api_url = f"https://api-inference.huggingface.co/models/{model}"
|
184 |
+
payload = {"inputs": "Hello, test access"}
|
185 |
+
|
186 |
+
print(info(f"Test d'accès à l'API d'inférence pour {model}..."))
|
187 |
+
|
188 |
+
response = requests.post(api_url, headers=headers, json=payload, timeout=20)
|
189 |
+
|
190 |
+
if response.status_code in [200, 503]: # 503 = modèle en cours de chargement, mais le token est valide
|
191 |
+
if response.status_code == 200:
|
192 |
+
print(success(f"Accès réussi à l'API d'inférence pour {model}"))
|
193 |
+
return True
|
194 |
+
else:
|
195 |
+
print(success(f"Accès autorisé pour {model} (modèle en cours de chargement)"))
|
196 |
+
return True
|
197 |
+
else:
|
198 |
+
error_message = "Unknown error"
|
199 |
+
try:
|
200 |
+
error_data = response.json()
|
201 |
+
if "error" in error_data:
|
202 |
+
error_message = error_data["error"]
|
203 |
+
except:
|
204 |
+
error_message = response.text
|
205 |
+
|
206 |
+
print(error(f"Échec d'accès à l'API d'inférence pour {model}: {response.status_code}"))
|
207 |
+
print(error(f"Message: {error_message}"))
|
208 |
+
|
209 |
+
# Analyse de l'erreur
|
210 |
+
if "quota" in error_message.lower() or "rate" in error_message.lower():
|
211 |
+
print(warning("Possible problème de quota ou de limite de taux"))
|
212 |
+
elif "loading" in error_message.lower():
|
213 |
+
print(info("Le modèle est en cours de chargement - réessayez plus tard"))
|
214 |
+
return True # Considérer comme un succès car le token est accepté
|
215 |
+
elif "permission" in error_message.lower() or "access" in error_message.lower():
|
216 |
+
print(error("Problème de permissions - vous n'avez pas accès à ce modèle"))
|
217 |
+
|
218 |
+
# Faire un test alternatif via l'API du Hub
|
219 |
+
try:
|
220 |
+
print(info(f"Test alternatif via l'API du Hub pour {model}..."))
|
221 |
+
hub_url = f"https://huggingface.co/api/models/{model}"
|
222 |
+
hub_response = requests.get(hub_url, headers=headers, timeout=10)
|
223 |
+
|
224 |
+
if hub_response.status_code == 200:
|
225 |
+
print(warning(f"Le modèle {model} existe et est accessible via l'API Hub, mais pas via l'API d'inférence"))
|
226 |
+
print(info("Cela peut être dû à des restrictions sur le modèle ou à des problèmes temporaires de l'API"))
|
227 |
+
if verbose:
|
228 |
+
model_info = hub_response.json()
|
229 |
+
if model_info.get("private", False):
|
230 |
+
print(info("Ce modèle est privé"))
|
231 |
+
if model_info.get("gated", False):
|
232 |
+
print(info("Ce modèle est à accès restreint (gated)"))
|
233 |
+
else:
|
234 |
+
print(error(f"Le modèle {model} n'est pas accessible via l'API Hub non plus: {hub_response.status_code}"))
|
235 |
+
except Exception as e:
|
236 |
+
print(error(f"Erreur lors du test alternatif: {str(e)}"))
|
237 |
+
|
238 |
+
return False
|
239 |
+
|
240 |
+
except Exception as e:
|
241 |
+
print(error(f"Erreur lors du test d'accès au modèle: {str(e)}"))
|
242 |
+
return False
|
243 |
+
|
244 |
+
|
245 |
+
def main():
|
246 |
+
parser = ArgumentParser(description="Vérifiez les propriétés d'un token Hugging Face")
|
247 |
+
parser.add_argument("--token", type=str, help="Token Hugging Face à vérifier (si non spécifié, utilise HF_TOKEN)")
|
248 |
+
parser.add_argument("--verbose", "-v", action="store_true", help="Afficher des informations détaillées")
|
249 |
+
parser.add_argument("--test-model", "-m", type=str, help="Tester l'accès à un modèle spécifique")
|
250 |
+
parser.add_argument("--test-premium", action="store_true", help="Tester l'accès aux modèles premium courants")
|
251 |
+
|
252 |
+
args = parser.parse_args()
|
253 |
+
|
254 |
+
# Charger les variables d'environnement
|
255 |
+
load_dotenv()
|
256 |
+
|
257 |
+
print(info(f"=== Vérification de Token Hugging Face - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===\n"))
|
258 |
+
|
259 |
+
# Vérifier le token via l'API d'inférence directement
|
260 |
+
token = args.token or os.environ.get("HF_TOKEN")
|
261 |
+
token_info = check_token_via_inference_api(token, args.verbose)
|
262 |
+
|
263 |
+
# Si le token est valide et qu'on a demandé de tester un modèle
|
264 |
+
if token_info["is_valid"]:
|
265 |
+
if args.test_model:
|
266 |
+
check_model_access(token, args.test_model, args.verbose)
|
267 |
+
|
268 |
+
if args.test_premium:
|
269 |
+
print("\n" + info("=== Test d'accès aux modèles premium ==="))
|
270 |
+
premium_models = [
|
271 |
+
"meta-llama/Llama-3.3-70B-Instruct",
|
272 |
+
"mistralai/Mistral-Small-24B-Instruct-2501",
|
273 |
+
"deepseek-ai/DeepSeek-R1-Distill-Llama-70B"
|
274 |
+
]
|
275 |
+
|
276 |
+
for model in premium_models:
|
277 |
+
result = check_model_access(token, model, args.verbose)
|
278 |
+
print(info(f"Résultat pour {model}: {success('Accessible') if result else error('Non accessible')}"))
|
279 |
+
print("-" * 50)
|
280 |
+
|
281 |
+
|
282 |
+
if __name__ == "__main__":
|
283 |
+
main()
|