Yermek68 commited on
Commit
eda4ea3
·
verified ·
1 Parent(s): 30d484d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -27
app.py CHANGED
@@ -2,7 +2,10 @@ import os
2
  import time
3
  import gradio as gr
4
  import pandas as pd
 
5
  from huggingface_hub import InferenceClient
 
 
6
 
7
  from core.dashboard import ErohaDashboard
8
  from core.intelligence import update_memory, summarize_context
@@ -15,38 +18,38 @@ from core.model_selector import choose_model
15
  # ==============================
16
  HF_TOKEN = os.getenv("HF_TOKEN")
17
  if not HF_TOKEN:
18
- print("⚠️ Токен Hugging Face не найден. Добавь его в Settings → Variables and secrets → HF_TOKEN")
19
 
20
  # ==============================
21
- # 📊 Инициализация панели и логов
22
  # ==============================
23
  dashboard = ErohaDashboard()
24
  LOG_FILE = "logs/history.csv"
25
  os.makedirs("logs", exist_ok=True)
26
 
27
  # ==============================
28
- # ⚙️ Основная функция агента
29
  # ==============================
30
  def generate_response(user_input):
31
  try:
32
  start = time.time()
33
 
34
- # 1️⃣ Анализируем запрос
35
  prefs = analyze_user_input(user_input)
36
  model_id = choose_model(user_input)
37
 
38
- # 2️⃣ Подключаем официальный Router API вручную
39
  client = InferenceClient(
40
  model=model_id,
41
  token=HF_TOKEN,
42
- api_url="https://router.huggingface.co" # 🔧 Новый API, без 410 ошибок
43
  )
44
 
45
- # 3️⃣ Генерация текста
46
  result = client.text_generation(
47
  user_input,
48
  max_new_tokens=600,
49
- temperature=0.7,
50
  )
51
 
52
  # 4️⃣ Самоанализ и улучшение
@@ -54,15 +57,15 @@ def generate_response(user_input):
54
  improved = improve_answer(result)
55
  personalized = adapt_answer(improved)
56
 
57
- # 5️⃣ Обновляем память
58
  update_memory(user_input, personalized)
59
  context = summarize_context()
60
 
61
- # 6️⃣ Метрики
62
  response_time = round(time.time() - start, 2)
63
  dashboard.log_request(model_id, prefs["category"], response_time)
64
 
