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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -64
app.py CHANGED
@@ -1,114 +1,94 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
 
4
 
5
- # 1. Khởi tạo Client với Qwen 2.5 (Ổn định và mạnh mẽ hơn cho Inference API)
6
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
7
- # Qwen/Qwen2.5-7B-Instruct là lựa chọn an toàn và Pro nhất hiện tại
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: 25px; border-radius: 12px; color: white; text-align: center;
14
- border: 1px solid #334155; margin-bottom: 20px;
 
 
 
15
  }
16
- .sidebar-box { background: #f8fafc; padding: 15px; border-radius: 10px; border: 1px solid #e2e8f0; }
17
  """
18
 
19
  def process_chat(message, history, session_memory, profile: gr.OAuthProfile | None):
20
- # Trích xuất nội dung tin nhắn
21
- if isinstance(message, dict):
22
- user_input = message.get("text", "")
23
- elif isinstance(message, list):
24
- user_input = message[-1]["content"][0]["text"]
25
- else:
26
- user_input = str(message)
27
 
28
  user_name = profile.name if profile else "Guest"
29
 
30
- # 2. AUTO-MEMORY LOGIC (Lưu trữ nội bộ)
31
- system_msg = f"Bạn là NodeAI Pro, một trợ lý AI cao cấp. Đang hỗ trợ {user_name}."
32
- if session_memory:
33
- system_msg += f" [Hệ thống nhớ]: {session_memory}"
34
 
35
  messages = [{"role": "system", "content": system_msg}]
36
-
37
- # Chuyển history sang định dạng API
38
- if history:
39
- for turn in history:
40
- role = turn["role"]
41
- # Đảm bảo lấy đúng text từ format phức tạp của Gradio 6
42
- content = turn["content"][0]["text"] if isinstance(turn["content"], list) else turn["content"]
43
- messages.append({"role": role, "content": content})
44
-
45
  messages.append({"role": "user", "content": user_input})
46
 
47
  try:
48
  full_response = ""
49
- # Gọi API với Qwen
50
- for token in client.chat_completion(messages=messages, max_tokens=1500, stream=True, temperature=0.7):
51
  delta = token.choices[0].delta.content
52
  if delta:
53
  full_response += delta
54
- # Cập nhật history theo chuẩn Gradio 6
55
- new_history = history + [
56
  {"role": "user", "content": [{"type": "text", "text": user_input}]},
57
  {"role": "assistant", "content": [{"type": "text", "text": full_response}]}
58
- ]
59
- yield "", new_history, session_memory
60
 
61
- # Tự động cập nhật bộ nhớ ẩn sau lượt chat
62
  if len(user_input) > 5:
63
- new_info = f"Người dùng quan tâm: {user_input[:40]}."
64
- session_memory = (session_memory + " " + new_info)[-500:] # Giữ 500 ký tự cuối
65
-
66
  except Exception as e:
67
- error_msg = f"❌ API Error: {str(e)}"
68
- yield "", history + [{"role": "assistant", "content": [{"type": "text", "text": error_msg}]}], session_memory
69
 
70
  with gr.Blocks(title="NodeAI Pro") as demo:
71
- # State lưu trữ Memory trong script
72
  internal_memory = gr.State("")
73
 
74
- gr.HTML("""
75
- <div class="header-node">
76
- <h1 style='margin:0'>NODE AI PRO</h1>
77
- <p style='margin:0; opacity: 0.7;'>Qwen-2.5 Neural Interface • Memory Enabled</p>
78
- </div>
79
- """)
80
 
81
  with gr.Row():
 
82
  with gr.Column(scale=1):
83
  with gr.Group():
84
- gr.Markdown("### 👤 Profile")
85
  login_btn = gr.LoginButton()
 
86
  @gr.render(inputs=login_btn)
87
- def render_user(profile: gr.OAuthProfile | None, *args):
88
  if profile:
89
- return gr.Markdown(f"✅ User: **{profile.name}**")
90
- return gr.Markdown("🌐 Mode: **Anonymous**")
 
 
 
 
 
 
91
 
92
- with gr.Group():
93
- gr.Markdown("### ⚙️ System")
94
- gr.Markdown(f"**Engine:** `Qwen-2.5-7B`")
95
- gr.Markdown("**Memory:** `Auto-Active` ✅")
96
-
97
- clear_btn = gr.Button("🗑️ Reset Session", variant="secondary")
98
-
99
- with gr.Column(scale=4):
100
- chatbot = gr.Chatbot(label="NodeAI Console", height=550)
101
 
 
 
 
102
  with gr.Row():
103
- msg_input = gr.Textbox(placeholder="Nhập yêu cầu...", show_label=False, scale=9)
104
  submit_btn = gr.Button("🚀", variant="primary", scale=1)
105
 
106
- # Xử lý sự kiện
107
- input_data = [msg_input, chatbot, internal_memory]
108
- output_data = [msg_input, chatbot, internal_memory]
109
-
110
- msg_input.submit(process_chat, input_data, output_data)
111
- submit_btn.click(process_chat, input_data, output_data)
112
  clear_btn.click(lambda: (None, [], ""), None, [msg_input, chatbot, internal_memory])
113
 
114
  if __name__ == "__main__":
 
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__":