Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,9 +2,10 @@ import gradio as gr
|
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import os
|
| 4 |
|
| 5 |
-
# 1. Khởi tạo Client
|
| 6 |
HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
custom_css = """
|
| 10 |
.header-node {
|
|
@@ -12,10 +13,11 @@ custom_css = """
|
|
| 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
|
| 19 |
if isinstance(message, dict):
|
| 20 |
user_input = message.get("text", "")
|
| 21 |
elif isinstance(message, list):
|
|
@@ -25,87 +27,89 @@ def process_chat(message, history, session_memory, profile: gr.OAuthProfile | No
|
|
| 25 |
|
| 26 |
user_name = profile.name if profile else "Guest"
|
| 27 |
|
| 28 |
-
# 2.
|
| 29 |
-
system_msg = f"Bạn là NodeAI Pro. Đang hỗ trợ {user_name}."
|
| 30 |
if session_memory:
|
| 31 |
-
system_msg += f"
|
| 32 |
|
| 33 |
messages = [{"role": "system", "content": system_msg}]
|
| 34 |
|
| 35 |
-
# Chuyển history sang
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
|
| 42 |
messages.append({"role": "user", "content": user_input})
|
| 43 |
|
| 44 |
try:
|
| 45 |
full_response = ""
|
| 46 |
-
# Gọi API
|
| 47 |
-
for token in client.chat_completion(messages=messages, max_tokens=
|
| 48 |
delta = token.choices[0].delta.content
|
| 49 |
if delta:
|
| 50 |
full_response += delta
|
| 51 |
-
# Cập nhật history
|
| 52 |
-
|
| 53 |
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 54 |
{"role": "assistant", "content": [{"type": "text", "text": full_response}]}
|
| 55 |
]
|
| 56 |
-
yield "",
|
| 57 |
|
| 58 |
-
# Tự động
|
| 59 |
-
if len(user_input) >
|
| 60 |
-
|
|
|
|
| 61 |
|
| 62 |
except Exception as e:
|
| 63 |
-
|
| 64 |
-
|
| 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 |
-
#
|
| 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
|
| 77 |
</div>
|
| 78 |
""")
|
| 79 |
|
| 80 |
with gr.Row():
|
| 81 |
with gr.Column(scale=1):
|
| 82 |
with gr.Group():
|
| 83 |
-
gr.Markdown("###
|
| 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"
|
| 89 |
-
return gr.Markdown("🌐
|
| 90 |
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
with gr.Column(scale=4):
|
| 94 |
-
|
| 95 |
-
chatbot = gr.Chatbot(label="NodeAI Neural Feed", height=550)
|
| 96 |
|
| 97 |
with gr.Row():
|
| 98 |
-
msg_input = gr.Textbox(placeholder="Nhập
|
| 99 |
submit_btn = gr.Button("🚀", variant="primary", scale=1)
|
| 100 |
|
| 101 |
-
#
|
| 102 |
-
|
| 103 |
-
|
| 104 |
|
| 105 |
-
msg_input.submit(process_chat,
|
| 106 |
-
submit_btn.click(process_chat,
|
| 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)
|
|
|
|
| 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 {
|
|
|
|
| 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):
|
|
|
|
| 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__":
|
|
|
|
| 115 |
demo.launch(css=custom_css)
|