Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,33 +1,24 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import os
|
| 4 |
-
import json
|
| 5 |
-
from datetime import datetime
|
| 6 |
|
| 7 |
-
# 1. Cấu hình Model
|
| 8 |
HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 9 |
-
model_id = "meta-llama/Llama-3.2-
|
| 10 |
client = InferenceClient(model=model_id, token=HF_TOKEN)
|
| 11 |
|
| 12 |
-
# 2. CSS Pro
|
| 13 |
custom_css = """
|
| 14 |
-
.header-
|
| 15 |
-
background: linear-gradient(135deg, #
|
| 16 |
-
padding: 25px; border-radius:
|
| 17 |
-
|
| 18 |
-
.memory-box {
|
| 19 |
-
background: #f0f4ff; border-left: 5px solid #004e92; padding: 10px; border-radius: 5px;
|
| 20 |
-
}
|
| 21 |
-
.user-status {
|
| 22 |
-
font-weight: bold; color: #004e92;
|
| 23 |
}
|
|
|
|
| 24 |
"""
|
| 25 |
|
| 26 |
-
def
|
| 27 |
-
#
|
| 28 |
-
user_name = profile.name if profile else "Guest"
|
| 29 |
-
|
| 30 |
-
# Định dạng Input của Gradio 6.9.0
|
| 31 |
if isinstance(message, dict):
|
| 32 |
user_input = message.get("text", "")
|
| 33 |
elif isinstance(message, list):
|
|
@@ -35,106 +26,109 @@ def chat_fn(message, history, memory, profile: gr.OAuthProfile | None):
|
|
| 35 |
else:
|
| 36 |
user_input = str(message)
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
| 44 |
-
messages = [{"role": "system", "content": system_prompt}]
|
| 45 |
|
| 46 |
-
#
|
| 47 |
for turn in history:
|
| 48 |
-
role
|
| 49 |
-
content = turn["content"][0]["text"]
|
| 50 |
-
messages.append({"role": role, "content": content})
|
| 51 |
|
| 52 |
messages.append({"role": "user", "content": user_input})
|
| 53 |
|
| 54 |
-
# Gọi API
|
| 55 |
try:
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
return "⚠️ Vui lòng đăng nhập để lưu cuộc trò chuyện!"
|
| 74 |
-
|
| 75 |
-
filename = f"chat_history_{profile.name}.json"
|
| 76 |
-
with open(filename, "w", encoding="utf-8") as f:
|
| 77 |
-
json.dump(history, f, ensure_ascii=False, indent=4)
|
| 78 |
-
return f"✅ Đã lưu {len(history)//2} tin nhắn vào {filename}"
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
</div>
|
| 89 |
""")
|
| 90 |
|
| 91 |
with gr.Row():
|
| 92 |
-
#
|
| 93 |
with gr.Column(scale=1):
|
| 94 |
with gr.Group():
|
| 95 |
-
gr.Markdown("###
|
| 96 |
login_btn = gr.LoginButton()
|
| 97 |
|
| 98 |
-
#
|
| 99 |
@gr.render(inputs=login_btn)
|
| 100 |
-
def
|
| 101 |
-
if
|
| 102 |
-
return gr.Markdown(f"
|
| 103 |
-
return gr.Markdown("
|
| 104 |
|
| 105 |
with gr.Group():
|
| 106 |
-
gr.Markdown("### 🧠 AI
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
with gr.Row():
|
| 122 |
-
msg_input = gr.Textbox(
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
-
|
| 134 |
-
|
| 135 |
|
| 136 |
-
#
|
| 137 |
-
clear_btn.click(lambda: ([], ""), None, [chatbot,
|
| 138 |
|
| 139 |
if __name__ == "__main__":
|
| 140 |
-
demo.launch(
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
| 3 |
import os
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# 1. Cấu hình Model (Llama 3.2 3B cho phản hồi cực nhanh và thông minh)
|
| 6 |
HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
|
| 7 |
+
model_id = "meta-llama/Llama-3.2-3B-Instruct"
|
| 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 |
+
# Fix định dạng tin nhắn Gradio 6.9.0
|
|
|
|
|
|
|
|
|
|
| 22 |
if isinstance(message, dict):
|
| 23 |
user_input = message.get("text", "")
|
| 24 |
elif isinstance(message, list):
|
|
|
|
| 26 |
else:
|
| 27 |
user_input = str(message)
|
| 28 |
|
| 29 |
+
user_name = profile.name if profile else "khách"
|
| 30 |
+
|
| 31 |
+
# 3. LOGIC MEMORY NỘI BỘ (AI tự nhớ ngữ cảnh)
|
| 32 |
+
# Chúng ta đưa session_memory vào system prompt để AI luôn nhớ
|
| 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" Thông tin đã biết về cuộc trò chuyện này: {session_memory}"
|
| 36 |
|
| 37 |
+
messages = [{"role": "system", "content": system_msg}]
|
|
|
|
| 38 |
|
| 39 |
+
# Chuyển đổi history sang format của Inference API
|
| 40 |
for turn in history:
|
| 41 |
+
messages.append({"role": turn["role"], "content": turn["content"][0]["text"]})
|
|
|
|
|
|
|
| 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 |
+
content = token.choices[0].delta.content
|
| 50 |
+
if content:
|
| 51 |
+
full_response += content
|
| 52 |
+
yield "", history + [
|
| 53 |
+
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 54 |
+
{"role": "assistant", "content": [{"type": "text", "text": full_response}]}
|
| 55 |
+
], session_memory
|
| 56 |
+
|
| 57 |
+
# 4. TỰ ĐỘNG CẬP NHẬT MEMORY
|
| 58 |
+
# Sau mỗi câu trả lời, AI tự cập nhật lại 'session_memory' (ví dụ: tóm tắt ngắn gọn)
|
| 59 |
+
# Ở đây ta đơn giản là lưu lại một phần ngữ cảnh quan trọng nhất
|
| 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 |
+
yield "", history + [
|
| 66 |
+
{"role": "user", "content": [{"type": "text", "text": user_input}]},
|
| 67 |
+
{"role": "assistant", "content": [{"type": "text", "text": f"❌ Lỗi: {str(e)}"}]}
|
| 68 |
+
], session_memory
|
| 69 |
+
|
| 70 |
+
with gr.Blocks(title="NodeAI Pro", css=custom_css) as demo:
|
| 71 |
+
# Bộ nhớ ẩn trong Script
|
| 72 |
+
internal_memory = gr.State("")
|
| 73 |
+
|
| 74 |
+
gr.HTML("""
|
| 75 |
+
<div class="header-node">
|
| 76 |
+
<h1 style='margin:0; font-size: 2em;'>NODE AI PRO</h1>
|
| 77 |
+
<p style='margin:0; opacity: 0.7;'>Advanced Neural Interface • v3.0</p>
|
| 78 |
</div>
|
| 79 |
""")
|
| 80 |
|
| 81 |
with gr.Row():
|
| 82 |
+
# Sidebar
|
| 83 |
with gr.Column(scale=1):
|
| 84 |
with gr.Group():
|
| 85 |
+
gr.Markdown("### 🛡️ Authentication")
|
| 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"✅ Đã nhận diện: **{profile.name}**")
|
| 93 |
+
return gr.Markdown("⚠️ Chế độ khách (Không lưu lịch sử)")
|
| 94 |
|
| 95 |
with gr.Group():
|
| 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 |
+
chatbot = gr.Chatbot(
|
| 105 |
+
label="Neural Feed",
|
| 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 |
+
# Xử lý sự kiện
|
| 121 |
+
chat_event = {
|
| 122 |
+
"fn": process_chat,
|
| 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 |
+
# Reset bộ nhớ và chat
|
| 131 |
+
clear_btn.click(lambda: (None, [], ""), None, [msg_input, chatbot, internal_memory])
|
| 132 |
|
| 133 |
if __name__ == "__main__":
|
| 134 |
+
demo.launch()
|