vortex123 commited on
Commit
ababf7c
·
verified ·
1 Parent(s): 2e1a1b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -68
app.py CHANGED
@@ -3,29 +3,27 @@ from openai import OpenAI
3
 
4
  # Инициализация клиента DeepSeek
5
  client = OpenAI(
6
- api_key="sk-a02694cf3c8640c9ae60428ee2c5a62e", # <-- Вставьте свой ключ
7
  base_url="https://api.deepseek.com"
8
  )
9
 
10
  def chat_with_deepseek(user_message, history):
11
  """
12
- user_message: строка, введённая пользователем.
13
- history: список словарей [{"role":"user"|"assistant","content":"..."}],
14
- формат Gradio Chatbot (type="messages").
15
 
16
- Возвращает (new_history, new_history, ""), где:
17
- - new_history обновлённая история (чат) в формате messages
18
- - "" — чтобы очистить поле ввода
19
  """
20
- # Собираем сообщения из history
21
  messages = []
22
- for h in history:
23
- messages.append({"role": h["role"], "content": h["content"]})
24
-
25
  # Добавляем текущее сообщение пользователя
26
  messages.append({"role": "user", "content": user_message})
27
 
28
- # Запрос к deepseek-reasoner
29
  try:
30
  response = client.chat.completions.create(
31
  model="deepseek-reasoner",
@@ -40,10 +38,12 @@ def chat_with_deepseek(user_message, history):
40
  {"role": "user", "content": user_message},
41
  {"role": "assistant", "content": assistant_content}
42
  ]
43
- # Третий элемент возвращаем пустой для очистки поля ввода
44
  return new_history, new_history, ""
