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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -30
app.py CHANGED
@@ -1,32 +1,31 @@
1
  import gradio as gr
2
  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 — обновлённая история для Chatbot
18
  - "" — чтобы очистить поле ввода
19
  """
20
-
21
- # Преобразуем history в формат messages для DeepSeek
22
  messages = []
23
- for msg in history:
24
- messages.append({"role": msg["role"], "content": msg["content"]})
25
 
26
  # Добавляем текущее сообщение пользователя
27
  messages.append({"role": "user", "content": user_message})
28
 
29
- # Запрашиваем модель deepseek-reasoner
30
  try:
31
  response = client.chat.completions.create(
32
  model="deepseek-reasoner",
@@ -41,11 +40,10 @@ def chat_with_deepseek(user_message, history):
41
  {"role": "user", "content": user_message},
42
  {"role": "assistant", "content": assistant_content}
43
  ]
44
- # Третий элемент ("") очистит поле ввода
45
  return new_history, new_history, ""
46
 
47
  with gr.Blocks(
48
- # Тема Gradio:
49
  theme=gr.themes.Base(
50
  primary_hue="slate",
51
  secondary_hue="blue",
@@ -53,8 +51,8 @@ with gr.Blocks(
53
  text_size="md",
54
  font=["Arial", "sans-serif"]
55
  ),
56
- # CSS для чёрного оформления
57
  css="""
 
58
  body {
59
  background-color: #000000 !important;
60
  }
@@ -64,21 +62,22 @@ with gr.Blocks(
64
  .gradio-container {
65
  color: #ffffff !important;
66
  }
 
67
  #chatbot {
68
  background-color: #111111 !important;
69
  }
70
  """
71
  ) as demo:
72
 
73
- # Шапка
74
  gr.HTML("""
75
  <h1 style="text-align:center; color:#ffffff;">Чат с deepseek-reasoner</h1>
76
  <p style="text-align:center; color:#cccccc;">
77
- <b>Enter</b> — отправить; <b>Ctrl+Enter</b> — новая строка.
78
  </p>
79
  """)
80
 
81
- # Компонент чата, хранящего сообщения в формате "messages"
82
  chatbot = gr.Chatbot(
83
  label="Диалог",
84
  height=400,
@@ -86,47 +85,46 @@ with gr.Blocks(
86
  elem_id="chatbot"
87
  )
88
 
89
- # Текстовое поле (2 строки по умолчанию)
90
  msg = gr.Textbox(
91
  label="Ваш вопрос",
92
  placeholder="Введите сообщение...",
93
  lines=2,
94
- elem_id="user_input"
95
  )
96
 
97
- # Скрытая кнопка (не показываем в UI), которую мы будем "нажимать" программно
98
  hidden_send_btn = gr.Button(
99
- "Скрытая кнопка",
100
- visible=False,
101
  elem_id="hidden_send_btn"
102
  )
103
 
104
- # Состояние для истории чата
105
  state = gr.State([])
106
 
107
- # При клике на кнопку (вызванной JS), отправляем сообщение
108
  hidden_send_btn.click(
109
  fn=chat_with_deepseek,
110
  inputs=[msg, state],
111
- outputs=[chatbot, state, msg],
112
  scroll_to_output=True
113
  )
114
 
115
- # Подключаем JS, чтобы:
116
- # - Enter => нажимать на скрытую кнопку (отправлять сообщение)
117
- # - Ctrl+Enter => перенос строки
118
  custom_js = """
119
  <script>
120
- document.addEventListener('DOMContentLoaded', function() {
121
  const userInput = document.querySelector('#user_input textarea');
122
  const sendButton = document.querySelector('#hidden_send_btn button');
123
 
124
  if (userInput && sendButton) {
125
  userInput.addEventListener('keydown', function(e) {
126
  if (e.key === 'Enter') {
127
- // Если нажали Enter
128
  if (e.ctrlKey) {
129
- // Ctrl+Enter => перенос строки
130
  e.preventDefault();
131
  const start = userInput.selectionStart;
132
  const end = userInput.selectionEnd;
 
1
  import gradio as gr
2
  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
  {"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",
 
51
  text_size="md",
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
+ /* Фон области чата */
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
  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;