Kenan023214 commited on
Commit
37f312f
·
verified ·
1 Parent(s): d604d43

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -21
app.py CHANGED
@@ -7,7 +7,7 @@ import time
7
  # --- Конфигурация Hugging Face Space ---
8
  MODEL_NAME = "Kenan023214/PyroNet-mini"
9
  DEVICE = "cpu" # Используем CPU, как указано для Basic Space
10
- MAX_NEW_TOKENS = 1024 # Увеличим для "хода мыслей"
11
  MAX_CONTEXT_TOKENS = 2048
12
 
13
  # Словарь с встроенным содержимым шаблонов чата
@@ -102,14 +102,18 @@ def trim_history_to_max_tokens(messages, max_tokens):
102
  total = 0
103
  kept = []
104
  for m in rev:
105
- approx = num_tokens_of_text(m["content"]) + 8
 
 
 
 
106
  if total + approx > max_tokens:
107
  break
108
  kept.append(m)
109
  total += approx
110
  return list(reversed(kept))
111
 
112
- def build_messages_for_template(history_messages, reasoning: bool, language: str):
113
  """Подготавливает сообщения для шаблона, включая системное сообщение."""
114
  full_template_content = CHAT_TEMPLATES.get(language, CHAT_TEMPLATES["en"])
115
 
