File size: 3,854 Bytes
8a6ff9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# diagnose.py
import os
import requests
import json

print("=" * 60)
print("🔍 ДИАГНОСТИКА HUGGING FACE API")
print("=" * 60)

# 1. Проверка токена
token = os.environ.get("HF_TOKEN")
print(f"1. Токен в переменных: {'✅ Есть' if token else '❌ Нет'}")
if token:
    print(f"   Длина: {len(token)} символов")
    print(f"   Начинается с: {token[:10]}...")

# 2. Проверка базового доступа
print("\n2. Проверка доступности API...")
try:
    test_url = "https://huggingface.co/api/whoami-v2"
    headers = {"Authorization": f"Bearer {token}"} if token else {}

    response = requests.get(test_url, headers=headers, timeout=10)
    if response.status_code == 200:
        user_data = response.json()
        print(f"   ✅ API доступен. Пользователь: {user_data.get('name', 'Unknown')}")
        print(f"   Организации: {[org['name'] for org in user_data.get('orgs', [])]}")
    else:
        print(f"   ❌ API недоступен. Код: {response.status_code}")
except Exception as e:
    print(f"   ❌ Ошибка подключения: {str(e)}")

# 3. Проверка Inference API
print("\n3. Тестирование Inference API...")
test_models = [
    "gpt2",  # Всегда должен работать
    "microsoft/phi-2",  # Проверка с токеном
]

for model in test_models:
    try:
        url = f"https://api-inference.huggingface.co/models/{model}"
        headers = {"Authorization": f"Bearer {token}"} if token else {}

        response = requests.post(
            url,
            headers=headers,
            json={"inputs": "Hello", "parameters": {"max_length": 5}},
            timeout=15
        )

        print(f"   {model}: ", end="")
        if response.status_code == 200:
            print("✅ Работает")
            # print(f"      Ответ: {response.json()}")
        elif response.status_code == 401:
            print("❌ 401 Unauthorized (проблема с токеном)")
        elif response.status_code == 403:
            print("❌ 403 Forbidden (нет прав на модель)")
        elif response.status_code == 404:
            print("❌ 404 Model not found")
        elif response.status_code == 429:
            print("⚠️  429 Rate limited (закончилась квота)")
        elif response.status_code == 503:
            print("⚠️  503 Model loading (модель загружается)")
            # Проверяем статус загрузки
            loading_url = f"https://api-inference.huggingface.co/status/{model.split('/')[-1]}"
            loading_response = requests.get(loading_url, headers=headers)
            if loading_response.status_code == 200:
                status = loading_response.json()
                print(f"      Статус: {status.get('state', 'unknown')}")
        else:
            print(f"❌ Код: {response.status_code}")
            print(f"      Ответ: {response.text[:100]}")

    except Exception as e:
        print(f"   {model}: ❌ Ошибка: {str(e)[:50]}")

print("\n" + "=" * 60)
print("РЕКОМЕНДАЦИИ:")

if not token:
    print("1. Добавьте HF_TOKEN в Variables & Secrets")
elif "401" in str(response.status_code):
    print("1. Токен невалиден. Создайте новый с Role=Write")
elif "429" in str(response.status_code):
    print("1. Закончилась бесплатная квота. Подождите или купите PRO")
elif "503" in str(response.status_code):
    print("1. Модель загружается. Подождите 30-60 секунд")
else:
    print("1. Используйте самый простой вариант с gpt2")

print("=" * 60)