Yermek68 commited on
Commit
5b714a0
·
verified ·
1 Parent(s): 3f976bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -29
app.py CHANGED
@@ -1,57 +1,107 @@
1
- from fastapi import FastAPI
2
- import gradio as gr
3
- from core.agent import generate_response
4
-
5
  import os
6
  import requests
 
 
7
 
 
 
 
8
  def check_hf_token():
9
  token = os.getenv("HF_TOKEN")
10
  if not token:
11
  print("❌ HF_TOKEN не найден. Добавь его в Secrets.")
12
- return "❌ Токен не найден"
13
 
14
  headers = {"Authorization": f"Bearer {token}"}
15
  try:
16
  response = requests.get("https://huggingface.co/api/whoami-v2", headers=headers, timeout=10)
17
  if response.status_code == 200:
18
  user = response.json().get("name", "неизвестный пользователь")
19
- print(f"✅ Hugging Face API доступен. Авторизован как: {user}")
20
- return f"✅ API доступен ({user})"
21
  else:
22
  print(f"⚠️ Токен отклонён. Код {response.status_code}")
23
  return f"⚠️ Ошибка токена ({response.status_code})"
24
  except Exception as e:
25
  print(f"❌ Ошибка подключения к Hugging Face API: {e}")
26
- return f"❌ Ошибка: {e}"
27
 
28
- # выполнить проверку при запуске приложения
29
  status_message = check_hf_token()
30
 
