Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 11,724 Bytes
aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa c4411e8 aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 3964afa aae1c13 |
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 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Standalone script to check and display Hugging Face token properties.
This script can be run separately to diagnose authentication issues.
"""
import os
import sys
import json
import requests
from datetime import datetime
from dotenv import load_dotenv
from argparse import ArgumentParser
def color_text(text, color_code):
"""Format text with color for terminal output."""
return f"\033[{color_code}m{text}\033[0m"
def success(text):
"""Format text as success message (green)."""
return color_text(f"✅ {text}", "92")
def warning(text):
"""Format text as warning message (yellow)."""
return color_text(f"⚠️ {text}", "93")
def error(text):
"""Format text as error message (red)."""
return color_text(f"❌ {text}", "91")
def info(text):
"""Format text as info message (blue)."""
return color_text(f"ℹ️ {text}", "94")
def check_token_via_inference_api(token=None, verbose=True):
"""
Check the validity of an HF token by directly testing the inference API.
The whoami API doesn't always work correctly for tokens but the inference API
is the priority in our application.
Args:
token: The token to check
verbose: Display detailed information
Returns:
dict: Check results
"""
results = {
"is_valid": False,
"token": None,
"error_message": None,
"can_access_inference": False
}
# 1. Obtenir le token
if token is None:
token = os.environ.get("HF_TOKEN")
if not token:
print(error("Aucun token trouvé. Veuillez spécifier un token avec --token ou définir la variable d'environnement HF_TOKEN."))
results["error_message"] = "No token provided"
return results
# Don't show any token characters, just indicate its presence
masked_token = "••••••••••"
results["token"] = masked_token
print(info(f"Token à vérifier: {masked_token}"))
# 2. Check basic format
if not token.startswith("hf_"):
print(warning("Le token ne commence pas par 'hf_' ce qui est inhabituel. Vérifiez son format."))
else:
print(success("Format du token valide (commence par 'hf_')"))
# 3. Test inference API directly - recommended method to validate a token
try:
# Test with a simple public model
test_model = "gpt2"
api_url = f"https://api-inference.huggingface.co/models/{test_model}"
print(info(f"Test du token avec l'API d'inférence sur le modèle public {test_model}..."))
headers = {"Authorization": f"Bearer {token}"}
payload = {"inputs": "Hello, how are you?"}
response = requests.post(api_url, headers=headers, json=payload, timeout=10)
if response.status_code in [200, 503]: # 503 means the model is loading, but the token is valid
print(success(f"Token valide pour l'API d'inférence! Status code: {response.status_code}"))
if response.status_code == 503:
print(info("Le modèle est en cours de chargement. Le token a bien été accepté par l'API."))
results["is_valid"] = True
results["can_access_inference"] = True
if verbose and response.status_code == 200:
print(info("Résultat de l'inférence:"))
print(json.dumps(response.json(), indent=2))
else:
print(error(f"Échec du test de l'API d'inférence. Status code: {response.status_code}"))
results["error_message"] = response.text
try:
error_data = response.json()
if "error" in error_data:
print(error(f"Message d'erreur: {error_data['error']}"))
results["error_message"] = error_data['error']
except:
print(error(f"Message d'erreur: {response.text}"))
# In case of failure, also test the model list endpoint
try:
print(info("Test alternatif avec la liste des modèles déployés..."))
list_url = "https://api-inference.huggingface.co/status"
list_response = requests.get(list_url, headers=headers, timeout=10)
if list_response.status_code == 200:
print(success("Le token peut accéder à la liste des modèles déployés"))
results["can_access_inference"] = True
results["is_valid"] = True
else:
print(error(f"Échec de l'accès à la liste des modèles. Status code: {list_response.status_code}"))
except Exception as e:
print(error(f"Erreur lors du test alternatif: {str(e)}"))
except Exception as e:
print(error(f"Erreur lors du test de l'API d'inférence: {str(e)}"))
results["error_message"] = str(e)
# 4. Additional permission tests
if results["is_valid"]:
try:
print(info("\nTest des permissions du token..."))
# Test if we can access organization's private models
if os.environ.get("HF_ORGANIZATION"):
org = os.environ.get("HF_ORGANIZATION")
print(info(f"Test d'accès aux modèles de l'organisation {org}..."))
# Just check if we can access the organization's model list
org_url = f"https://huggingface.co/api/models?author={org}"
org_response = requests.get(org_url, headers=headers, timeout=10)
if org_response.status_code == 200:
print(success(f"Accès autorisé aux modèles de l'organisation {org}"))
else:
print(warning(f"Le token n'a pas accès aux modèles de l'organisation {org}"))
except Exception as e:
print(error(f"Erreur lors du test des permissions: {str(e)}"))
return results
def check_model_access(token, model, verbose=False):
"""
Check if the token has access to a specific model.
Args:
token: HF token to check
model: Name of the model to test
verbose: Display detailed information
Returns:
bool: True if model is accessible, False otherwise
"""
print(f"\n" + info(f"Test d'accès au modèle: {model}"))
headers = {
"Authorization": f"Bearer {token}"
}
# 1. Check if the model exists and is accessible via inference API
try:
api_url = f"https://api-inference.huggingface.co/models/{model}"
payload = {"inputs": "Hello, test access"}
print(info(f"Test d'accès à l'API d'inférence pour {model}..."))
response = requests.post(api_url, headers=headers, json=payload, timeout=20)
if response.status_code in [200, 503]: # 503 = model is loading, but token is valid
if response.status_code == 200:
print(success(f"Accès réussi à l'API d'inférence pour {model}"))
return True
else:
print(success(f"Accès autorisé pour {model} (modèle en cours de chargement)"))
return True
else:
error_message = "Unknown error"
try:
error_data = response.json()
if "error" in error_data:
error_message = error_data["error"]
except:
error_message = response.text
print(error(f"Échec d'accès à l'API d'inférence pour {model}: {response.status_code}"))
print(error(f"Message: {error_message}"))
# Analyse de l'erreur
if "quota" in error_message.lower() or "rate" in error_message.lower():
print(warning("Possible problème de quota ou de limite de taux"))
elif "loading" in error_message.lower():
print(info("Le modèle est en cours de chargement - réessayez plus tard"))
return True # Consider as success because token is accepted
elif "permission" in error_message.lower() or "access" in error_message.lower():
print(error("Problème de permissions - vous n'avez pas accès à ce modèle"))
# Faire un test alternatif via l'API du Hub
try:
print(info(f"Test alternatif via l'API du Hub pour {model}..."))
hub_url = f"https://huggingface.co/api/models/{model}"
hub_response = requests.get(hub_url, headers=headers, timeout=10)
if hub_response.status_code == 200:
print(warning(f"Le modèle {model} existe et est accessible via l'API Hub, mais pas via l'API d'inférence"))
print(info("Cela peut être dû à des restrictions sur le modèle ou à des problèmes temporaires de l'API"))
if verbose:
model_info = hub_response.json()
if model_info.get("private", False):
print(info("Ce modèle est privé"))
if model_info.get("gated", False):
print(info("Ce modèle est à accès restreint (gated)"))
else:
print(error(f"Le modèle {model} n'est pas accessible via l'API Hub non plus: {hub_response.status_code}"))
except Exception as e:
print(error(f"Erreur lors du test alternatif: {str(e)}"))
return False
except Exception as e:
print(error(f"Erreur lors du test d'accès au modèle: {str(e)}"))
return False
def main():
parser = ArgumentParser(description="Vérifiez les propriétés d'un token Hugging Face")
parser.add_argument("--token", type=str, help="Token Hugging Face à vérifier (si non spécifié, utilise HF_TOKEN)")
parser.add_argument("--verbose", "-v", action="store_true", help="Afficher des informations détaillées")
parser.add_argument("--test-model", "-m", type=str, help="Tester l'accès à un modèle spécifique")
parser.add_argument("--test-premium", action="store_true", help="Tester l'accès aux modèles premium courants")
args = parser.parse_args()
# Load environment variables
load_dotenv()
print(info(f"=== Vérification de Token Hugging Face - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} ===\n"))
# Check token directly via inference API
token = args.token or os.environ.get("HF_TOKEN")
token_info = check_token_via_inference_api(token, args.verbose)
# If token is valid and we were asked to test a model
if token_info["is_valid"]:
if args.test_model:
check_model_access(token, args.test_model, args.verbose)
if args.test_premium:
print("\n" + info("=== Test d'accès aux modèles premium ==="))
premium_models = [
"meta-llama/Llama-3.3-70B-Instruct",
"mistralai/Mistral-Small-24B-Instruct-2501",
"deepseek-ai/DeepSeek-R1-Distill-Llama-70B"
]
for model in premium_models:
result = check_model_access(token, model, args.verbose)
print(info(f"Résultat pour {model}: {success('Accessible') if result else error('Non accessible')}"))
print("-" * 50)
if __name__ == "__main__":
main() |