Dzsysop commited on
Commit
8a6ff9d
·
1 Parent(s): d18d426

debug app.py about available models

Browse files
Files changed (2) hide show
  1. app.py +19 -88
  2. diagnose.py +93 -0
app.py CHANGED
@@ -1,93 +1,24 @@
1
- # diagnose.py
 
 
2
  import os
3
- import requests
4
- import json
5
 
6
- print("=" * 60)
7
- print("🔍 ДИАГНОСТИКА HUGGING FACE API")
8
- print("=" * 60)
9
 
10
- # 1. Проверка токена
11
- token = os.environ.get("HF_TOKEN")
12
- print(f"1. Токен в переменных: {'✅ Есть' if token else '❌ Нет'}")
13
- if token:
14
- print(f" Длина: {len(token)} символов")
15
- print(f" Начинается с: {token[:10]}...")
16
-
17
- # 2. Проверка базового доступа
18
- print("\n2. Проверка доступности API...")
19
- try:
20
- test_url = "https://huggingface.co/api/whoami-v2"
21
- headers = {"Authorization": f"Bearer {token}"} if token else {}
22
-
23
- response = requests.get(test_url, headers=headers, timeout=10)
24
- if response.status_code == 200:
25
- user_data = response.json()
26
- print(f" ✅ API доступен. Пользователь: {user_data.get('name', 'Unknown')}")
27
- print(f" Организации: {[org['name'] for org in user_data.get('orgs', [])]}")
28
- else:
29
- print(f" ❌ API недоступен. Код: {response.status_code}")
30
- except Exception as e:
31
- print(f" ❌ Ошибка подключения: {str(e)}")
32
-
33
- # 3. Проверка Inference API
34
- print("\n3. Тестирование Inference API...")
35
- test_models = [
36
- "gpt2", # Всегда должен работать
37
- "microsoft/phi-2", # Проверка с токеном
38
- ]
39
-
40
- for model in test_models:
41
  try:
42
- url = f"https://api-inference.huggingface.co/models/{model}"
43
- headers = {"Authorization": f"Bearer {token}"} if token else {}
44
-
45
- response = requests.post(
46
- url,
47
- headers=headers,
48
- json={"inputs": "Hello", "parameters": {"max_length": 5}},
49
- timeout=15
50
  )
51
-
52
- print(f" {model}: ", end="")
53
- if response.status_code == 200:
54
- print("✅ Работает")
55
- # print(f" Ответ: {response.json()}")
56
- elif response.status_code == 401:
57
- print(" 401 Unauthorized (проблема с токеном)")
58
- elif response.status_code == 403:
59
- print(" 403 Forbidden (нет прав на модель)")
60
- elif response.status_code == 404:
61
- print("❌ 404 Model not found")
62
- elif response.status_code == 429:
63
- print("⚠️ 429 Rate limited (закончилась квота)")
64
- elif response.status_code == 503:
65
- print("⚠️ 503 Model loading (модель загружается)")
66
- # Проверяем статус загрузки
67
- loading_url = f"https://api-inference.huggingface.co/status/{model.split('/')[-1]}"
68
- loading_response = requests.get(loading_url, headers=headers)
69
- if loading_response.status_code == 200:
70
- status = loading_response.json()
71
- print(f" Статус: {status.get('state', 'unknown')}")
72
- else:
73
- print(f"❌ Код: {response.status_code}")
74
- print(f" Ответ: {response.text[:100]}")
75
-
76
- except Exception as e:
77
- print(f" {model}: ❌ Ошибка: {str(e)[:50]}")
78
-
79
- print("\n" + "=" * 60)
80
- print("РЕКОМЕНДАЦИИ:")
81
-
82
- if not token:
83
- print("1. Добавьте HF_TOKEN в Variables & Secrets")
84
- elif "401" in str(response.status_code):
85
- print("1. Токен невалиден. Создайте новый с Role=Write")
86
- elif "429" in str(response.status_code):
87
- print("1. Закончилась бесплатная квота. Подождите или купите PRO")
88
- elif "503" in str(response.status_code):
89
- print("1. Модель загружается. Подождите 30-60 секунд")
90
- else:
91
- print("1. Используйте самый простой вариант с gpt2")
92
-
93
- print("=" * 60)
 
1
+ # app.py
2
+ import gradio as gr
3
+ from huggingface_hub import InferenceClient
4
  import os
 
 
5
 
6
+ client = InferenceClient(token=os.environ.get("HF_TOKEN"))
 
 
7
 
