Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,23 +2,20 @@ import gradio as gr
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import os
|
| 4 |
|
| 5 |
-
# 1.
|
| 6 |
HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 7 |
-
|
| 8 |
-
client = InferenceClient(model=model_id, token=HF_TOKEN)
|
| 9 |
|
| 10 |
-
# 2. CSS Pro: Giao diện tối tối giản, hiện đại
|
| 11 |
custom_css = """
|
| 12 |
.header-node {
|
| 13 |
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
|
| 14 |
padding: 25px; border-radius: 12px; color: white; text-align: center;
|
| 15 |
border: 1px solid #334155; margin-bottom: 20px;
|
| 16 |
}
|
| 17 |
-
.status-bar { font-size: 0.85em; padding: 5px 10px; border-radius: 20px; background: #f1f5f9; }
|
| 18 |
"""
|
| 19 |
|
| 20 |
def process_chat(message, history, session_memory, profile: gr.OAuthProfile | None):
|
| 21 |
-
#
|
| 22 |
if isinstance(message, dict):
|
| 23 |
user_input = message.get("text", "")
|
| 24 |
elif isinstance(message, list):
|
|
@@ -26,109 +23,89 @@ def process_chat(message, history, session_memory, profile: gr.OAuthProfile | No
|
|
| 26 |
else:
|
| 27 |
user_input = str(message)
|
| 28 |
|
| 29 |
-
user_name = profile.name if profile else "
|
| 30 |
|
| 31 |
-
#
|
| 32 |
-
|
| 33 |
-
system_msg = f"Bạn là NodeAI Pro, một trợ lý AI cao cấp. Bạn đang hỗ trợ {user_name}."
|
| 34 |
if session_memory:
|
| 35 |
-
system_msg += f"
|
| 36 |
|
| 37 |
messages = [{"role": "system", "content": system_msg}]
|
| 38 |
|
| 39 |
-
# Chuyển
|
| 40 |
for turn in history:
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
messages.append({"role": "user", "content": user_input})
|
| 44 |
|
| 45 |
try:
|
| 46 |
-
# Gọi API với streaming để Pro hơn
|
| 47 |
full_response = ""
|
|
|
|
| 48 |
for token in client.chat_completion(messages=messages, max_tokens=1024, stream=True):
|
| 49 |
-
|
| 50 |
-
if
|
| 51 |
-
full_response +=
|
| 52 |
-
|
|
|
|
| 53 |
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 54 |
{"role": "assistant", "content": [{"type": "text", "text": full_response}]}
|
| 55 |
-
]
|
|
|
|
| 56 |
|
| 57 |
-
#
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
if len(full_response) > 20:
|
| 61 |
-
new_memory = f"Người dùng vừa hỏi về '{user_input[:30]}...' và bạn đã trả lời."
|
| 62 |
-
session_memory = (session_memory + " " + new_memory)[-500:] # Giới hạn 500 ký tự cho memory
|
| 63 |
|
| 64 |
except Exception as e:
|
| 65 |
-
|
| 66 |
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 67 |
-
{"role": "assistant", "content": [{"type": "text", "text": f"❌
|
| 68 |
-
]
|
|
|
|
| 69 |
|
| 70 |
-
with gr.Blocks(title="NodeAI Pro"
|
| 71 |
-
# Bộ nhớ ẩn
|
| 72 |
internal_memory = gr.State("")
|
| 73 |
|
| 74 |
gr.HTML("""
|
| 75 |
<div class="header-node">
|
| 76 |
-
<h1 style='margin:0
|
| 77 |
-
<p style='margin:0; opacity: 0.7;'>
|
| 78 |
</div>
|
| 79 |
""")
|
| 80 |
|
| 81 |
with gr.Row():
|
| 82 |
-
# Sidebar
|
| 83 |
with gr.Column(scale=1):
|
| 84 |
with gr.Group():
|
| 85 |
-
gr.Markdown("### 🛡️
|
| 86 |
login_btn = gr.LoginButton()
|
| 87 |
-
|
| 88 |
-
# FIX LỖI 1 tham số vs 2 tham số bằng cách dùng *args
|
| 89 |
@gr.render(inputs=login_btn)
|
| 90 |
def render_user(profile: gr.OAuthProfile | None, *args):
|
| 91 |
if profile:
|
| 92 |
-
return gr.Markdown(f"
|
| 93 |
-
return gr.Markdown("
|
| 94 |
|
| 95 |
-
|
| 96 |
-
gr.Markdown("### 🧠 AI Analytics")
|
| 97 |
-
status = gr.Markdown("🟢 **Hệ thống:** Sẵn sàng")
|
| 98 |
-
mem_display = gr.Markdown("📜 **Bộ nhớ nội bộ:** Trống")
|
| 99 |
-
|
| 100 |
-
clear_btn = gr.Button("🗑️ Clear Session", variant="stop")
|
| 101 |
|
| 102 |
-
# Chat Box
|
| 103 |
with gr.Column(scale=4):
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
height=600,
|
| 107 |
-
show_copy_button=True,
|
| 108 |
-
bubble_full_width=False
|
| 109 |
-
)
|
| 110 |
|
| 111 |
with gr.Row():
|
| 112 |
-
msg_input = gr.Textbox(
|
| 113 |
-
placeholder="Nhập lệnh hoặc câu hỏi...",
|
| 114 |
-
show_label=False,
|
| 115 |
-
scale=9,
|
| 116 |
-
container=False
|
| 117 |
-
)
|
| 118 |
submit_btn = gr.Button("🚀", variant="primary", scale=1)
|
| 119 |
|
| 120 |
-
#
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
"inputs": [msg_input, chatbot, internal_memory],
|
| 124 |
-
"outputs": [msg_input, chatbot, internal_memory]
|
| 125 |
-
}
|
| 126 |
-
|
| 127 |
-
msg_input.submit(**chat_event)
|
| 128 |
-
submit_btn.click(**chat_event)
|
| 129 |
|
| 130 |
-
|
|
|
|
| 131 |
clear_btn.click(lambda: (None, [], ""), None, [msg_input, chatbot, internal_memory])
|
| 132 |
|
| 133 |
if __name__ == "__main__":
|
| 134 |
-
|
|
|
|
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import os
|
| 4 |
|
| 5 |
+
# 1. Khởi tạo Client (Sử dụng Llama-3.2-3B)
|
| 6 |
HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 7 |
+
client = InferenceClient(model="meta-llama/Llama-3.2-3B-Instruct", token=HF_TOKEN)
|
|
|
|
| 8 |
|
|
|
|
| 9 |
custom_css = """
|
| 10 |
.header-node {
|
| 11 |
background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
|
| 12 |
padding: 25px; border-radius: 12px; color: white; text-align: center;
|
| 13 |
border: 1px solid #334155; margin-bottom: 20px;
|
| 14 |
}
|
|
|
|
| 15 |
"""
|
| 16 |
|
| 17 |
def process_chat(message, history, session_memory, profile: gr.OAuthProfile | None):
|
| 18 |
+
# Trích xuất text từ định dạng Gradio 6
|
| 19 |
if isinstance(message, dict):
|
| 20 |
user_input = message.get("text", "")
|
| 21 |
elif isinstance(message, list):
|
|
|
|
| 23 |
else:
|
| 24 |
user_input = str(message)
|
| 25 |
|
| 26 |
+
user_name = profile.name if profile else "Guest"
|
| 27 |
|
| 28 |
+
# 2. INTERNAL MEMORY LOGIC
|
| 29 |
+
system_msg = f"Bạn là NodeAI Pro. Đang hỗ trợ {user_name}."
|
|
|
|
| 30 |
if session_memory:
|
| 31 |
+
system_msg += f" Bối cảnh quan trọng cần nhớ: {session_memory}"
|
| 32 |
|
| 33 |
messages = [{"role": "system", "content": system_msg}]
|
| 34 |
|
| 35 |
+
# Chuyển history sang API format
|
| 36 |
for turn in history:
|
| 37 |
+
# turn có dạng: {"role": "user", "content": [{"type": "text", "text": "..."}]}
|
| 38 |
+
role = turn["role"]
|
| 39 |
+
content = turn["content"][0]["text"]
|
| 40 |
+
messages.append({"role": role, "content": content})
|
| 41 |
|
| 42 |
messages.append({"role": "user", "content": user_input})
|
| 43 |
|
| 44 |
try:
|
|
|
|
| 45 |
full_response = ""
|
| 46 |
+
# Gọi API Streaming
|
| 47 |
for token in client.chat_completion(messages=messages, max_tokens=1024, stream=True):
|
| 48 |
+
delta = token.choices[0].delta.content
|
| 49 |
+
if delta:
|
| 50 |
+
full_response += delta
|
| 51 |
+
# Cập nhật history liên tục cho Gradio 6
|
| 52 |
+
current_history = history + [
|
| 53 |
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 54 |
{"role": "assistant", "content": [{"type": "text", "text": full_response}]}
|
| 55 |
+
]
|
| 56 |
+
yield "", current_history, session_memory
|
| 57 |
|
| 58 |
+
# Tự động tóm tắt hoặc lưu thông tin vào Memory ẩn
|
| 59 |
+
if len(user_input) > 10:
|
| 60 |
+
session_memory = f"{session_memory} | Người dùng quan tâm đến: {user_input[:50]}..."
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
except Exception as e:
|
| 63 |
+
error_history = history + [
|
| 64 |
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 65 |
+
{"role": "assistant", "content": [{"type": "text", "text": f"❌ Error: {str(e)}"}]}
|
| 66 |
+
]
|
| 67 |
+
yield "", error_history, session_memory
|
| 68 |
|
| 69 |
+
with gr.Blocks(title="NodeAI Pro") as demo:
|
| 70 |
+
# Bộ nhớ ẩn nội bộ
|
| 71 |
internal_memory = gr.State("")
|
| 72 |
|
| 73 |
gr.HTML("""
|
| 74 |
<div class="header-node">
|
| 75 |
+
<h1 style='margin:0'>NODE AI PRO</h1>
|
| 76 |
+
<p style='margin:0; opacity: 0.7;'>Neural Interface v3.1 • Memory Enabled</p>
|
| 77 |
</div>
|
| 78 |
""")
|
| 79 |
|
| 80 |
with gr.Row():
|
|
|
|
| 81 |
with gr.Column(scale=1):
|
| 82 |
with gr.Group():
|
| 83 |
+
gr.Markdown("### 🛡️ Secure Login")
|
| 84 |
login_btn = gr.LoginButton()
|
|
|
|
|
|
|
| 85 |
@gr.render(inputs=login_btn)
|
| 86 |
def render_user(profile: gr.OAuthProfile | None, *args):
|
| 87 |
if profile:
|
| 88 |
+
return gr.Markdown(f"👤 User: **{profile.name}**")
|
| 89 |
+
return gr.Markdown("🌐 Chế độ: **Ẩn danh**")
|
| 90 |
|
| 91 |
+
clear_btn = gr.Button("🗑️ Reset Chat", variant="secondary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
|
|
|
| 93 |
with gr.Column(scale=4):
|
| 94 |
+
# Chỉ giữ lại các tham số cơ bản nhất để tránh TypeError
|
| 95 |
+
chatbot = gr.Chatbot(label="NodeAI Neural Feed", height=550)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
with gr.Row():
|
| 98 |
+
msg_input = gr.Textbox(placeholder="Nhập lệnh...", show_label=False, scale=9)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
submit_btn = gr.Button("🚀", variant="primary", scale=1)
|
| 100 |
|
| 101 |
+
# Sự kiện
|
| 102 |
+
input_list = [msg_input, chatbot, internal_memory]
|
| 103 |
+
output_list = [msg_input, chatbot, internal_memory]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
msg_input.submit(process_chat, input_list, output_list)
|
| 106 |
+
submit_btn.click(process_chat, input_list, output_list)
|
| 107 |
clear_btn.click(lambda: (None, [], ""), None, [msg_input, chatbot, internal_memory])
|
| 108 |
|
| 109 |
if __name__ == "__main__":
|
| 110 |
+
# Đưa CSS vào đây để fix UserWarning
|
| 111 |
+
demo.launch(css=custom_css)
|