45
 
 
46
  with gr.Blocks(
 
47
  theme=gr.themes.Base(
48
  primary_hue="slate",
49
  secondary_hue="blue",
@@ -52,7 +52,7 @@ with gr.Blocks(
52
  font=["Arial", "sans-serif"]
53
  ),
54
  css="""
55
- /* Фон приложения чёрный */
56
  body {
57
  background-color: #000000 !important;
58
  }
@@ -62,22 +62,21 @@ with gr.Blocks(
62
  .gradio-container {
63
  color: #ffffff !important;
64
  }
65
- /* Фон области чата */
66
  #chatbot {
67
  background-color: #111111 !important;
68
  }
69
  """
70
  ) as demo:
71
 
72
- # Верхняя часть: "заголовок"
73
  gr.HTML("""
74
  <h1 style="text-align:center; color:#ffffff;">Чат с deepseek-reasoner</h1>
75
  <p style="text-align:center; color:#cccccc;">
76
- <b>Enter</b> отправить, <b>Ctrl+Enter</b> новая строка
77
  </p>
78
  """)
79
 
80
- # Сам чат: храним историю в формате messages (OpenAI-стиль)
81
  chatbot = gr.Chatbot(
82
  label="Диалог",
83
  height=400,
@@ -85,65 +84,24 @@ with gr.Blocks(
85
  elem_id="chatbot"
86
  )
87
 
88
- # Поле для ввода текста (многострочное)
 
 
 
89
  msg = gr.Textbox(
90
  label="Ваш вопрос",
91
- placeholder="Введите сообщение...",
92
- lines=2,
93
- elem_id="user_input",
94
- )
95
-
96
- # Скрытая кнопка: не отображается, но на неё будем "кликать" через JS
97
- hidden_send_btn = gr.Button(
98
- "Скрытая кнопка",
99
- visible=False,
100
- elem_id="hidden_send_btn"
101
  )
102
 
103
- # Храним историю чата
104
- state = gr.State([])
105
-
106
- # Логика при "клике" на скрытую кнопку
107
- hidden_send_btn.click(
108
  fn=chat_with_deepseek,
109
  inputs=[msg, state],
110
- outputs=[chatbot, state, msg], # msg получит ""
111
  scroll_to_output=True
112
  )
113
 
114
- # JavaScript-код:
115
- # При Enter — отправка (клик по hidden_send_btn)
116
- # При Ctrl+Enter — перенос строки
117
- custom_js = """
118
- <script>
119
- window.addEventListener('load', function() {
120
- const userInput = document.querySelector('#user_input textarea');
121
- const sendButton = document.querySelector('#hidden_send_btn button');
122
-
123
- if (userInput && sendButton) {
124
- userInput.addEventListener('keydown', function(e) {
125
- if (e.key === 'Enter') {
126
- if (e.ctrlKey) {
127
- // Ctrl+Enter => новая строка
128
- e.preventDefault();
129
- const start = userInput.selectionStart;
130
- const end = userInput.selectionEnd;
131
- userInput.value = userInput.value.substring(0, start) + "\\n"
132
- + userInput.value.substring(end);
133
- userInput.selectionStart = userInput.selectionEnd = start + 1;
134
- } else {
135
- // Enter => отправка
136
- e.preventDefault();
137
- sendButton.click();
138
- }
139
- }
140
- });
141
- }
142
- });
143
- </script>
144
- """
145
- gr.HTML(custom_js)
146
-
147
  # Запуск
148
  if __name__ == "__main__":
149
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
3
 
4
  # Инициализация клиента DeepSeek
5
  client = OpenAI(
6
+ api_key="sk-a02694cf3c8640c9ae60428ee2c5a62e", # <-- Замените на свой ключ
7
  base_url="https://api.deepseek.com"
8
  )
9
 
10
  def chat_with_deepseek(user_message, history):
11
  """
12
+ user_message: текст, введённый пользователем (str).
13
+ history: список словарей [{"role": "user"/"assistant", "content": "..."}],
14
+ в формате, ожидаемом Chatbot(type="messages").
15
 
16
+ Возвращает (new_history, new_history, ""),
17
+ где третий элемент очищает поле ввода.
 
18
  """
19
+ # Преобразуем историю в формат messages для модели:
20
  messages = []
21
+ for msg in history:
22
+ messages.append({"role": msg["role"], "content": msg["content"]})
 
23
  # Добавляем текущее сообщение пользователя
24
  messages.append({"role": "user", "content": user_message})
25
 
26
+ # Обращаемся к deepseek-reasoner
27
  try:
28
  response = client.chat.completions.create(
29
  model="deepseek-reasoner",
 
38
  {"role": "user", "content": user_message},
39
  {"role": "assistant", "content": assistant_content}
40
  ]
41
+ # Третий выход (пустая строка) очистит поле ввода
42
  return new_history, new_history, ""
43
 
44
+ # Создаём Gradio-приложение
45
  with gr.Blocks(
46
+ # Настраиваем тему и тёмное оформление
47
  theme=gr.themes.Base(
48
  primary_hue="slate",
49
  secondary_hue="blue",
 
52
  font=["Arial", "sans-serif"]
53
  ),
54
  css="""
55
+ /* Полностью чёрная тема */
56
  body {
57
  background-color: #000000 !important;
58
  }
 
62
  .gradio-container {
63
  color: #ffffff !important;
64
  }
 
65
  #chatbot {
66
  background-color: #111111 !important;
67
  }
68
  """
69
  ) as demo:
70
 
71
+ # Заголовок
72
  gr.HTML("""
73
  <h1 style="text-align:center; color:#ffffff;">Чат с deepseek-reasoner</h1>
74
  <p style="text-align:center; color:#cccccc;">
75
+ При нажатии Enter сообщение отправляется!
76
  </p>
77
  """)
78
 
79
+ # Чат (в формате "messages", чтобы избежать предупреждений Gradio)
80
  chatbot = gr.Chatbot(
81
  label="Диалог",
82
  height=400,
 
84
  elem_id="chatbot"
85
  )
86
 
87
+ # Храним историю в стейте (пустой список по умолчанию)
88
+ state = gr.State([])
89
+
90
+ # Поле ввода: Enter => отправка, т.к. lines=1
91
  msg = gr.Textbox(
92
  label="Ваш вопрос",
93
+ placeholder="Введите сообщение и нажмите Enter для отправки",
94
+ lines=1, # Однострочное поле
 
 
 
 
 
 
 
 
95
  )
96
 
97
+ # Привязываем отправку при нажатии Enter (submit)
98
+ msg.submit(
 
 
 
99
  fn=chat_with_deepseek,
100
  inputs=[msg, state],
101
+ outputs=[chatbot, state, msg], # msg = "" (очищается)
102
  scroll_to_output=True
103
  )
104
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
  # Запуск
106
  if __name__ == "__main__":
107
  demo.launch(server_name="0.0.0.0", server_port=7860)