lamgamepro1 commited on
Commit
3be7846
·
verified ·
1 Parent(s): 1a9a75b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -59
app.py CHANGED
@@ -3,97 +3,79 @@ from huggingface_hub import InferenceClient
3
  import os
4
  import uuid
5
 
6
- # 1. Cấu hình Model
7
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
8
  client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
9
 
10
  custom_css = """
11
- body, .gradio-container { background-color: #131314 !important; color: #e3e3e3 !important; }
12
- .sidebar { background-color: #1e1f20 !important; border-right: 1px solid #333 !important; height: 100vh; padding: 15px !important; }
13
- .gemini-title { color: #8ab4f8; font-size: 24px; font-weight: bold; margin-bottom: 20px; }
14
- .nav-btn { text-align: left !important; background: #333 !important; color: white !important; margin-bottom: 10px; border-radius: 20px !important; }
15
- .history-btn {
16
- width: 100%; text-align: left !important; background: transparent !important;
17
- border: none !important; color: #ccc !important; cursor: pointer; padding: 5px 10px !important;
18
- }
19
- .history-btn:hover { background: #2d2e30 !important; color: white !important; }
20
- .footer-tag { font-size: 0.75rem; color: #9aa0a6; text-align: center; margin-top: 15px; }
21
  """
22
 
23
- def chat_fn(message, history, session_id, chat_store):
24
- if not message: return "", history, session_id, chat_store
25
  user_text = message if isinstance(message, str) else message.get("text", "")
26
 
27
- # Gọi API
28
- messages = [{"role": "system", "content": "Bạn là NodeAI Pro phong cách Gemini."}]
 
 
 
29
  for turn in history:
30
- content = turn["content"][0]["text"] if isinstance(turn["content"], list) else turn["content"]
31
- messages.append({"role": turn["role"], "content": content})
32
- messages.append({"role": "user", "content": user_text})
33
 
34
  try:
35
- response_text = ""
36
  for token in client.chat_completion(messages=messages, max_tokens=1024, stream=True):
37
  delta = token.choices[0].delta.content
38
  if delta:
39
- response_text += delta
40
- current_history = history + [
41
  {"role": "user", "content": [{"type": "text", "text": user_text}]},
42
- {"role": "assistant", "content": [{"type": "text", "text": response_text}]}
43
  ]
44
- yield "", current_history, session_id, chat_store
45
-
46
- # LƯU TOÀN BỘ VÀO STORE
47
- chat_store[session_id] = {"title": user_text[:20] + "...", "data": current_history}
48
  except Exception as e:
49
- yield "", history + [{"role": "assistant", "content": [{"type": "text", "text": str(e)}]}], session_id, chat_store
50
-
51
- def load_old_chat(session_id_to_load, chat_store):
52
- # Lấy dữ liệu từ store dựa trên ID đã chọn
53
- old_data = chat_store.get(session_id_to_load, {}).get("data", [])
54
- return old_data, session_id_to_load
55
 
56
- def start_new_chat():
57
- return [], str(uuid.uuid4())
 
58
 
59
  with gr.Blocks(title="NodeAI Gemini") as demo:
60
  chat_store = gr.State({})
61
- session_id = gr.State(str(uuid.uuid4()))
62
 
63
  with gr.Row():
64
  # SIDEBAR
65
  with gr.Column(scale=1, elem_classes="sidebar"):
66
- gr.Markdown("Gemini", elem_classes="gemini-title")
67
- new_btn = gr.Button("+ Cuộc trò chuyện mới", elem_classes="nav-btn")
68
  gr.Markdown("---")
69
- gr.Markdown("### Gần đây")
70
 
71
- # Danh sách các nút lịch sử
72
- history_container = gr.Column()
73
-
74
  @gr.render(inputs=chat_store)
75
- def render_history(store):
76
- for sid, info in store.items():
77
- # Tạo một nút cho mỗi cuộc hội thoại cũ
78
- btn = gr.Button(f"🕒 {info['title']}", elem_classes="history-btn")
79
- # Khi nhấn vào nút này, load lại chat đó
80
- btn.click(load_old_chat, [gr.State(sid), chat_store], [chatbot, session_id])
81
-
82
- gr.Markdown("<div style='height: 30vh;'></div>")
83
- gr.LoginButton(size="sm")
84
 
85
- # MAIN
86
  with gr.Column(scale=4):
87
- chatbot = gr.Chatbot(label=None, height=600)
88
  with gr.Row():
