AndrejsBoka commited on
Commit
859634b
·
verified ·
1 Parent(s): 62fbad1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -9
app.py CHANGED
@@ -7,14 +7,21 @@ generator = pipeline("text-generation", model="distilgpt2")
7
 
8
  # Функция для ответа "чат-бота"
9
  def chat(message, history):
10
- # берём последние сообщения из истории
11
  prompt = ""
12
- for user, bot in history:
13
- prompt += f"User: {user}\nBot: {bot}\n"
 
 
14
  prompt += f"User: {message}\nBot:"
15
 
16
- # генерируем ответ
17
- result = generator(prompt, max_length=200, num_return_sequences=1, pad_token_id=50256)
 
 
 
 
 
18
  reply = result[0]["generated_text"].split("Bot:")[-1].strip()
19
 
20
  return reply
@@ -22,16 +29,17 @@ def chat(message, history):
22
  # Интерфейс Gradio
23
  with gr.Blocks() as demo:
24
  gr.Markdown("## 🤖 Простой чат-бот на Hugging Face (distilgpt2)")
25
- chatbot = gr.Chatbot()
26
  msg = gr.Textbox(placeholder="Напиши сообщение и нажми Enter...")
27
 
28
  def respond(message, chat_history):
29
  bot_message = chat(message, chat_history)
30
- chat_history.append((message, bot_message))
 
31
  return "", chat_history
32
 
33
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
34
 
35
- # Запускаем
36
  if __name__ == "__main__":
37
- demo.launch()
 
7
 
8
  # Функция для ответа "чат-бота"
9
  def chat(message, history):
10
+ # Собираем промпт из истории
11
  prompt = ""
12
+ for msg in history:
13
+ role = msg["role"]
14
+ content = msg["content"]
15
+ prompt += f"{role}: {content}\n"
16
  prompt += f"User: {message}\nBot:"
17
 
18
+ # Генерация ответа
19
+ result = generator(
20
+ prompt,
21
+ max_length=200,
22
+ num_return_sequences=1,
23
+ pad_token_id=50256,
24
+ )
25
  reply = result[0]["generated_text"].split("Bot:")[-1].strip()
26
 
27
  return reply
 
29
  # Интерфейс Gradio
30
  with gr.Blocks() as demo:
31
  gr.Markdown("## 🤖 Простой чат-бот на Hugging Face (distilgpt2)")
32
+ chatbot = gr.Chatbot(type="messages")
33
  msg = gr.Textbox(placeholder="Напиши сообщение и нажми Enter...")
34
 
35
  def respond(message, chat_history):
36
  bot_message = chat(message, chat_history)
37
+ chat_history.append({"role": "user", "content": message})
38
+ chat_history.append({"role": "assistant", "content": bot_message})
39
  return "", chat_history
40
 
41
  msg.submit(respond, [msg, chatbot], [msg, chatbot])
42
 
43
+ # Запуск
44
  if __name__ == "__main__":
45
+ demo.launch()