MrAlexGov commited on
Commit
b4c97ca
·
verified ·
1 Parent(s): 59c9796

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -21
app.py CHANGED
@@ -36,9 +36,9 @@ def load_model(model_key: str):
36
  model_cache = {}
37
 
38
  def respond(message: str,
39
- history: List[Dict[str, str]],
40
  model_key: str,
41
- system_prompt: str) -> Tuple[List[Dict[str, str]], str, Dict[str, Any]]:
42
  """Локальный чат с pipeline."""
43
  try:
44
  if model_key not in model_cache:
@@ -47,11 +47,16 @@ def respond(message: str,
47
 
48
  print(f"🚀 Генерация: {model_key}, Msg='{message[:30]}...'")
49
 
50
- # Chat format (system + history + user)
51
  messages = []
52
  if system_prompt.strip():
53
  messages.append({"role": "system", "content": system_prompt})
54
- messages.extend(history)
 
 
 
 
 
55
  messages.append({"role": "user", "content": message})
56
 
57
  # Apply chat template (для instruct)
@@ -64,38 +69,34 @@ def respond(message: str,
64
 
65
  print(f"✅ Ответ: {bot_reply[:50]}...")
66
 
67
- new_history = history + [
68
- {"role": "user", "content": message},
69
- {"role": "assistant", "content": bot_reply}
70
- ]
71
  return new_history, "", gr.update(value="")
72
 
73
  except Exception as e:
74
  error_msg = f"❌ {model_key}: {str(e)}"
75
  print(f"💥 {error_msg}")
76
- new_history = history + [
77
- {"role": "user", "content": message},
78
- {"role": "assistant", "content": error_msg}
79
- ]
80
  return new_history, error_msg, gr.update(value="")
81
 
82
- # UI - Убрал параметр theme из gr.Blocks()
83
  with gr.Blocks(title="🚀 Локальный HF Чат (на слабом CPU!)") as demo:
84
  gr.Markdown("# Локальный Inference (без API!)\n**Маленькие модели** — 1-3 сек CPU. Большие думают ооочень долго. Нет limits/token. В качестве примера.")
85
 
86
- with gr.Row(variant="compact"):
87
  model_dropdown = gr.Dropdown(choices=list(MODELS.keys()), value="Qwen2.5-0.5B", label="🧠 Модель")
88
  system_prompt = gr.Textbox(label="📝 System", placeholder="Ты весёлый ИИ.", lines=2)
89
 
90
- chatbot = gr.Chatbot(type="messages", height=500)
 
91
 
92
  with gr.Row():
93
- msg_input = gr.Textbox(placeholder="Привет! (Enter)", scale=7)
94
- send_btn = gr.Button("📤", variant="primary", scale=1)
95
 
96
  with gr.Row():
97
- clear_btn = gr.Button("🗑️ Clear")
98
- retry_btn = gr.Button("🔄 Retry")
99
 
100
  status = gr.Textbox(label="Логи", interactive=False, lines=4)
101
 
@@ -108,8 +109,8 @@ with gr.Blocks(title="🚀 Локальный HF Чат (на слабом CPU!)
108
  clear_btn.click(clear, outputs=[chatbot, status, msg_input])
109
 
110
  def retry(history):
111
- if len(history) >= 2 and history[-2]["role"] == "user":
112
- return history[-2]["content"]
113
  return ""
114
  retry_btn.click(retry, inputs=[chatbot], outputs=[msg_input])
115
 
 
36
  model_cache = {}
37
 
38
  def respond(message: str,
39
+ history: List[List[str]],
40
  model_key: str,
41
+ system_prompt: str) -> Tuple[List[List[str]], str, Dict[str, Any]]:
42
  """Локальный чат с pipeline."""
43
  try:
44
  if model_key not in model_cache:
 
47
 
48
  print(f"🚀 Генерация: {model_key}, Msg='{message[:30]}...'")
49
 
50
+ # Преобразуем формат истории из Gradio в формат сообщений
51
  messages = []
52
  if system_prompt.strip():
53
  messages.append({"role": "system", "content": system_prompt})
54
+
55
+ # Конвертируем историю из формата [["user_msg", "bot_msg"], ...]
56
+ for user_msg, bot_msg in history:
57
+ messages.append({"role": "user", "content": user_msg})
58
+ messages.append({"role": "assistant", "content": bot_msg})
59
+
60
  messages.append({"role": "user", "content": message})
61
 
62
  # Apply chat template (для instruct)
 
69
 
70
  print(f"✅ Ответ: {bot_reply[:50]}...")
71
 
72
+ # Обновляем историю в формате Gradio
73
+ new_history = history + [[message, bot_reply]]
 
 
74
  return new_history, "", gr.update(value="")
75
 
76
  except Exception as e:
77
  error_msg = f"❌ {model_key}: {str(e)}"
78
  print(f"💥 {error_msg}")
79
+ new_history = history + [[message, error_msg]]
 
 
 
80
  return new_history, error_msg, gr.update(value="")
81
 
82
+ # UI
83
  with gr.Blocks(title="🚀 Локальный HF Чат (на слабом CPU!)") as demo:
84
  gr.Markdown("# Локальный Inference (без API!)\n**Маленькие модели** — 1-3 сек CPU. Большие думают ооочень долго. Нет limits/token. В качестве примера.")
85
 
86
+ with gr.Row():
87
  model_dropdown = gr.Dropdown(choices=list(MODELS.keys()), value="Qwen2.5-0.5B", label="🧠 Модель")
88
  system_prompt = gr.Textbox(label="📝 System", placeholder="Ты весёлый ИИ.", lines=2)
89
 
90
+ # Убрал параметр type="messages" для совместимости со старой версией
91
+ chatbot = gr.Chatbot(height=500)
92
 
93
  with gr.Row():
94
+ msg_input = gr.Textbox(placeholder="Привет! (Enter)", show_label=False, lines=1)
95
+ send_btn = gr.Button("📤 Отправить", variant="primary")
96
 
97
  with gr.Row():
98
+ clear_btn = gr.Button("🗑️ Очистить")
99
+ retry_btn = gr.Button("🔄 Повторить")
100
 
101
  status = gr.Textbox(label="Логи", interactive=False, lines=4)
102
 
 
109
  clear_btn.click(clear, outputs=[chatbot, status, msg_input])
110
 
111
  def retry(history):
112
+ if len(history) >= 1:
113
+ return history[-1][0] # Последнее сообщение пользователя
114
  return ""
115
  retry_btn.click(retry, inputs=[chatbot], outputs=[msg_input])
116