89
- msg_input = gr.Textbox(placeholder="Nhập yêu cầu...", show_label=False, container=False, scale=9)
90
- submit_btn = gr.Button("🚀", scale=1, variant="primary")
91
- gr.Markdown("NodeAI Pro v4.5 | Powered by Qwen 2.5", elem_classes="footer-tag")
92
 
93
- # Xử lý
94
- msg_input.submit(chat_fn, [msg_input, chatbot, session_id, chat_store], [msg_input, chatbot, session_id, chat_store])
95
- submit_btn.click(chat_fn, [msg_input, chatbot, session_id, chat_store], [msg_input, chatbot, session_id, chat_store])
96
- new_btn.click(start_new_chat, None, [chatbot, session_id])
97
 
98
  if __name__ == "__main__":
99
  demo.launch(css=custom_css)
 
3
  import os
4
  import uuid
5
 
6
+ # 1. Khởi tạo
7
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
8
  client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
9
 
10
  custom_css = """
11
+ body, .gradio-container { background-color: #131314 !important; color: #eee !important; }
12
+ .sidebar { background-color: #1e1f20 !important; border-right: 1px solid #333 !important; padding: 15px !important; }
13
+ .nav-btn { background: #333 !important; color: white !important; border-radius: 20px !important; margin-bottom: 15px !important; }
14
+ .history-btn { text-align: left !important; background: transparent !important; border: none !important; color: #ccc !important; cursor: pointer; }
15
+ .history-btn:hover { background: #2d2e30 !important; }
 
 
 
 
 
16
  """
17
 
18
+ def chat_fn(message, history, current_id, chat_store):
19
+ if not message: return "", history, current_id, chat_store
20
  user_text = message if isinstance(message, str) else message.get("text", "")
21
 
22
+ # Cập nhật Store nếu là lần đầu chat trong phiên này
23
+ if not history:
24
+ chat_store[current_id] = {"title": user_text[:20] + "...", "data": []}
25
+
26
+ messages = [{"role": "user", "content": user_text}]
27
  for turn in history:
28
+ messages.insert(-1, {"role": turn["role"], "content": turn["content"][0]["text"]})
 
 
29
 
30
  try:
31
+ res = ""
32
  for token in client.chat_completion(messages=messages, max_tokens=1024, stream=True):
33
  delta = token.choices[0].delta.content
34
  if delta:
35
+ res += delta
36
+ new_history = history + [
37
  {"role": "user", "content": [{"type": "text", "text": user_text}]},
38
+ {"role": "assistant", "content": [{"type": "text", "text": res}]}
39
  ]
40
+ # Lưu dữ liệu vào bộ nhớ
41
+ chat_store[current_id]["data"] = new_history
42
+ yield "", new_history, current_id, chat_store
 
43
  except Exception as e:
44
+ yield "", history, current_id, chat_store
 
 
 
 
 
45
 
46
+ # Hàm để khi bấm vào nút cũ thì hiện lại chat
47
+ def load_chat(sid, store):
48
+ return store[sid]["data"], sid
49
 
50
  with gr.Blocks(title="NodeAI Gemini") as demo:
51
  chat_store = gr.State({})
52
+ current_id = gr.State(str(uuid.uuid4()))
53
 
54
  with gr.Row():
55
  # SIDEBAR
56
  with gr.Column(scale=1, elem_classes="sidebar"):
57
+ gr.Markdown("## Gemini")
58
+ new_btn = gr.Button("+ Trò chuyện mới", elem_classes="nav-btn")
59
  gr.Markdown("---")
 
60
 
61
+ # ��ÂY LÀ CHỖ TẠO NÚT
 
 
62
  @gr.render(inputs=chat_store)
63
+ def show_history(store):
64
+ for sid in store.keys():
65
+ btn = gr.Button(f"💬 {store[sid]['title']}", elem_classes="history-btn")
66
+ btn.click(load_chat, [gr.State(sid), chat_store], [chatbot, current_id])
 
 
 
 
 
67
 
68
+ # MAIN CHAT
69
  with gr.Column(scale=4):
70
+ chatbot = gr.Chatbot(height=600)
71
  with gr.Row():
72
+ msg_input = gr.Textbox(placeholder="Nhập tin nhắn...", show_label=False, scale=9)
73
+ submit_btn = gr.Button("🚀", scale=1)
 
74
 
75
+ # Logic
76
+ msg_input.submit(chat_fn, [msg_input, chatbot, current_id, chat_store], [msg_input, chatbot, current_id, chat_store])
77
+ submit_btn.click(chat_fn, [msg_input, chatbot, current_id, chat_store], [msg_input, chatbot, current_id, chat_store])
78
+ new_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, current_id])
79
 
80
  if __name__ == "__main__":
81
  demo.launch(css=custom_css)