lamgamepro1 commited on
Commit
ff9bb9f
·
verified ·
1 Parent(s): 9c11e8b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -111
app.py CHANGED
@@ -16,83 +16,41 @@ except:
16
 
17
  client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
18
 
19
- # 2. JAVASCRIPT "DIỆT" TẬN GỐC (Xóa thành phần ngay khi nó vừa xuất hiện)
20
- head_js = """
21
- <script>
22
  const observer = new MutationObserver(() => {
23
- // Danh sách các thành phần cần xóa bỏ
24
- const targets = [
25
- 'footer',
26
- '.built-with',
27
- 'header',
28
- '#header',
29
- '.share-button',
30
- '.gr-pro',
31
- '#component-10' // ID thường thấy của footer trong Gradio 6
32
- ];
33
-
34
- targets.forEach(selector => {
35
- const el = document.querySelector(selector);
36
  if (el) el.remove();
37
  });
38
  });
39
-
40
  observer.observe(document.body, { childList: true, subtree: true });
41
- </script>
42
  """
43
 
44
- # 3. GIAO DIỆN CSS (Ẩn trước khi JS kịp xóa)
45
  custom_css = """
46
- /* Ẩn triệt để footer và header */
47
- footer, .built-with, header, #header, .share-button {
48
- display: none !important;
49
- visibility: hidden !important;
50
- }
51
-
52
- /* Cấu hình tràn viền hoàn toàn */
53
- .gradio-container {
54
- max-width: 100% !important;
55
- padding: 0 !important;
56
- background: radial-gradient(circle at 50% 0%, #0f172a 0%, #020617 100%) !important;
57
- }
58
-
59
- /* Sidebar & UI phong cách NodeAI */
60
- .sidebar-node {
61
- background: rgba(15, 23, 42, 0.8) !important;
62
- border-right: 1px solid #38bdf833;
63
- padding: 20px;
64
- }
65
-
66
  .logo-area {
67
  font-family: 'Orbitron', sans-serif;
68
  background: linear-gradient(90deg, #38bdf8, #818cf8);
69
  -webkit-background-clip: text;
70
  -webkit-text-fill-color: transparent;
71
- font-size: 22px;
72
- text-align: center;
73
- font-weight: bold;
74
- margin-bottom: 20px;
75
- }
76
-
77
- .custom-warning {
78
- text-align: center;
79
- color: #94a3b8;
80
- font-size: 12px;
81
- margin-top: 8px;
82
- margin-bottom: 8px;
83
- font-style: italic;
84
- font-family: sans-serif;
85
  }
 
86
  """
87
 
88
- # 4. LOGIC XỬ LÝ DỮ LIỆU
89
  def get_db_history(profile: gr.OAuthProfile | None):
90
  if not supabase or not profile: return []
91
  try:
92
  res = supabase.table("chats").select("*").eq("username", profile.username).order("created_at", desc=True).execute()
93
  return res.data
94
- except:
95
- return []
96
 
97
  def load_selected_chat(evt: gr.SelectData, db_data):
98
  selected_item = db_data[evt.index]
@@ -100,93 +58,54 @@ def load_selected_chat(evt: gr.SelectData, db_data):
100
 
101
  def chat_engine(message, history, session_id, profile: gr.OAuthProfile | None):
102
  text = message.get("text", "").strip()
103
- if not text:
104
- yield gr.update(value={"text": "", "files": []}), history, session_id
105
- return
106
-
107
  user_name = profile.username if profile else "Guest"
108
- messages = [{"role": "system", "content": f"Bạn là NodeAI Genesis. Master: {user_name}. Phản hồi bằng tiếng Việt."}]
109
-
110
- for msg in history:
111
- messages.append({"role": msg["role"], "content": msg["content"]})
112
  messages.append({"role": "user", "content": text})
113
-
114
  new_history = history + [{"role": "user", "content": text}]
115
  ans = ""
116
-
117
  yield gr.update(value={"text": "", "files": []}), new_history + [{"role": "assistant", "content": "..."}], session_id
118
-
119
  try:
120
  for token in client.chat_completion(messages=messages, max_tokens=2048, stream=True):
121
  if token.choices[0].delta.content:
122
  ans += token.choices[0].delta.content
123
  yield gr.update(), new_history + [{"role": "assistant", "content": ans}], session_id
124
-
125
  if profile:
126
- data = {
127
- "username": profile.username,
128
- "session_id": session_id,
129
- "title": text[:30],
130
- "history": new_history + [{"role": "assistant", "content": ans}]
131
- }
132
  supabase.table("chats").upsert(data, on_conflict="session_id").execute()
133
  except Exception as e:
134
  yield gr.update(), new_history + [{"role": "assistant", "content": f"Lỗi: {str(e)}"}], session_id
135
 
136
- # 5. XÂY DỰNG UI VỚI HEAD SCRIPT
137
- with gr.Blocks(head=head_js) as demo:
 
 
 
