lamgamepro1 commited on
Commit
e615e91
·
verified ·
1 Parent(s): 2e4ec4d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -66
app.py CHANGED
@@ -1,95 +1,107 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
4
- import json
5
 
6
- # 1. Khởi tạo Client
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
- .header-node {
12
- background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
13
- padding: 20px; border-radius: 12px; color: white; text-align: center; margin-bottom: 20px;
14
- }
15
- .log-container {
16
- background: #1e293b; color: #34d399; font-family: 'Courier New', monospace;
17
- padding: 10px; border-radius: 8px; font-size: 0.85em; height: 150px; overflow-y: auto;
18
  }
 
 
19
  """
20
 
21
- def process_chat(message, history, session_memory, profile: gr.OAuthProfile | None):
22
- # Trích xuất nội dung
23
- if isinstance(message, dict): user_input = message.get("text", "")
24
- elif isinstance(message, list): user_input = message[-1]["content"][0]["text"]
25
- else: user_input = str(message)
26
-
27
- user_name = profile.name if profile else "Guest"
28
 
29
- # Logic Memory
30
- system_msg = f"Bạn là NodeAI Pro. Đang hỗ trợ {user_name}."
31
- if session_memory: system_msg += f" [Memory]: {session_memory}"
32
-
33
- messages = [{"role": "system", "content": system_msg}]
 
34
  for turn in history:
35
- messages.append({"role": turn["role"], "content": turn["content"][0]["text"]})
36
- messages.append({"role": "user", "content": user_input})
37
-
38
  try:
39
- full_response = ""
40
- for token in client.chat_completion(messages=messages, max_tokens=1500, stream=True):
41
  delta = token.choices[0].delta.content
42
  if delta:
43
  full_response += delta
44
- yield "", history + [
45
  {"role": "user", "content": [{"type": "text", "text": user_input}]},
46
  {"role": "assistant", "content": [{"type": "text", "text": full_response}]}
47
- ], session_memory
48
-
49
- # Cập nhật bộ nhớ sau khi chat
50
- if len(user_input) > 5:
51
- session_memory += f" | {user_name} hỏi về {user_input[:30]}"
52
  except Exception as e:
53
- yield "", history + [{"role": "assistant", "content": [{"type": "text", "text": f"Error: {str(e)}"}]}], session_memory
54
 
55
- with gr.Blocks(title="NodeAI Pro") as demo:
56
- internal_memory = gr.State("")
 
 
 
57
 
58
- gr.HTML("<div class='header-node'><h1>NODE AI PRO v3.3</h1><p>Persistent Memory & History Interface</p></div>")
 
59
 
 
 
 
 
 
60
  with gr.Row():
61
- # SIDEBAR: Chỉ hiện thị đầy đủ khi đã Login
62
- with gr.Column(scale=1):
63
- with gr.Group():
64
- gr.Markdown("### 👤 Tài khoản")
65
- login_btn = gr.LoginButton()
66
-
67
- @gr.render(inputs=login_btn)
68
- def render_history_panel(profile: gr.OAuthProfile | None, *args):
69
- if profile:
70
- gr.Markdown(f"👋 Chào, **{profile.name}**")
71
- with gr.Accordion("📂 Nhật ký phiên chat", open=True):
72
- # Hiển thị log bộ nhớ hiện tại
73
- gr.Markdown("**Dữ liệu bộ nhớ AI đang giữ:**")
74
- gr.HTML("<div class='log-container' id='mem-log'>Đang phân tích ngữ cảnh...</div>")
75
- save_btn = gr.Button("💾 Xuất file Lịch sử (.json)", size="sm")
76
- else:
77
- gr.Markdown("⚠️ Đăng nhập để kích hoạt bộ nhớ và lưu lịch sử.")
78
-
79
- clear_btn = gr.Button("🗑️ Xóa phiên chat", variant="secondary")
80
 
81
- # CHAT MAIN
82
- with gr.Column(scale=3):
83
- chatbot = gr.Chatbot(label="Neural Feed", height=500)
84
  with gr.Row():
85
- msg_input = gr.Textbox(placeholder="Gõ lệnh tại đây...", show_label=False, scale=9)
86
- submit_btn = gr.Button("🚀", variant="primary", scale=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
- # Xử lý Logic
89
- chat_args = {"fn": process_chat, "inputs": [msg_input, chatbot, internal_memory], "outputs": [msg_input, chatbot, internal_memory]}
90
- msg_input.submit(**chat_args)
91
- submit_btn.click(**chat_args)
92
- clear_btn.click(lambda: (None, [], ""), None, [msg_input, chatbot, internal_memory])
93
 
94
  if __name__ == "__main__":
95
- demo.launch(css=custom_css)
 
1
  import gradio as gr
2
  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
+ # 2. CSS để tạo giao diện giống Gemini
11
  custom_css = """