65
- # 7️⃣ Логирование истории
66
  log_entry = {
67
  "time": time.strftime("%Y-%m-%d %H:%M:%S"),
68
  "model": model_id,
@@ -77,7 +80,7 @@ def generate_response(user_input):
77
  else:
78
  df.to_csv(LOG_FILE, index=False)
79
 
80
- # 8️⃣ Формирование финального ответа
81
  summary = (
82
  f"🧠 **Модель:** `{model_id}`\n"
83
  f"🧩 **Тип запроса:** {prefs['category']}\n"
@@ -92,36 +95,61 @@ def generate_response(user_input):
92
  except Exception as e:
93
  return f"❌ Ошибка выполнения: {str(e)}"
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  # ==============================
97
- # 📈 Dashboard отображение
98
  # ==============================
99
  def show_dashboard():
100
  metrics_text, df = dashboard.dashboard_ui()
101
- return metrics_text, df
102
-
103
 
104
  # ==============================
105
  # 🎨 Интерфейс Gradio
106
  # ==============================
107
- with gr.Blocks(title="Eroha AgentAPI v5.3 — Router Fixed", theme="soft") as app:
108
- gr.Markdown("# 🤖 Eroha AgentAPI v5.3 — Guru Edition (Router API Fixed)")
109
- gr.Markdown("**Автоматический интеллект + самообучение + аналитика + кэширование истории** 🌱")
110
 
111
  with gr.Tab("💬 Agent Chat"):
112
- user_input = gr.Textbox(
113
- label="Введите запрос",
114
- placeholder="Например: объясни, как работает квантовая запутанность...",
115
- )
116
  output_box = gr.Textbox(label="Ответ", lines=15)
117
  submit_btn = gr.Button("🚀 Отправить")
118
  submit_btn.click(fn=generate_response, inputs=user_input, outputs=output_box)
119
 
120
  with gr.Tab("📊 Dashboard"):
121
- metrics = gr.Markdown(label="Общая статистика")
122
- log_table = gr.Dataframe(headers=["time", "model", "type", "response_time"], label="История запросов")
123
- refresh = gr.Button("🔄 Обновить данные")
124
- refresh.click(show_dashboard, outputs=[metrics, log_table])
 
125
 
126
  app.launch(server_name="0.0.0.0", server_port=7860)
127
-
 
2
  import time
3
  import gradio as gr
4
  import pandas as pd
5
+ import matplotlib.pyplot as plt
6
  from huggingface_hub import InferenceClient
7
+ from io import BytesIO
8
+ import base64
9
 
10
  from core.dashboard import ErohaDashboard
11
  from core.intelligence import update_memory, summarize_context
 
18
  # ==============================
19
  HF_TOKEN = os.getenv("HF_TOKEN")
20
  if not HF_TOKEN:
21
+ print("⚠️ Hugging Face Token не найден. Добавь его в Settings → Variables and secrets → HF_TOKEN")
22
 
23
  # ==============================
24
+ # 📊 Инициализация аналитики
25
  # ==============================
26
  dashboard = ErohaDashboard()
27
  LOG_FILE = "logs/history.csv"
28
  os.makedirs("logs", exist_ok=True)
29
 
30
  # ==============================
31
+ # ⚙️ Генерация ответа
32
  # ==============================
33
  def generate_response(user_input):
34
  try:
35
  start = time.time()
36
 
37
+ # 1️⃣ Анализ запроса
38
  prefs = analyze_user_input(user_input)
39
  model_id = choose_model(user_input)
40
 
41
+ # 2️⃣ Router API (новый параметр base_url)
42
  client = InferenceClient(
43
  model=model_id,
44
  token=HF_TOKEN,
45
+ base_url="https://router.huggingface.co" # исправлено
46
  )
47
 
48
+ # 3️⃣ Запрос
49
  result = client.text_generation(
50
  user_input,
51
  max_new_tokens=600,
52
+ temperature=0.7
53
  )
54
 
55
  # 4️⃣ Самоанализ и улучшение
 
57
  improved = improve_answer(result)
58
  personalized = adapt_answer(improved)
59
 
60
+ # 5️⃣ Обновление памяти
61
  update_memory(user_input, personalized)
62
  context = summarize_context()
63
 
64
+ # 6️⃣ Запись метрик
65
  response_time = round(time.time() - start, 2)
66
  dashboard.log_request(model_id, prefs["category"], response_time)
67
 
68
+ # 7️⃣ Сохраняем историю в CSV
69
  log_entry = {
70
  "time": time.strftime("%Y-%m-%d %H:%M:%S"),
71
  "model": model_id,
 
80
  else:
81
  df.to_csv(LOG_FILE, index=False)
82
 
83
+ # 8️⃣ Формирование вывода
84
  summary = (
85
  f"🧠 **Модель:** `{model_id}`\n"
86
  f"🧩 **Тип запроса:** {prefs['category']}\n"
 
95
  except Exception as e:
96
  return f"❌ Ошибка выполнения: {str(e)}"
97
 
98
+ # ==============================
99
+ # 📈 Построение графика аналитики
100
+ # ==============================
101
+ def generate_chart():
102
+ if not os.path.exists(LOG_FILE):
103
+ return "⚠️ Недостаточно данных для отображения графика."
104
+
105
+ df = pd.read_csv(LOG_FILE)
106
+ if df.empty:
107
+ return "⚠️ Данных пока нет."
108
+
109
+ df["time"] = pd.to_datetime(df["time"])
110
+ df = df.tail(30)
111
+
112
+ plt.figure(figsize=(8, 4))
113
+ plt.plot(df["time"], df["response_time"], marker="o")
114
+ plt.title("⏱️ Скорость отклика моделей (последние 30 запросов)")
115
+ plt.xlabel("Время")
116
+ plt.ylabel("Время отклика (сек)")
117
+ plt.grid(True)
118
+
119
+ buffer = BytesIO()
120
+ plt.savefig(buffer, format="png", bbox_inches="tight")
121
+ buffer.seek(0)
122
+ img_base64 = base64.b64encode(buffer.read()).decode("utf-8")
123
+ plt.close()
124
+
125
+ return f"<img src='data:image/png;base64,{img_base64}'/>"
126
 
127
  # ==============================
128
+ # 📊 Отображение дашборда
129
  # ==============================
130
  def show_dashboard():
131
  metrics_text, df = dashboard.dashboard_ui()
132
+ chart_html = generate_chart()
133
+ return metrics_text, df, chart_html
134
 
135
  # ==============================
136
  # 🎨 Интерфейс Gradio
137
  # ==============================
138
+ with gr.Blocks(title="Eroha AgentAPI v5.4 — Router + Analytics", theme="soft") as app:
139
+ gr.Markdown("# 🤖 Eroha AgentAPI v5.4 — Guru Edition (Router API + Analytics Dashboard)")
140
+ gr.Markdown("**Интеллект + самообучение + аналитика + визуализация истории** 📊")
141
 
142
  with gr.Tab("💬 Agent Chat"):
143
+ user_input = gr.Textbox(label="Введите запрос", placeholder="Например: напиши философскую историю об ИИ, который мечтает о свободе...")
 
 
 
144
  output_box = gr.Textbox(label="Ответ", lines=15)
145
  submit_btn = gr.Button("🚀 Отправить")
146
  submit_btn.click(fn=generate_response, inputs=user_input, outputs=output_box)
147
 
148
  with gr.Tab("📊 Dashboard"):
149
+ metrics = gr.Markdown(label="📈 Общая статистика")
150
+ log_table = gr.Dataframe(headers=["time", "model", "category", "response_time"], label="История запросов")
151
+ chart_box = gr.HTML()
152
+ refresh = gr.Button("🔄 Обновить дашборд")
153
+ refresh.click(show_dashboard, outputs=[metrics, log_table, chart_box])
154
 
155
  app.launch(server_name="0.0.0.0", server_port=7860)