Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,13 +4,11 @@ from supabase import create_client, Client
|
|
| 4 |
import os
|
| 5 |
import uuid
|
| 6 |
|
| 7 |
-
# 1. CẤU HÌNH CORE
|
| 8 |
URL = os.environ.get("SUPABASE_URL")
|
| 9 |
KEY = os.environ.get("SUPABASE_KEY")
|
| 10 |
HF_TOKEN = os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
| 11 |
|
| 12 |
-
MASTER_ID = "lamgamepro"
|
| 13 |
-
|
| 14 |
try:
|
| 15 |
supabase: Client = create_client(URL, KEY) if URL and KEY else None
|
| 16 |
except:
|
|
@@ -18,118 +16,123 @@ except:
|
|
| 18 |
|
| 19 |
client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
|
| 20 |
|
| 21 |
-
# 2. HỆ THỐNG MEMORY
|
| 22 |
-
def get_db_history():
|
| 23 |
-
if not supabase
|
|
|
|
| 24 |
try:
|
| 25 |
-
res = supabase.table("chats").select("*").eq("username",
|
| 26 |
return res.data
|
| 27 |
-
except
|
| 28 |
-
print(f"Lỗi tải DB: {e}")
|
| 29 |
return []
|
| 30 |
|
| 31 |
-
def save_to_db(session_id, title, history):
|
| 32 |
-
|
|
|
|
|
|
|
| 33 |
try:
|
| 34 |
-
data = {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
supabase.table("chats").upsert(data, on_conflict="session_id").execute()
|
| 36 |
-
except
|
| 37 |
-
|
| 38 |
|
| 39 |
-
# 3. GIAO DIỆN
|
| 40 |
custom_css = """
|
| 41 |
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700&family=Plus+Jakarta+Sans:wght@400;600&display=swap');
|
| 42 |
-
|
| 43 |
-
.
|
| 44 |
-
.
|
| 45 |
-
.
|
| 46 |
-
.
|
| 47 |
-
.
|
| 48 |
-
footer { display: none !important; }
|
| 49 |
"""
|
| 50 |
|
| 51 |
-
|
| 52 |
-
def process_content(message):
|
| 53 |
text = message.get("text", "")
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
with open(f, "r", encoding="utf-8") as file:
|
| 61 |
-
combined_prompt += f"\n\n[FILE: {name}]\n{file.read()}"
|
| 62 |
-
except: pass
|
| 63 |
-
return combined_prompt
|
| 64 |
-
|
| 65 |
-
def chat_engine(message, history, session_id):
|
| 66 |
-
full_prompt = process_content(message)
|
| 67 |
-
if not full_prompt.strip():
|
| 68 |
-
yield gr.update(value={"text": "", "files": []}), history, session_id
|
| 69 |
-
return
|
| 70 |
-
|
| 71 |
-
messages = [{"role": "system", "content": "Bạn là NodeAI Genesis. Chuyên gia Roblox Studio và Web Development."}]
|
| 72 |
for msg in history:
|
| 73 |
messages.append({"role": msg["role"], "content": msg["content"]})
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# Gradio 6 dùng list of dicts mặc định
|
| 78 |
-
new_history = history + [{"role": "user", "content": message.get("text") or "Đã gửi tệp tin"}]
|
| 79 |
ans = ""
|
| 80 |
|
|
|
|
|
|
|
|
|
|
| 81 |
yield gr.update(value={"text": "", "files": []}), new_history + [{"role": "assistant", "content": "..."}], session_id
|
| 82 |
|
| 83 |
try:
|
| 84 |
for token in client.chat_completion(messages=messages, max_tokens=2048, stream=True):
|
| 85 |
if token.choices[0].delta.content:
|
| 86 |
ans += token.choices[0].delta.content
|
| 87 |
-
yield gr.update(), new_history + [{"role": "assistant", "content": ans}], session_id
|
| 88 |
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
| 90 |
except Exception as e:
|
| 91 |
yield gr.update(), new_history + [{"role": "assistant", "content": f"Lỗi: {str(e)}"}], session_id
|
| 92 |
|
| 93 |
-
#
|
| 94 |
-
with gr.Blocks(
|
| 95 |
session_id = gr.State(str(uuid.uuid4()))
|
| 96 |
db_state = gr.State([])
|
| 97 |
|
| 98 |
with gr.Row():
|
| 99 |
with gr.Column(scale=1, elem_classes="sidebar-node"):
|
| 100 |
gr.HTML("<div class='logo-area'>NODEAI GENESIS</div>")
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
gr.Markdown("### 🗄️ Database Memory")
|
| 103 |
|
|
|
|
|
|
|
| 104 |
@gr.render(inputs=[db_state])
|
| 105 |
-
def
|
| 106 |
with gr.Column():
|
| 107 |
-
for item in items
|
| 108 |
-
|
| 109 |
-
|
| 110 |
|
| 111 |
with gr.Column(scale=4):
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
demo.load(
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
).then(lambda: get_db_history(), None, db_state)
|
| 130 |
|
|
|
|
| 131 |
new_chat_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
|
| 132 |
|
| 133 |
if __name__ == "__main__":
|
| 134 |
-
# FIX: Chuyển css xuống launch()
|
| 135 |
demo.launch(css=custom_css)
|
|
|
|
| 4 |
import os
|
| 5 |
import uuid
|
| 6 |
|
| 7 |
+
# 1. CẤU HÌNH CORE
|
| 8 |
URL = os.environ.get("SUPABASE_URL")
|
| 9 |
KEY = os.environ.get("SUPABASE_KEY")
|
| 10 |
HF_TOKEN = os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
| 11 |
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
supabase: Client = create_client(URL, KEY) if URL and KEY else None
|
| 14 |
except:
|
|
|
|
| 16 |
|
| 17 |
client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
|
| 18 |
|
| 19 |
+
# 2. HỆ THỐNG MEMORY (Chỉ chạy khi có Profile)
|
| 20 |
+
def get_db_history(profile: gr.OAuthProfile | None):
|
| 21 |
+
if not supabase or not profile:
|
| 22 |
+
return []
|
| 23 |
try:
|
| 24 |
+
res = supabase.table("chats").select("*").eq("username", profile.username).order("created_at", desc=True).execute()
|
| 25 |
return res.data
|
| 26 |
+
except:
|
|
|
|
| 27 |
return []
|
| 28 |
|
| 29 |
+
def save_to_db(session_id, title, history, profile: gr.OAuthProfile | None):
|
| 30 |
+
# CHẶN LƯU: Nếu không có profile (chưa đăng nhập) thì thoát luôn
|
| 31 |
+
if not supabase or not profile or profile.username is None:
|
| 32 |
+
return
|
| 33 |
try:
|
| 34 |
+
data = {
|
| 35 |
+
"username": profile.username,
|
| 36 |
+
"session_id": session_id,
|
| 37 |
+
"title": title,
|
| 38 |
+
"history": history
|
| 39 |
+
}
|
| 40 |
supabase.table("chats").upsert(data, on_conflict="session_id").execute()
|
| 41 |
+
except:
|
| 42 |
+
pass
|
| 43 |
|
| 44 |
+
# 3. GIAO DIỆN
|
| 45 |
custom_css = """
|
| 46 |
@import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@700&family=Plus+Jakarta+Sans:wght@400;600&display=swap');
|
| 47 |
+
.gradio-container { background: radial-gradient(circle at 50% 0%, #0f172a 0%, #020617 100%) !important; color: #e2e8f0 !important; }
|
| 48 |
+
.sidebar-node { background: rgba(15, 23, 42, 0.8) !important; backdrop-filter: blur(15px); border-right: 1px solid #38bdf833; padding: 20px; overflow-y: auto; height: 100vh; }
|
| 49 |
+
.logo-area { font-family: 'Orbitron'; background: linear-gradient(90deg, #38bdf8, #818cf8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 22px; margin-bottom: 20px; text-align: center; }
|
| 50 |
+
.status-tag { font-size: 0.8em; padding: 5px 10px; border-radius: 20px; text-align: center; margin-bottom: 15px; }
|
| 51 |
+
.status-online { background: rgba(34, 197, 94, 0.2); color: #4ade80; border: 1px solid #22c55e44; }
|
| 52 |
+
.status-offline { background: rgba(239, 68, 68, 0.2); color: #f87171; border: 1px solid #ef444444; }
|
|
|
|
| 53 |
"""
|
| 54 |
|
| 55 |
+
def chat_engine(message, history, session_id, profile: gr.OAuthProfile | None):
|
|
|
|
| 56 |
text = message.get("text", "")
|
| 57 |
+
if not text.strip(): return gr.update(value={"text": "", "files": []}), history, session_id
|
| 58 |
+
|
| 59 |
+
# Xác định Master hay Khách
|
| 60 |
+
user_name = profile.username if profile else "Guest"
|
| 61 |
+
messages = [{"role": "system", "content": f"Bạn là NodeAI Genesis. Đang hỗ trợ: {user_name}."}]
|
| 62 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
for msg in history:
|
| 64 |
messages.append({"role": msg["role"], "content": msg["content"]})
|
| 65 |
+
messages.append({"role": "user", "content": text})
|
| 66 |
+
|
| 67 |
+
new_history = history + [{"role": "user", "content": text}]
|
|
|
|
|
|
|
| 68 |
ans = ""
|
| 69 |
|
| 70 |
+
# Hiển thị trạng thái lưu
|
| 71 |
+
save_status = "" if profile else "\n\n*(Lưu ý: Bạn chưa đăng nhập, lịch sử này sẽ mất khi tải lại trang)*"
|
| 72 |
+
|
| 73 |
yield gr.update(value={"text": "", "files": []}), new_history + [{"role": "assistant", "content": "..."}], session_id
|
| 74 |
|
| 75 |
try:
|
| 76 |
for token in client.chat_completion(messages=messages, max_tokens=2048, stream=True):
|
| 77 |
if token.choices[0].delta.content:
|
| 78 |
ans += token.choices[0].delta.content
|
| 79 |
+
yield gr.update(), new_history + [{"role": "assistant", "content": ans + (save_status if not token.choices[0].delta.content else "")}], session_id
|
| 80 |
|
| 81 |
+
# CHỈ LƯU VÀO DB KHI CÓ PROFILE
|
| 82 |
+
if profile:
|
| 83 |
+
save_to_db(session_id, text[:25], new_history + [{"role": "assistant", "content": ans}], profile)
|
| 84 |
+
|
| 85 |
except Exception as e:
|
| 86 |
yield gr.update(), new_history + [{"role": "assistant", "content": f"Lỗi: {str(e)}"}], session_id
|
| 87 |
|
| 88 |
+
# 4. UI
|
| 89 |
+
with gr.Blocks() as demo:
|
| 90 |
session_id = gr.State(str(uuid.uuid4()))
|
| 91 |
db_state = gr.State([])
|
| 92 |
|
| 93 |
with gr.Row():
|
| 94 |
with gr.Column(scale=1, elem_classes="sidebar-node"):
|
| 95 |
gr.HTML("<div class='logo-area'>NODEAI GENESIS</div>")
|
| 96 |
+
|
| 97 |
+
gr.LoginButton(value="Sign in with Hugging Face", size="sm")
|
| 98 |
+
|
| 99 |
+
# Hiển thị trạng thái đăng nhập trực quan
|
| 100 |
+
with gr.Group():
|
| 101 |
+
status_html = gr.HTML()
|
| 102 |
+
|
| 103 |
+
new_chat_btn = gr.Button("+ CHAT MỚI", variant="primary")
|
| 104 |
gr.Markdown("### 🗄️ Database Memory")
|
| 105 |
|
| 106 |
+
# Render danh sách lịch sử
|
| 107 |
+
history_box = gr.Column()
|
| 108 |
@gr.render(inputs=[db_state])
|
| 109 |
+
def show_history(items):
|
| 110 |
with gr.Column():
|
| 111 |
+
for item in items:
|
| 112 |
+
btn = gr.Button(f"◈ {item['title']}", variant="ghost")
|
| 113 |
+
btn.click(lambda h=item['history'], s=item['session_id']: (h, s), None, [chatbot, session_id])
|
| 114 |
|
| 115 |
with gr.Column(scale=4):
|
| 116 |
+
chatbot = gr.Chatbot(show_label=False, height="85vh")
|
| 117 |
+
msg_input = gr.MultimodalTextbox(show_label=False, placeholder="Hỏi NodeAI...", container=False)
|
| 118 |
+
|
| 119 |
+
# Logic khi tải trang / Đăng nhập
|
| 120 |
+
def check_user(profile: gr.OAuthProfile | None):
|
| 121 |
+
if profile:
|
| 122 |
+
msg = f"<div class='status-tag status-online'>● Online: {profile.username}</div>"
|
| 123 |
+
return msg, get_db_history(profile)
|
| 124 |
+
msg = "<div class='status-tag status-offline'>● Guest Mode (No Save)</div>"
|
| 125 |
+
return msg, []
|
| 126 |
+
|
| 127 |
+
demo.load(check_user, None, [status_html, db_state])
|
| 128 |
+
|
| 129 |
+
# Sự kiện chat
|
| 130 |
+
msg_input.submit(chat_engine, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id]).then(
|
| 131 |
+
lambda profile: get_db_history(profile) if profile else [], None, db_state
|
| 132 |
+
)
|
|
|
|
| 133 |
|
| 134 |
+
# Nút chat mới
|
| 135 |
new_chat_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
|
| 136 |
|
| 137 |
if __name__ == "__main__":
|
|
|
|
| 138 |
demo.launch(css=custom_css)
|