lamgamepro1 commited on
Commit
0ca5b9d
·
verified ·
1 Parent(s): 51e9c00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -38
app.py CHANGED
@@ -4,12 +4,11 @@ import os
4
  import uuid
5
  import json
6
 
7
- # 1. CẤU HÌNH HỆ THỐNG
8
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
9
  client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
10
  DB_FILE = "nodeai_user_vault.json"
11
 
12
- # 2. QUẢN LÝ DỮ LIỆU THEO USER (DATABASE LOGIC)
13
  def load_vault():
14
  if os.path.exists(DB_FILE):
15
  try:
@@ -21,7 +20,7 @@ def save_vault(vault_data):
21
  with open(DB_FILE, "w", encoding="utf-8") as f:
22
  json.dump(vault_data, f, ensure_ascii=False, indent=4)
23
 
24
- # 3. GIAO DIỆN GLASSMORPHISM PLATINUM
25
  custom_css = """
26
  @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@800&family=Plus+Jakarta+Sans:wght@400;600&display=swap');
27
 
@@ -30,7 +29,7 @@ custom_css = """
30
  font-family: 'Plus Jakarta Sans', sans-serif !important;
31
  }
32
 
33
- /* Sidebar Pro */
34
  .sidebar-node {
35
  position: fixed !important;
36
  left: 0 !important; top: 0 !important;
@@ -50,7 +49,6 @@ custom_css = """
50
  font-size: 24px; text-align: center; margin-bottom: 25px;
51
  }
52
 
53
- /* Nút Workspace Màu Cam Cực Đẹp */
54
  .orange-btn {
55
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%) !important;
56
  border: none !important; color: white !important;
@@ -58,12 +56,13 @@ custom_css = """
58
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3) !important;
59
  }
60
 
61
- /* Khung Chat Chính */
62
  .chat-main {
63
  margin-left: 280px !important;
64
  width: calc(100% - 280px) !important;
65
  height: 100vh !important;
66
  padding: 0 20px !important;
 
67
  }
68
 
69
  .gr-chatbot {
@@ -71,7 +70,7 @@ custom_css = """
71
  height: 78vh !important; margin-bottom: 110px !important;
72
  }
73
 
74
- /* Thanh Nhập Liệu - Fix lỗi tràn màn hình */
75
  .input-fixed-bottom {
76
  position: fixed !important;
77
  bottom: 30px !important;
@@ -85,11 +84,11 @@ custom_css = """
85
  border-radius: 22px !important;
86
  padding: 5px 15px !important;
87
  z-index: 2000 !important;
 
88
  }
89
 
90
  footer { display: none !important; }
91
 
92
- /* Mobile Optimization */
93
  @media screen and (max-width: 768px) {
94
  .sidebar-node { display: none !important; }
95
  .chat-main { margin-left: 0 !important; width: 100% !important; }
@@ -97,13 +96,12 @@ footer { display: none !important; }
97
  }