8
+ def predict(prompt):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  try:
10
+ response = client.text_generation(
11
+ prompt=prompt,
12
+ model="microsoft/phi-2",
13
+ max_new_tokens=100
 
 
 
 
14
  )
15
+ return response
16
+ except:
17
+ return "Извините, сервис временно недоступен"
18
+
19
+ gr.Interface(
20
+ fn=predict,
21
+ inputs=gr.Textbox(label="Вопрос к NPC"),
22
+ outputs=gr.Textbox(label="Ответ"),
23
+ title="AI для игры"
24
+ ).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
diagnose.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # diagnose.py
2
+ import os
3
+ import requests
4
+ import json
5
+
6
+ print("=" * 60)
7
+ print("🔍 ДИАГНОСТИКА HUGGING FACE API")
8
+ print("=" * 60)
9
+
10
+ # 1. Проверка токена
11
+ token = os.environ.get("HF_TOKEN")
12
+ print(f"1. Токен в переменных: {'✅ Есть' if token else '❌ Нет'}")
13
+ if token:
14
+ print(f" Длина: {len(token)} символов")
15
+ print(f" Начинается с: {token[:10]}...")
16
+
17
+ # 2. Проверка базового доступа
18
+ print("\n2. Проверка доступности API...")
19
+ try:
20
+ test_url = "https://huggingface.co/api/whoami-v2"
21
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
22
+
23
+ response = requests.get(test_url, headers=headers, timeout=10)
24
+ if response.status_code == 200:
25
+ user_data = response.json()
26
+ print(f" ✅ API доступен. Пользователь: {user_data.get('name', 'Unknown')}")
27
+ print(f" Организации: {[org['name'] for org in user_data.get('orgs', [])]}")
28
+ else:
29
+ print(f" ❌ API недоступен. Код: {response.status_code}")
30
+ except Exception as e:
31
+ print(f" ❌ Ошибка подключения: {str(e)}")
32
+
33
+ # 3. Проверка Inference API
34
+ print("\n3. Тестирование Inference API...")
35
+ test_models = [
36
+ "gpt2", # Всегда должен работать
37
+ "microsoft/phi-2", # Проверка с токеном
38
+ ]
39
+
40
+ for model in test_models:
41
+ try:
42
+ url = f"https://api-inference.huggingface.co/models/{model}"
43
+ headers = {"Authorization": f"Bearer {token}"} if token else {}
44
+
45
+ response = requests.post(
46
+ url,
47
+ headers=headers,
48
+ json={"inputs": "Hello", "parameters": {"max_length": 5}},
49
+ timeout=15
50
+ )
51
+
52
+ print(f" {model}: ", end="")
53
+ if response.status_code == 200:
54
+ print("✅ Работает")
55
+ # print(f" Ответ: {response.json()}")
56
+ elif response.status_code == 401:
57
+ print("❌ 401 Unauthorized (проблема с токеном)")
58
+ elif response.status_code == 403:
59
+ print("❌ 403 Forbidden (нет прав на модель)")
60
+ elif response.status_code == 404:
61
+ print("❌ 404 Model not found")
62
+ elif response.status_code == 429:
63
+ print("⚠️ 429 Rate limited (закончилась квота)")
64
+ elif response.status_code == 503:
65
+ print("⚠️ 503 Model loading (модель загружается)")
66
+ # Проверяем статус загрузки
67
+ loading_url = f"https://api-inference.huggingface.co/status/{model.split('/')[-1]}"
68
+ loading_response = requests.get(loading_url, headers=headers)
69
+ if loading_response.status_code == 200:
70
+ status = loading_response.json()
71
+ print(f" Статус: {status.get('state', 'unknown')}")
72
+ else:
73
+ print(f"❌ Код: {response.status_code}")
74
+ print(f" Ответ: {response.text[:100]}")
75
+
76
+ except Exception as e:
77
+ print(f" {model}: ❌ Ошибка: {str(e)[:50]}")
78
+
79
+ print("\n" + "=" * 60)
80
+ print("РЕКОМЕНДАЦИИ:")
81
+
82
+ if not token:
83
+ print("1. Добавьте HF_TOKEN в Variables & Secrets")
84
+ elif "401" in str(response.status_code):
85
+ print("1. Токен невалиден. Создайте новый с Role=Write")
86
+ elif "429" in str(response.status_code):
87
+ print("1. Закончилась бесплатная квота. Подождите или купите PRO")
88
+ elif "503" in str(response.status_code):
89
+ print("1. Модель загружается. Подождите 30-60 секунд")
90
+ else:
91
+ print("1. Используйте самый простой вариант с gpt2")
92
+
93
+ print("=" * 60)