@@ -117,7 +121,12 @@ def build_messages_for_template(history_messages, reasoning: bool, language: str
117
  system_end_tag = "<|end|>"
118
  system_message_raw = full_template_content.split(system_start_tag)[1].split(system_end_tag)[0].strip()
119
 
120
- messages = [{"role": "system", "content": system_message_raw}] + list(history_messages)
 
 
 
 
 
121
 
122
  if reasoning:
123
  messages.append({"role": "user", "content": f"Режим рассуждения: покажи свои шаги, а затем окончательный ответ, начиная с '{REASONING_SEPARATOR}'"})
@@ -141,25 +150,22 @@ def extract_assistant_reply_and_reasoning(raw_generated_text: str) -> tuple[str,
141
  reply = parts[1].strip()
142
  return reply, reasoning
143
  else:
144
- return text, "" # Если разделитель не найден, возвращаем все как ответ
 
 
145
 
146
  # --- Основная функция для Gradio ---
147
  def generate_response(user_text: str, history, reasoning: bool, language: str):
148
  """
149
  Обрабатывает пользовательский запрос, генерирует ответ и возвращает его
150
- с эффектом печати.
151
  """
152
- # Добавляем user-сообщение во внутреннюю историю
153
  history.append([user_text, None])
154
 
155
- # Конвертируем Gradio-историю в наш внутренний формат
156
- internal_history = [{"role": "user", "content": h[0]} for h in history if h[0] is not None]
157
-
158
- trimmed_history = trim_history_to_max_tokens(internal_history, MAX_CONTEXT_TOKENS)
159
  messages_for_template = build_messages_for_template(trimmed_history, reasoning, language)
160
  template_content = CHAT_TEMPLATES.get(language, CHAT_TEMPLATES["en"])
161
 
162
- # Применяем шаблон и токенизируем
163
  text = tokenizer.apply_chat_template(
164
  messages_for_template,
165
  chat_template=template_content,
@@ -181,17 +187,19 @@ def generate_response(user_text: str, history, reasoning: bool, language: str):
181
 
182
  raw = tokenizer.decode(outputs[0], skip_special_tokens=False)
183
 
184
- # Извлекаем финальный ответ и ход мыслей
185
  reply, reasoning_text = extract_assistant_reply_and_reasoning(raw)
186
-
187
- # Обновляем историю Gradio с финальным ответом
188
- history[-1][1] = ""
189
 
190
- # Используем генератор для создания эффекта печати
 
 
 
 
 
191
  for chunk in reply.split():
192
- history[-1][1] += chunk + " "
193
- time.sleep(0.05) # Небольшая задержка для анимации
194
- yield "", history, reasoning_text
 
195
 
196
  # --- Интерфейс Gradio ---
197
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
@@ -248,4 +256,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
248
  )
249
 
250
  if __name__ == "__main__":
251
- demo.launch()
 
7
  # --- Конфигурация Hugging Face Space ---
8
  MODEL_NAME = "Kenan023214/PyroNet-mini"
9
  DEVICE = "cpu" # Используем CPU, как указано для Basic Space
10
+ MAX_NEW_TOKENS = 512 # Увеличим для "хода мыслей"
11
  MAX_CONTEXT_TOKENS = 2048
12
 
13
  # Словарь с встроенным содержимым шаблонов чата
 
102
  total = 0
103
  kept = []
104
  for m in rev:
105
+ if len(m) == 2:
106
+ approx = num_tokens_of_text(m[0]) + num_tokens_of_text(m[1] if m[1] else "") + 10
107
+ else:
108
+ approx = num_tokens_of_text(m[0]) + 10
109
+
110
  if total + approx > max_tokens:
111
  break
112
  kept.append(m)
113
  total += approx
114
  return list(reversed(kept))
115
 
116
+ def build_messages_for_template(history, reasoning: bool, language: str):
117
  """Подготавливает сообщения для шаблона, включая системное сообщение."""
118
  full_template_content = CHAT_TEMPLATES.get(language, CHAT_TEMPLATES["en"])
119
 
 
121
  system_end_tag = "<|end|>"
122
  system_message_raw = full_template_content.split(system_start_tag)[1].split(system_end_tag)[0].strip()
123
 
124
+ messages = [{"role": "system", "content": system_message_raw}]
125
+
126
+ for user_msg, assistant_msg in history:
127
+ messages.append({"role": "user", "content": user_msg})
128
+ if assistant_msg is not None:
129
+ messages.append({"role": "assistant", "content": assistant_msg})
130
 
131
  if reasoning:
132
  messages.append({"role": "user", "content": f"Режим рассуждения: покажи свои шаги, а затем окончательный ответ, начиная с '{REASONING_SEPARATOR}'"})
 
150
  reply = parts[1].strip()
151
  return reply, reasoning
152
  else:
153
+ # Если разделитель не найден, считаем весь текст ответом
154
+ # А ход мыслей оставляем пустым или с сообщением об отсутствии
155
+ return text, "Ход мыслей не предоставлен."
156
 
157
  # --- Основная функция для Gradio ---
158
  def generate_response(user_text: str, history, reasoning: bool, language: str):
159
  """
160
  Обрабатывает пользовательский запрос, генерирует ответ и возвращает его
161
+ с эффектом печати и отдельным отображением хода мыслей.
162
  """
 
163
  history.append([user_text, None])
164
 
165
+ trimmed_history = trim_history_to_max_tokens(history, MAX_CONTEXT_TOKENS)
 
 
 
166
  messages_for_template = build_messages_for_template(trimmed_history, reasoning, language)
167
  template_content = CHAT_TEMPLATES.get(language, CHAT_TEMPLATES["en"])
168
 
 
169
  text = tokenizer.apply_chat_template(
170
  messages_for_template,
171
  chat_template=template_content,
 
187
 
188
  raw = tokenizer.decode(outputs[0], skip_special_tokens=False)
189
 
 
190
  reply, reasoning_text = extract_assistant_reply_and_reasoning(raw)
 
 
 
191
 
192
+ # Сразу обновляем поле с ходом мыслей.
193
+ # Эта команда отправит обновление до начала анимации чата.
194
+ yield "", history, gr.Textbox.update(value=reasoning_text)
195
+
196
+ # Запускаем анимацию печати
197
+ full_response = ""
198
  for chunk in reply.split():
199
+ full_response += chunk + " "
200
+ history[-1][1] = full_response
201
+ time.sleep(0.05)
202
+ yield "", history, gr.Textbox.update(value=reasoning_text)
203
 
204
  # --- Интерфейс Gradio ---
205
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
 
256
  )
257
 
258
  if __name__ == "__main__":
259
+ demo.launch()