12
+ .sidebar { background-color: #1e1f20; border-right: 1px solid #333; padding: 10px; height: 100vh; }
13
+ .chat-container { background-color: #131314; color: white; }
14
+ .nav-item {
15
+ background: transparent; border: none; color: #e3e3e3; text-align: left;
16
+ width: 100%; padding: 10px; border-radius: 8px; cursor: pointer; margin-bottom: 5px;
 
 
17
  }
18
+ .nav-item:hover { background: #333; }
19
+ .gemini-header { color: #8ab4f8; font-weight: bold; font-size: 1.5rem; margin-bottom: 20px; }
20
  """
21
 
22
+ def chat_fn(message, history, current_chat_id, all_chats):
23
+ if not message: return "", history, current_chat_id, all_chats
 
 
 
 
 
24
 
25
+ # Trích xuất text
26
+ user_input = message if isinstance(message, str) else message.get("text", "")
27
+
28
+ # Gửi API
29
+ messages = [{"role": "user", "content": user_input}]
30
+ # Thêm ngữ cảnh cũ nếu có
31
  for turn in history:
32
+ messages.insert(-1, {"role": turn["role"], "content": turn["content"][0]["text"]})
33
+
34
+ full_response = ""
35
  try:
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
  full_response += delta
40
+ current_history = history + [
41
  {"role": "user", "content": [{"type": "text", "text": user_input}]},
42
  {"role": "assistant", "content": [{"type": "text", "text": full_response}]}
43
+ ]
44
+ yield "", current_history, current_chat_id, all_chats
 
 
 
45
  except Exception as e:
46
+ yield "", history + [{"role": "assistant", "content": [{"type": "text", "text": str(e)}]}], current_chat_id, all_chats
47
 
48
+ # Cập nhật danh sách cuộc trò chuyện ở Sidebar nếu là tin nhắn đầu tiên
49
+ if len(history) == 0:
50
+ all_chats[current_chat_id] = user_input[:20] + "..."
51
+
52
+ return "", current_history, current_chat_id, all_chats
53
 
54
+ def new_chat():
55
+ return [], str(uuid.uuid4()), gr.update()
56
 
57
+ with gr.Blocks(css=custom_css, title="NodeAI Gemini") as demo:
58
+ # State quản lý dữ liệu
59
+ all_chats = gr.State({}) # Lưu {id: title}
60
+ current_chat_id = gr.State(str(uuid.uuid4()))
61
+
62
  with gr.Row():
63
+ # SIDEBAR (Giống Gemini)
64
+ with gr.Column(scale=1, elem_classes="sidebar"):
65
+ gr.Markdown("### Gemini", elem_classes="gemini-header")
66
+ new_btn = gr.Button("+ Cuộc trò chuyện mới", variant="secondary")
67
+ gr.Markdown("---")
68
+ gr.Markdown("**Gần đây**")
69
+
70
+ # Khu vực hiển thị danh sách chat
71
+ chat_list_display = gr.HTML("<i>Chưa có cuộc hội thoại nào</i>")
72
+
73
+ # Cập nhật sidebar khi có chat mới
74
+ def update_sidebar(chats):
75
+ html = "".join([f'<div class="nav-item">💬 {title}</div>' for title in chats.values()])
76
+ return html if html else "<i>Chưa có cuộc hội thoại nào</i>"
77
+
78
+ # MAIN CHAT AREA
79
+ with gr.Column(scale=4, elem_classes="chat-container"):
80
+ chatbot = gr.Chatbot(label="", height=650, type="messages")
 
81
 
 
 
 
82
  with gr.Row():
83
+ msg_input = gr.Textbox(
84
+ placeholder="Hỏi NodeAI...",
85
+ show_label=False,
86
+ container=False,
87
+ scale=9
88
+ )
89
+ submit_btn = gr.Button("🚀", scale=1)
90
+
91
+ # Logic xử lý
92
+ msg_input.submit(
93
+ chat_fn,
94
+ [msg_input, chatbot, current_chat_id, all_chats],
95
+ [msg_input, chatbot, current_chat_id, all_chats]
96
+ ).then(update_sidebar, all_chats, chat_list_display)
97
+
98
+ submit_btn.click(
99
+ chat_fn,
100
+ [msg_input, chatbot, current_chat_id, all_chats],
101
+ [msg_input, chatbot, current_chat_id, all_chats]
102
+ ).then(update_sidebar, all_chats, chat_list_display)
103
 
104
+ new_btn.click(new_chat, None, [chatbot, current_chat_id, chat_list_display])
 
 
 
 
105
 
106
  if __name__ == "__main__":
107
+ demo.launch()