138
  session_id = gr.State(str(uuid.uuid4()))
139
  db_state = gr.State([])
140
 
141
  with gr.Row():
142
- # Sidebar
143
  with gr.Column(scale=1, elem_classes="sidebar-node"):
144
  gr.HTML("<div class='logo-area'>NODEAI GENESIS</div>")
145
- gr.LoginButton(value="Đăng nhập Hugging Face", size="sm")
146
  new_chat_btn = gr.Button("+ WORKSPACE MỚI", variant="primary")
147
-
148
- gr.Markdown("### 🗄️ Database Memory")
149
- history_list = gr.Dataset(
150
- components=[gr.Textbox(visible=False)],
151
- label="Lịch sử chat",
152
- samples=[],
153
- type="index"
154
- )
155
 
156
- # Main Chat Area
157
  with gr.Column(scale=4):
158
  chatbot = gr.Chatbot(show_label=False, height="76vh")
159
-
160
- # Dòng cảnh báo Master yêu cầu
161
- gr.HTML("<div class='custom-warning'>"
162
- "NodeAI không thể chắc chắn 100%, hãy rà soát lại khi bạn có chuyện gì quan trọng!"
163
- "</div>")
164
-
165
- msg_input = gr.MultimodalTextbox(
166
- show_label=False,
167
- placeholder="Hỏi NodeAI hoặc dán code Roblox...",
168
- container=False
169
- )
170
 
171
- # 6. ĐIỀU KHIỂN SỰ KIỆN
172
  def refresh_data(profile: gr.OAuthProfile | None):
173
  if not profile: return [], gr.Dataset(samples=[])
174
  data = get_db_history(profile)
175
- samples = [[item['title']] for item in data]
176
- return data, gr.Dataset(samples=samples)
177
 
178
  demo.load(refresh_data, None, [db_state, history_list])
179
-
180
  history_list.select(fn=load_selected_chat, inputs=[db_state], outputs=[chatbot, session_id])
181
-
182
- msg_input.submit(
183
- chat_engine,
184
- [msg_input, chatbot, session_id],
185
- [msg_input, chatbot, session_id]
186
- ).then(
187
- refresh_data, None, [db_state, history_list]
188
- )
189
-
190
  new_chat_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
191
 
192
  if __name__ == "__main__":
 
16
 
17
  client = InferenceClient(model="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN)
18
 
19
+ # 2. JAVASCRIPT "DIỆT" TẬN GỐC (Dạng chuỗi HTML)
20
+ js_cleaner = """
21
+ <img src="x" onerror="
22
  const observer = new MutationObserver(() => {
23
+ ['footer', '.built-with', 'header', '#header', '.share-button', '.gr-pro'].forEach(s => {
24
+ const el = document.querySelector(s);
 
 
 
 
 
 
 
 
 
 
 
25
  if (el) el.remove();
26
  });
27
  });
 
28
  observer.observe(document.body, { childList: true, subtree: true });
29
+ " style="display:none;">
30
  """
31
 
32
+ # 3. GIAO DIỆN CSS
33
  custom_css = """
34
+ footer, .built-with, header, #header { display: none !important; visibility: hidden !important; }
35
+ .gradio-container { max-width: 100% !important; padding: 0 !important; }
36
+ .sidebar-node { background: rgba(15, 23, 42, 0.8) !important; border-right: 1px solid #38bdf833; padding: 20px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # 4. LOGIC XỬ LÝ (Giữ nguyên)
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("created_at", desc=True).execute()
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]
 
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
+ messages = [{"role": "system", "content": f"Master: {user_name}."}]
64
+ for msg in history: messages.append({"role": msg["role"], "content": msg["content"]})
 
 
65
  messages.append({"role": "user", "content": text})
 
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
+ data = {"username": profile.username, "session_id": session_id, "title": text[:30], "history": new_history + [{"role": "assistant", "content": ans}]}
 
 
 
 
 
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 (Bỏ tham số head gây lỗi)
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
 
88
  with gr.Row():
 
89
  with gr.Column(scale=1, elem_classes="sidebar-node"):
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):
97
  chatbot = gr.Chatbot(show_label=False, height="76vh")
98
+ gr.HTML("<div class='custom-warning'>NodeAI không thể chắc chắn 100%, hãy rà soát lại khi bạn có chuyện gì quan trọng!</div>")
99
+ msg_input = gr.MultimodalTextbox(show_label=False, placeholder="Hỏi NodeAI...", container=False)
 
 
 
 
 
 
 
 
 
100
 
 
101
  def refresh_data(profile: gr.OAuthProfile | None):
102
  if not profile: return [], gr.Dataset(samples=[])
103
  data = get_db_history(profile)
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
+ msg_input.submit(chat_engine, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id]).then(refresh_data, None, [db_state, history_list])
 
 
 
 
 
 
 
 
109
  new_chat_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
110
 
111
  if __name__ == "__main__":