Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ from supabase import create_client, Client
|
|
| 4 |
import os
|
| 5 |
import uuid
|
| 6 |
|
| 7 |
-
# 1.
|
| 8 |
URL = os.environ.get("SUPABASE_URL")
|
| 9 |
KEY = os.environ.get("SUPABASE_KEY")
|
| 10 |
HF_TOKEN = os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
|
@@ -16,11 +16,11 @@ except:
|
|
| 16 |
|
| 17 |
client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
|
| 18 |
|
| 19 |
-
# 2.
|
| 20 |
js_cleaner = """
|
| 21 |
<img src="x" onerror="
|
| 22 |
const observer = new MutationObserver(() => {
|
| 23 |
-
['footer', '.built-with', 'header', '#header', '.share-button'
|
| 24 |
const el = document.querySelector(s);
|
| 25 |
if (el) el.remove();
|
| 26 |
});
|
|
@@ -29,59 +29,72 @@ js_cleaner = """
|
|
| 29 |
" style="display:none;">
|
| 30 |
"""
|
| 31 |
|
| 32 |
-
# 3. GIAO DIỆN CSS
|
| 33 |
custom_css = """
|
| 34 |
-
footer, .built-with, header, #header { display: none !important;
|
| 35 |
.gradio-container { max-width: 100% !important; padding: 0 !important; }
|
| 36 |
-
.sidebar-node { background: rgba(15, 23, 42, 0.
|
| 37 |
.logo-area {
|
| 38 |
font-family: 'Orbitron', sans-serif;
|
| 39 |
background: linear-gradient(90deg, #38bdf8, #818cf8);
|
| 40 |
-
-webkit-background-clip: text;
|
| 41 |
-
-webkit-text-fill-color: transparent;
|
| 42 |
font-size: 22px; text-align: center; font-weight: bold; margin-bottom: 20px;
|
| 43 |
}
|
| 44 |
.custom-warning { text-align: center; color: #94a3b8; font-size: 12px; margin: 8px 0; font-style: italic; }
|
| 45 |
"""
|
| 46 |
|
| 47 |
-
#
|
| 48 |
def get_db_history(profile: gr.OAuthProfile | None):
|
| 49 |
if not supabase or not profile: return []
|
| 50 |
try:
|
| 51 |
-
res = supabase.table("chats").select("*").eq("username", profile.username).order("
|
| 52 |
return res.data
|
| 53 |
except: return []
|
| 54 |
|
| 55 |
def load_selected_chat(evt: gr.SelectData, db_data):
|
| 56 |
selected_item = db_data[evt.index]
|
|
|
|
| 57 |
return selected_item['history'], selected_item['session_id']
|
| 58 |
|
|
|
|
| 59 |
def chat_engine(message, history, session_id, profile: gr.OAuthProfile | None):
|
| 60 |
text = message.get("text", "").strip()
|
| 61 |
if not text: yield gr.update(value={"text": "", "files": []}), history, session_id; return
|
|
|
|
|
|
|
| 62 |
user_name = profile.username if profile else "Guest"
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
| 66 |
new_history = history + [{"role": "user", "content": text}]
|
| 67 |
ans = ""
|
|
|
|
| 68 |
yield gr.update(value={"text": "", "files": []}), new_history + [{"role": "assistant", "content": "..."}], session_id
|
|
|
|
| 69 |
try:
|
| 70 |
for token in client.chat_completion(messages=messages, max_tokens=2048, stream=True):
|
| 71 |
if token.choices[0].delta.content:
|
| 72 |
ans += token.choices[0].delta.content
|
| 73 |
yield gr.update(), new_history + [{"role": "assistant", "content": ans}], session_id
|
|
|
|
|
|
|
| 74 |
if profile:
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
supabase.table("chats").upsert(data, on_conflict="session_id").execute()
|
|
|
|
| 77 |
except Exception as e:
|
| 78 |
yield gr.update(), new_history + [{"role": "assistant", "content": f"Lỗi: {str(e)}"}], session_id
|
| 79 |
|
| 80 |
-
# 5. UI
|
| 81 |
-
with gr.Blocks() as demo:
|
| 82 |
-
# Chèn Script xóa Header/Footer thông qua HTML ẩn
|
| 83 |
gr.HTML(js_cleaner, visible=False)
|
| 84 |
-
|
| 85 |
session_id = gr.State(str(uuid.uuid4()))
|
| 86 |
db_state = gr.State([])
|
| 87 |
|
|
@@ -90,7 +103,7 @@ with gr.Blocks() as demo:
|
|
| 90 |
gr.HTML("<div class='logo-area'>NODEAI GENESIS</div>")
|
| 91 |
gr.LoginButton(value="Đăng nhập", size="sm")
|
| 92 |
new_chat_btn = gr.Button("+ WORKSPACE MỚI", variant="primary")
|
| 93 |
-
gr.Markdown("### 🗄️ Memory")
|
| 94 |
history_list = gr.Dataset(components=[gr.Textbox(visible=False)], samples=[], type="index")
|
| 95 |
|
| 96 |
with gr.Column(scale=4):
|
|
@@ -104,9 +117,15 @@ with gr.Blocks() as demo:
|
|
| 104 |
return data, gr.Dataset(samples=[[item['title']] for item in data])
|
| 105 |
|
| 106 |
demo.load(refresh_data, None, [db_state, history_list])
|
|
|
|
|
|
|
| 107 |
history_list.select(fn=load_selected_chat, inputs=[db_state], outputs=[chatbot, session_id])
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
new_chat_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
|
| 110 |
|
| 111 |
if __name__ == "__main__":
|
| 112 |
-
demo.queue().launch(
|
|
|
|
| 4 |
import os
|
| 5 |
import uuid
|
| 6 |
|
| 7 |
+
# 1. SETUP
|
| 8 |
URL = os.environ.get("SUPABASE_URL")
|
| 9 |
KEY = os.environ.get("SUPABASE_KEY")
|
| 10 |
HF_TOKEN = os.environ.get("HUGGINGFACE_HUB_TOKEN")
|
|
|
|
| 16 |
|
| 17 |
client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
|
| 18 |
|
| 19 |
+
# 2. JS & CSS (Xóa sạch Header/Footer)
|
| 20 |
js_cleaner = """
|
| 21 |
<img src="x" onerror="
|
| 22 |
const observer = new MutationObserver(() => {
|
| 23 |
+
['footer', '.built-with', 'header', '#header', '.share-button'].forEach(s => {
|
| 24 |
const el = document.querySelector(s);
|
| 25 |
if (el) el.remove();
|
| 26 |
});
|
|
|
|
| 29 |
" style="display:none;">
|
| 30 |
"""
|
| 31 |
|
|
|
|
| 32 |
custom_css = """
|
| 33 |
+
footer, .built-with, header, #header { display: none !important; }
|
| 34 |
.gradio-container { max-width: 100% !important; padding: 0 !important; }
|
| 35 |
+
.sidebar-node { background: rgba(15, 23, 42, 0.9) !important; border-right: 1px solid #38bdf833; padding: 20px; }
|
| 36 |
.logo-area {
|
| 37 |
font-family: 'Orbitron', sans-serif;
|
| 38 |
background: linear-gradient(90deg, #38bdf8, #818cf8);
|
| 39 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
|
|
|
| 40 |
font-size: 22px; text-align: center; font-weight: bold; margin-bottom: 20px;
|
| 41 |
}
|
| 42 |
.custom-warning { text-align: center; color: #94a3b8; font-size: 12px; margin: 8px 0; font-style: italic; }
|
| 43 |
"""
|
| 44 |
|
| 45 |
+
# 3. DATABASE LOGIC
|
| 46 |
def get_db_history(profile: gr.OAuthProfile | None):
|
| 47 |
if not supabase or not profile: return []
|
| 48 |
try:
|
| 49 |
+
res = supabase.table("chats").select("*").eq("username", profile.username).order("last_updated", desc=True).execute()
|
| 50 |
return res.data
|
| 51 |
except: return []
|
| 52 |
|
| 53 |
def load_selected_chat(evt: gr.SelectData, db_data):
|
| 54 |
selected_item = db_data[evt.index]
|
| 55 |
+
# Trả về lịch sử từ SQL và session_id tương ứng
|
| 56 |
return selected_item['history'], selected_item['session_id']
|
| 57 |
|
| 58 |
+
# 4. CHAT ENGINE (Đọc/Ghi Memory trực tiếp vào SQL)
|
| 59 |
def chat_engine(message, history, session_id, profile: gr.OAuthProfile | None):
|
| 60 |
text = message.get("text", "").strip()
|
| 61 |
if not text: yield gr.update(value={"text": "", "files": []}), history, session_id; return
|
| 62 |
+
|
| 63 |
+
# Cấu hình bối cảnh cho AI
|
| 64 |
user_name = profile.username if profile else "Guest"
|
| 65 |
+
system_msg = {"role": "system", "content": f"Bạn là NodeAI Genesis. Master: {user_name}."}
|
| 66 |
+
|
| 67 |
+
# Tạo prompt từ lịch sử (Memory)
|
| 68 |
+
messages = [system_msg] + history + [{"role": "user", "content": text}]
|
| 69 |
+
|
| 70 |
new_history = history + [{"role": "user", "content": text}]
|
| 71 |
ans = ""
|
| 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}], session_id
|
| 80 |
+
|
| 81 |
+
# LƯU VÀO SQL (Memory thực thụ)
|
| 82 |
if profile:
|
| 83 |
+
final_history = new_history + [{"role": "assistant", "content": ans}]
|
| 84 |
+
data = {
|
| 85 |
+
"username": profile.username,
|
| 86 |
+
"session_id": session_id,
|
| 87 |
+
"title": text[:30],
|
| 88 |
+
"history": final_history
|
| 89 |
+
}
|
| 90 |
supabase.table("chats").upsert(data, on_conflict="session_id").execute()
|
| 91 |
+
|
| 92 |
except Exception as e:
|
| 93 |
yield gr.update(), new_history + [{"role": "assistant", "content": f"Lỗi: {str(e)}"}], session_id
|
| 94 |
|
| 95 |
+
# 5. UI
|
| 96 |
+
with gr.Blocks(css=custom_css) as demo:
|
|
|
|
| 97 |
gr.HTML(js_cleaner, visible=False)
|
|
|
|
| 98 |
session_id = gr.State(str(uuid.uuid4()))
|
| 99 |
db_state = gr.State([])
|
| 100 |
|
|
|
|
| 103 |
gr.HTML("<div class='logo-area'>NODEAI GENESIS</div>")
|
| 104 |
gr.LoginButton(value="Đăng nhập", size="sm")
|
| 105 |
new_chat_btn = gr.Button("+ WORKSPACE MỚI", variant="primary")
|
| 106 |
+
gr.Markdown("### 🗄️ SQL Memory")
|
| 107 |
history_list = gr.Dataset(components=[gr.Textbox(visible=False)], samples=[], type="index")
|
| 108 |
|
| 109 |
with gr.Column(scale=4):
|
|
|
|
| 117 |
return data, gr.Dataset(samples=[[item['title']] for item in data])
|
| 118 |
|
| 119 |
demo.load(refresh_data, None, [db_state, history_list])
|
| 120 |
+
|
| 121 |
+
# Khi nhấn vào lịch sử, Chatbot sẽ hiển thị Memory từ SQL
|
| 122 |
history_list.select(fn=load_selected_chat, inputs=[db_state], outputs=[chatbot, session_id])
|
| 123 |
+
|
| 124 |
+
msg_input.submit(chat_engine, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id]).then(
|
| 125 |
+
refresh_data, None, [db_state, history_list]
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
new_chat_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
|
| 129 |
|
| 130 |
if __name__ == "__main__":
|
| 131 |
+
demo.queue().launch()
|