98
  """
99
 
100
- # 4. XỬ LÝ CHAT THEO USERNAME
101
- def get_user_data(profile: gr.OAuthProfile | None):
102
- # Nếu chưa login, dùng tên mặc định 'Guest'
103
- return profile.username if profile else "Guest"
104
 
105
  def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
106
- username = get_user_data(profile)
107
  user_text = message.get("text", "")
108
  if not user_text: yield {"text": ""}, history, session_id, "" ; return
109
 
@@ -128,57 +126,68 @@ def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
128
  final_h = new_h + [{"role": "assistant", "content": ans}]
129
  vault[username][session_id]["history"] = final_h
130
  save_vault(vault)
 
131
  yield {"text": ""}, final_h, session_id, ans
132
  except Exception as e:
133
  yield {"text": ""}, history + [{"role": "assistant", "content": str(e)}], session_id, ""
134
 
135
- # 5. DỰNG GIAO DIỆN CÁ NHÂN HÓA
136
- with gr.Blocks(title="NodeAI Genesis v32.5", css=custom_css) as demo:
 
 
 
 
 
 
 
137
  session_id = gr.State(str(uuid.uuid4()))
138
  tts_buffer = gr.Textbox(visible=False)
 
 
139
 
140
  with gr.Row():
141
  # SIDEBAR
142
  with gr.Column(elem_classes="sidebar-node"):
143
  gr.HTML("<div class='logo-text'>NODEAI GENESIS</div>")
144
-
145
- # Nút đăng nhập chính chủ
146
- gr.LoginButton(value="Xác thực Nick")
147
-
148
  new_btn = gr.Button("+ NEW WORKSPACE", elem_classes="orange-btn")
149
 
150
  gr.Markdown("### 🕒 Lịch sử trò chuyện")
151
- history_area = gr.Column()
152
-
153
- @gr.render(inputs=history_area)
154
- def render_history(profile: gr.OAuthProfile | None):
155
- username = get_user_data(profile)
156
- vault = load_vault()
157
- user_chats = vault.get(username, {})
158
-
159
- for sid in reversed(list(user_chats.keys())):
160
- btn = gr.Button(f"◈ {user_chats[sid]['title']}", variant="ghost")
161
- # Khi bấm vào lịch sử, load lại đúng chat của sid đó
162
- btn.click(lambda s=sid, u=username: (load_vault()[u][s]["history"], s),
163
- None, [chatbot, session_id])
164
-
165
- # MAIN AREA
166
  with gr.Column(elem_classes="chat-main"):
167
  chatbot = gr.Chatbot(show_label=False, type="messages")
168
  audio_out = gr.Audio(autoplay=True, visible=False)
169
 
170
  with gr.Row(elem_classes="input-fixed-bottom"):
171
  msg_input = gr.MultimodalTextbox(
172
- show_label=False, placeholder="Nhập tin nhắn...", container=False
173
  )
174
 
175
  # EVENT HANDLERS
 
 
176
  msg_input.submit(
177
  chat_fn, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id, tts_buffer]
178
- ).then(lambda x: gr.update() if not x else gr.Audio(value=f"https://translate.google.com/translate_tts?ie=UTF-8&tl=vi&client=tw-ob&q={x}"),
179
- tts_buffer, audio_out)
 
 
 
180
 
181
  new_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
182
 
183
  if __name__ == "__main__":
184
- demo.launch()
 
 
4
  import uuid
5
  import json
6
 
7
+ # 1. HỆ THỐNG & MODEL
8
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
9
  client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
10
  DB_FILE = "nodeai_user_vault.json"
11
 
 
12
  def load_vault():
13
  if os.path.exists(DB_FILE):
14
  try:
 
20
  with open(DB_FILE, "w", encoding="utf-8") as f:
21
  json.dump(vault_data, f, ensure_ascii=False, indent=4)
22
 
23
+ # 2. GIAO DIỆN SIÊU CẤP (GLASSMORPHISM)
24
  custom_css = """
25
  @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@800&family=Plus+Jakarta+Sans:wght@400;600&display=swap');
26
 
 
29
  font-family: 'Plus Jakarta Sans', sans-serif !important;
30
  }
31
 
32
+ /* Sidebar */
33
  .sidebar-node {
34
  position: fixed !important;
35
  left: 0 !important; top: 0 !important;
 
49
  font-size: 24px; text-align: center; margin-bottom: 25px;
50
  }
51
 
 
52
  .orange-btn {
53
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%) !important;
54
  border: none !important; color: white !important;
 
56
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.3) !important;
57
  }
58
 
59
+ /* Chat Area */
60
  .chat-main {
61
  margin-left: 280px !important;
62
  width: calc(100% - 280px) !important;
63
  height: 100vh !important;
64
  padding: 0 20px !important;
65
+ box-sizing: border-box !important;
66
  }
67
 
68
  .gr-chatbot {
 
70
  height: 78vh !important; margin-bottom: 110px !important;
71
  }
72
 
73
+ /* Input Area Fixed */
74
  .input-fixed-bottom {
75
  position: fixed !important;
76
  bottom: 30px !important;
 
84
  border-radius: 22px !important;
85
  padding: 5px 15px !important;
86
  z-index: 2000 !important;
87
+ box-sizing: border-box !important;
88
  }