31
- app = FastAPI(title="Eroha AgentAPI v3.1 (Guru Edition)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- def chat_interface(user_input):
34
- return generate_response(user_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
- iface = gr.Interface(
37
- fn=chat_interface,
38
- inputs=gr.Textbox(lines=3, placeholder="Введите запрос..."),
39
- outputs="text",
40
- title="🤖 Eroha AgentAPI v3.1 — Guru Edition",
41
- description="Умный агент на базе Hugging Face Inference API"
42
- )
 
 
43
 
44
- @app.get("/health")
45
- def health():
46
- return {"status": "ok"}
 
 
47
 
48
- @app.get("/")
49
- def index():
50
- return {"message": "Eroha AgentAPI v3.1 — running!"}
51
 
52
- @app.get("/generate")
53
- def generate(q: str):
54
- return {"result": generate_response(q)}
55
 
 
 
 
56
  if __name__ == "__main__":
57
- iface.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ #!/usr/bin/env python3
 
 
 
2
  import os
3
  import requests
4
+ import gradio as gr
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
6
 
7
+ # ==========================================================
8
+ # 1️⃣ Проверка токена Hugging Face API
9
+ # ==========================================================
10
  def check_hf_token():
11
  token = os.getenv("HF_TOKEN")
12
  if not token:
13
  print("❌ HF_TOKEN не найден. Добавь его в Secrets.")
14
+ return "❌ HF_TOKEN не найден (добавь в Settings → Secrets)"
15
 
16
  headers = {"Authorization": f"Bearer {token}"}
17
  try:
18
  response = requests.get("https://huggingface.co/api/whoami-v2", headers=headers, timeout=10)
19
  if response.status_code == 200:
20
  user = response.json().get("name", "неизвестный пользователь")
21
+ print(f"✅ Подключено к Hugging Face API. Авторизован как: {user}")
22
+ return f"✅ Подключено к Hugging Face API {user}"
23
  else:
24
  print(f"⚠️ Токен отклонён. Код {response.status_code}")
25
  return f"⚠️ Ошибка токена ({response.status_code})"
26
  except Exception as e:
27
  print(f"❌ Ошибка подключения к Hugging Face API: {e}")
28
+ return f"❌ Ошибка подключения: {e}"
29
 
 
30
  status_message = check_hf_token()
31
 
32
+ # ==========================================================
33
+ # 2️⃣ Авто-подбор оптимальной модели (умный выбор)
34
+ # ==========================================================
35
+ def auto_select_model(prompt: str) -> str:
36
+ """Определяет лучшую бесплатную модель HF под задачу"""
37
+ prompt_lower = prompt.lower()
38
+
39
+ # Логика выбора модели
40
+ if any(x in prompt_lower for x in ["квант", "физик", "теория", "расчёт", "анализ"]):
41
+ return "mistralai/Mistral-7B-Instruct-v0.3"
42
+ elif any(x in prompt_lower for x in ["программ", "код", "python", "js", "ошибка", "debug"]):
43
+ return "bigcode/starcoder2-3b"
44
+ elif any(x in prompt_lower for x in ["переведи", "английский", "translate", "перевод"]):
45
+ return "facebook/nllb-200-distilled-600M"
46
+ elif any(x in prompt_lower for x in ["психолог", "мотивация", "совет", "эмоции", "отношения"]):
47
+ return "meta-llama/Llama-3.2-1B-Instruct"
48
+ else:
49
+ return "microsoft/Phi-3.5-mini-instruct" # базовая «гуру» модель
50
+
51
+ # ==========================================================
52
+ # 3️⃣ Генерация ответа от выбранной модели
53
+ # ==========================================================
54
+ def generate_response(user_input: str):
55
+ if not user_input.strip():
56
+ return "⚠️ Введите запрос"
57
+
58
+ # Автоматически выбираем подходящую модель
59
+ model_name = auto_select_model(user_input)
60
+ print(f"🔍 Выбрана модель: {model_name}")
61
+
62
+ token = os.getenv("HF_TOKEN")
63
+ headers = {"Authorization": f"Bearer {token}"}
64
 
65
+ # Используем Inference API Hugging Face
66
+ api_url = f"https://api-inference.huggingface.co/models/{model_name}"
67
+
68
+ payload = {"inputs": user_input, "parameters": {"max_new_tokens": 300, "temperature": 0.7}}
69
+ try:
70
+ response = requests.post(api_url, headers=headers, json=payload, timeout=60)
71
+ if response.status_code == 200:
72
+ data = response.json()
73
+ if isinstance(data, list) and len(data) > 0 and "generated_text" in data[0]:
74
+ output = data[0]["generated_text"]
75
+ else:
76
+ output = str(data)
77
+ return f"🤖 Модель: {model_name}\n\n{output}"
78
+ else:
79
+ return f"⚠️ Ошибка API ({response.status_code}): {response.text}"
80
+ except Exception as e:
81
+ return f"❌ Ошибка при обращении к модели: {e}"
82
 
83
+ # ==========================================================
84
+ # 4️⃣ Интерфейс Gradio
85
+ # ==========================================================
86
+ with gr.Blocks(title="Eroha AgentAPI v3.1 — Guru Edition") as demo:
87
+ gr.Markdown(
88
+ f"<div style='background-color:#e8f5e9;padding:10px;border-radius:6px;border:1px solid #4caf50;"
89
+ f"color:#2e7d32;font-size:16px;margin-bottom:10px;'>{status_message}</div>"
90
+ )
91
+ gr.Markdown("### 🤖 Умный агент на базе Hugging Face Inference API")
92
 
93
+ with gr.Row():
94
+ user_input = gr.Textbox(
95
+ label="Введите запрос", placeholder="Например: Объясни, как работает квантовая суперпозиция"
96
+ )
97
+ output = gr.Textbox(label="Ответ", placeholder="Здесь появится ответ")
98
 
99
+ submit_btn = gr.Button("Отправить 🚀")
 
 
100
 
101
+ submit_btn.click(fn=generate_response, inputs=user_input, outputs=output)
 
 
102
 
103
+ # ==========================================================
104
+ # 5️⃣ Запуск
105
+ # ==========================================================
106
  if __name__ == "__main__":
107
+ demo.launch(server_name="0.0.0.0", server_port=7860)