89
 
90
  footer { display: none !important; }
91
 
 
92
  @media screen and (max-width: 768px) {
93
  .sidebar-node { display: none !important; }
94
  .chat-main { margin-left: 0 !important; width: 100% !important; }
 
96
  }
97
  """
98
 
99
+ # 3. CORE LOGIC
100
+ def get_username(profile: gr.OAuthProfile | None):
101
+ return profile.username if profile else "Master_Phuc"
 
102
 
103
  def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
104
+ username = get_username(profile)
105
  user_text = message.get("text", "")
106
  if not user_text: yield {"text": ""}, history, session_id, "" ; return
107
 
 
126
  final_h = new_h + [{"role": "assistant", "content": ans}]
127
  vault[username][session_id]["history"] = final_h
128
  save_vault(vault)
129
+ # Trả về ans cuối cùng để đưa vào TTS
130
  yield {"text": ""}, final_h, session_id, ans
131
  except Exception as e:
132
  yield {"text": ""}, history + [{"role": "assistant", "content": str(e)}], session_id, ""
133
 
134
+ def tts_engine(text):
135
+ if not text or len(text) < 2: return None
136
+ try:
137
+ # Sử dụng API TTS của Google trực tiếp để tránh lỗi file
138
+ return f"https://translate.google.com/translate_tts?ie=UTF-8&tl=vi&client=tw-ob&q={text[:200]}"
139
+ except: return None
140
+
141
+ # 4. GIAO DIỆN
142
+ with gr.Blocks(title="NodeAI Genesis v32.6") as demo:
143
  session_id = gr.State(str(uuid.uuid4()))
144
  tts_buffer = gr.Textbox(visible=False)
145
+ # State để kích hoạt render lại lịch sử
146
+ vault_state = gr.State(load_vault())
147
 
148
  with gr.Row():
149
  # SIDEBAR
150
  with gr.Column(elem_classes="sidebar-node"):
151
  gr.HTML("<div class='logo-text'>NODEAI GENESIS</div>")
152
+ gr.LoginButton(value="Đăng nhập")
 
 
 
153
  new_btn = gr.Button("+ NEW WORKSPACE", elem_classes="orange-btn")
154
 
155
  gr.Markdown("### 🕒 Lịch sử trò chuyện")
156
+
157
+ # SỬA LỖI RENDER TẠI ĐÂY
158
+ @gr.render(inputs=[vault_state])
159
+ def render_history(current_vault, profile: gr.OAuthProfile | None):
160
+ username = get_username(profile)
161
+ user_chats = current_vault.get(username, {})
162
+ with gr.Column():
163
+ for sid in reversed(list(user_chats.keys())):
164
+ btn = gr.Button(f"◈ {user_chats[sid]['title']}", variant="ghost")
165
+ btn.click(lambda s=sid, u=username: (load_vault()[u][s]["history"], s),
166
+ None, [chatbot, session_id])
167
+
168
+ # MAIN
 
 
169
  with gr.Column(elem_classes="chat-main"):
170
  chatbot = gr.Chatbot(show_label=False, type="messages")
171
  audio_out = gr.Audio(autoplay=True, visible=False)
172
 
173
  with gr.Row(elem_classes="input-fixed-bottom"):
174
  msg_input = gr.MultimodalTextbox(
175
+ show_label=False, placeholder="Hỏi Master Phúc...", container=False
176
  )
177
 
178
  # EVENT HANDLERS
179
+ def update_vault(): return load_vault()
180
+
181
  msg_input.submit(
182
  chat_fn, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id, tts_buffer]
183
+ ).then(
184
+ update_vault, None, vault_state # Cập nhật lại state để sidebar render lại
185
+ ).then(
186
+ tts_engine, tts_buffer, audio_out
187
+ )
188
 
189
  new_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
190
 
191
  if __name__ == "__main__":
192
+ # CHUYỂN CSS VÀO ĐÂY ĐỂ FIX WARNING
193
+ demo.launch(css=custom_css)