lamgamepro1 commited on
Commit
fa459d1
·
verified ·
1 Parent(s): f642f20

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -111
app.py CHANGED
@@ -4,10 +4,12 @@ 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
  def load_vault():
13
  if os.path.exists(DB_FILE):
@@ -16,109 +18,67 @@ def load_vault():
16
  except: return {}
17
  return {}
18
 
19
- def save_vault(vault_data):
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 DIAMOND)
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
-
27
- .gradio-container {
28
- background: radial-gradient(circle at 50% 0%, #0f172a 0%, #020617 100%) !important;
29
- font-family: 'Plus Jakarta Sans', sans-serif !important;
30
- }
31
-
32
- /* Sidebar Kính Mờ */
33
- .sidebar-node {
34
- position: fixed !important;
35
- left: 0 !important; top: 0 !important;
36
- width: 280px !important; height: 100vh !important;
37
- background: rgba(15, 23, 42, 0.6) !important;
38
- backdrop-filter: blur(20px) !important;
39
- border-right: 1px solid rgba(255, 255, 255, 0.1) !important;
40
- z-index: 1000 !important;
41
- padding: 25px !important;
42
- }
43
-
44
- .logo-text {
45
- font-family: 'Orbitron', sans-serif !important;
46
- background: linear-gradient(90deg, #38bdf8, #818cf8);
47
- -webkit-background-clip: text;
48
- -webkit-text-fill-color: transparent;
49
- font-size: 22px; text-align: center; margin-bottom: 25px;
50
- }
51
-
52
- .orange-btn {
53
- background: linear-gradient(135deg, #f97316 0%, #fb923c 100%) !important;
54
- border: none !important; color: white !important;
55
- font-weight: 600 !important; border-radius: 12px !important;
56
- box-shadow: 0 4px 15px rgba(249, 115, 22, 0.3) !important;
57
- }
58
-
59
- /* Chat Main 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 {
69
- background: transparent !important; border: none !important;
70
- height: 75vh !important; margin-bottom: 110px !important;
71
- }
72
-
73
- /* Input Area Fixed - Không bao giờ tràn */
74
- .input-fixed-bottom {
75
- position: fixed !important;
76
- bottom: 25px !important;
77
- left: 50% !important;
78
- transform: translateX(calc(-50% + 140px)) !important;
79
- width: calc(100% - 340px) !important;
80
- max-width: 800px !important;
81
- background: rgba(30, 41, 59, 0.8) !important;
82
- backdrop-filter: blur(10px) !important;
83
- border: 1px solid rgba(56, 189, 248, 0.3) !important;
84
- border-radius: 20px !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; }
95
- .input-fixed-bottom { transform: translateX(-50%) !important; width: 92% !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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  vault = load_vault()
109
  if username not in vault: vault[username] = {}
110
-
111
  if session_id not in vault[username]:
112
- vault[username][session_id] = {"title": user_text[:20] + "...", "history": []}
113
-
114
- api_messages = [{"role": "system", "content": f"Master: {username}. Bạn là NodeAI Genesis."}]
115
- for msg in history: api_messages.append({"role": msg["role"], "content": msg["content"]})
116
- api_messages.append({"role": "user", "content": user_text})
 
117
 
 
 
118
  try:
119
  ans = ""
120
- new_h = history + [{"role": "user", "content": user_text}]
121
- for token in client.chat_completion(messages=api_messages, max_tokens=2000, stream=True):
 
 
 
122
  if token.choices[0].delta.content:
123
  ans += token.choices[0].delta.content
124
  yield {"text": ""}, new_h + [{"role": "assistant", "content": ans}], session_id, ""
@@ -128,58 +88,46 @@ def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
128
  save_vault(vault)
129
  yield {"text": ""}, final_h, session_id, ans
130
  except Exception as e:
131
- yield {"text": ""}, history + [{"role": "assistant", "content": str(e)}], session_id, ""
132
 
133
  # 4. GIAO DIỆN
134
- with gr.Blocks(title="NodeAI Genesis v32.7") as demo:
135
  session_id = gr.State(str(uuid.uuid4()))
136
  tts_buffer = gr.Textbox(visible=False)
137
  vault_state = gr.State(load_vault())
138
 
139
  with gr.Row():
140
- # SIDEBAR
141
  with gr.Column(elem_classes="sidebar-node"):
142
- gr.HTML("<div class='logo-text'>NODEAI GENESIS</div>")
143
  gr.LoginButton(value="Xác thực Nick")
144
  new_btn = gr.Button("+ NEW WORKSPACE", elem_classes="orange-btn")
145
-
146
  gr.Markdown("### 🕒 Lịch sử Chat")
147
-
148
  @gr.render(inputs=[vault_state])
149
  def render_history(current_vault, profile: gr.OAuthProfile | None):
150
- username = get_username(profile)
151
  user_chats = current_vault.get(username, {})
152
  with gr.Column():
153
  for sid in reversed(list(user_chats.keys())):
154
  btn = gr.Button(f"◈ {user_chats[sid]['title']}", variant="ghost")
155
- btn.click(lambda s=sid, u=username: (load_vault()[u][s]["history"], s),
156
- None, [chatbot, session_id])
157
 
158
- # MAIN
159
  with gr.Column(elem_classes="chat-main"):
160
- # Đã xóa type="messages" để fix lỗi runtime
161
  chatbot = gr.Chatbot(show_label=False)
162
  audio_out = gr.Audio(autoplay=True, visible=False)
163
-
164
  with gr.Row(elem_classes="input-fixed-bottom"):
165
  msg_input = gr.MultimodalTextbox(
166
  show_label=False,
167
- placeholder="Hỏi Master Phúc bất cứ điều gì...",
168
- container=False
 
169
  )
170
 
171
- # EVENT HANDLERS
172
- def update_vault(): return load_vault()
173
-
174
  msg_input.submit(
175
  chat_fn, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id, tts_buffer]
176
- ).then(
177
- update_vault, None, vault_state
178
- ).then(
179
  lambda x: f"https://translate.google.com/translate_tts?ie=UTF-8&tl=vi&client=tw-ob&q={x[:200]}" if x else None,
180
  tts_buffer, audio_out
181
  )
182
-
183
  new_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
184
 
185
  if __name__ == "__main__":
 
4
  import uuid
5
  import json
6
 
7
+ # 1. CẤU HÌNH (Sử dụng model hỗ trợ Hình ảnh/Vision)
8
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
9
+ # Chuyển sang model Vision để AI xem được ảnh
10
+ MODEL_ID = "Qwen/Qwen2-VL-7B-Instruct"
11
+ client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
12
+ DB_FILE = "nodeai_vision_vault.json"
13
 
14
  def load_vault():
15
  if os.path.exists(DB_FILE):
 
18
  except: return {}
19
  return {}
20
 
21
+ def save_vault(data):
22
  with open(DB_FILE, "w", encoding="utf-8") as f:
23
+ json.dump(data, f, ensure_ascii=False, indent=4)
24
 
25
+ # 2. UI DIAMOND GLASS (Cập nhật để hiển thị file gửi lên đẹp hơn)
26
  custom_css = """
27
  @import url('https://fonts.googleapis.com/css2?family=Orbitron:wght@800&family=Plus+Jakarta+Sans:wght@400;600&display=swap');
28
+ .gradio-container { background: radial-gradient(circle at 50% 0%, #0f172a 0%, #020617 100%) !important; font-family: 'Plus Jakarta Sans', sans-serif !important; }
29
+ .sidebar-node { position: fixed !important; left: 0 !important; top: 0 !important; width: 280px !important; height: 100vh !important; background: rgba(15, 23, 42, 0.6) !important; backdrop-filter: blur(20px) !important; border-right: 1px solid rgba(255, 255, 255, 0.1) !important; z-index: 1000 !important; padding: 25px !important; }
30
+ .logo-text { font-family: 'Orbitron', sans-serif !important; background: linear-gradient(90deg, #38bdf8, #818cf8); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-size: 22px; text-align: center; margin-bottom: 25px; }
31
+ .orange-btn { background: linear-gradient(135deg, #f97316 0%, #fb923c 100%) !important; border: none !important; color: white !important; font-weight: 600 !important; border-radius: 12px !important; }
32
+ .chat-main { margin-left: 280px !important; width: calc(100% - 280px) !important; height: 100vh !important; padding: 0 20px !important; box-sizing: border-box !important; }
33
+ .gr-chatbot { background: transparent !important; border: none !important; height: 75vh !important; margin-bottom: 110px !important; }
34
+ .input-fixed-bottom { position: fixed !important; bottom: 25px !important; left: 50% !important; transform: translateX(calc(-50% + 140px)) !important; width: calc(100% - 340px) !important; max-width: 800px !important; background: rgba(30, 41, 59, 0.9) !important; border: 1px solid rgba(56, 189, 248, 0.3) !important; border-radius: 20px !important; padding: 5px 15px !important; z-index: 2000 !important; box-sizing: border-box !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  footer { display: none !important; }
36
+ @media screen and (max-width: 768px) { .sidebar-node { display: none !important; } .chat-main { margin-left: 0 !important; width: 100% !important; } .input-fixed-bottom { transform: translateX(-50%) !important; width: 92% !important; } }
 
 
 
 
 
37
  """
38
 
39
+ # 3. CORE LOGIC (Xử lý đa phương tiện)
 
 
 
40
  def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
41
+ username = profile.username if profile else "Master_Phuc"
42
  user_text = message.get("text", "")
43
+ files = message.get("files", [])
44
 
45
+ if not user_text and not files:
46
+ yield {"text": ""}, history, session_id, ""
47
+ return
48
+
49
+ # Chuẩn bị tin nhắn cho AI
50
+ # Lưu ý: Gradio gửi tin nhắn dưới dạng list các nội dung (văn bản hoặc file)
51
+ content = []
52
+ if user_text:
53
+ content.append({"type": "text", "text": user_text})
54
+
55
+ for f in files:
56
+ # Nếu là ảnh, gửi dưới dạng image_url cho AI xem
57
+ if f.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.webp')):
58
+ content.append({"type": "image_url", "image_url": {"url": f}})
59
+ else:
60
+ # Nếu là file khác, AI sẽ được thông báo có file gửi kèm (Hỗ trợ đọc nội dung file text/code)
61
+ content.append({"type": "text", "text": f"[Gửi kèm file: {os.path.basename(f)}]"})
62
+
63
  vault = load_vault()
64
  if username not in vault: vault[username] = {}
 
65
  if session_id not in vault[username]:
66
+ vault[username][session_id] = {"title": user_text[:20] if user_text else "Media Chat", "history": []}
67
+
68
+ # Xây dựng prompt
69
+ messages = [{"role": "system", "content": f"Bạn là NodeAI Genesis. Master: {username}. Bạn có khả năng xem ảnh và đọc file."}]
70
+ for msg in history:
71
+ messages.append({"role": msg["role"], "content": msg["content"]})
72
 
73
+ messages.append({"role": "user", "content": content})
74
+
75
  try:
76
  ans = ""
77
+ # Thêm tin nhắn người dùng vào giao diện ngay lập tức
78
+ user_msg = {"role": "user", "content": content}
79
+ new_h = history + [user_msg]
80
+
81
+ for token in client.chat_completion(messages=messages, max_tokens=1500, stream=True):
82
  if token.choices[0].delta.content:
83
  ans += token.choices[0].delta.content
84
  yield {"text": ""}, new_h + [{"role": "assistant", "content": ans}], session_id, ""
 
88
  save_vault(vault)
89
  yield {"text": ""}, final_h, session_id, ans
90
  except Exception as e:
91
+ yield {"text": ""}, history + [{"role": "assistant", "content": f"Lỗi: {str(e)}"}], session_id, ""
92
 
93
  # 4. GIAO DIỆN
94
+ with gr.Blocks(title="NodeAI Genesis Vision") as demo:
95
  session_id = gr.State(str(uuid.uuid4()))
96
  tts_buffer = gr.Textbox(visible=False)
97
  vault_state = gr.State(load_vault())
98
 
99
  with gr.Row():
 
100
  with gr.Column(elem_classes="sidebar-node"):
101
+ gr.HTML("<div class='logo-text'>NODEAI VISION</div>")
102
  gr.LoginButton(value="Xác thực Nick")
103
  new_btn = gr.Button("+ NEW WORKSPACE", elem_classes="orange-btn")
 
104
  gr.Markdown("### 🕒 Lịch sử Chat")
 
105
  @gr.render(inputs=[vault_state])
106
  def render_history(current_vault, profile: gr.OAuthProfile | None):
107
+ username = profile.username if profile else "Master_Phuc"
108
  user_chats = current_vault.get(username, {})
109
  with gr.Column():
110
  for sid in reversed(list(user_chats.keys())):
111
  btn = gr.Button(f"◈ {user_chats[sid]['title']}", variant="ghost")
112
+ btn.click(lambda s=sid, u=username: (load_vault()[u][s]["history"], s), None, [chatbot, session_id])
 
113
 
 
114
  with gr.Column(elem_classes="chat-main"):
 
115
  chatbot = gr.Chatbot(show_label=False)
116
  audio_out = gr.Audio(autoplay=True, visible=False)
 
117
  with gr.Row(elem_classes="input-fixed-bottom"):
118
  msg_input = gr.MultimodalTextbox(
119
  show_label=False,
120
+ placeholder="Gửi ảnh hoặc hỏi Master Phúc...",
121
+ container=False,
122
+ file_types=["image", ".pdf", ".txt", ".py", ".html"] # Cho phép gửi nhiều loại file
123
  )
124
 
 
 
 
125
  msg_input.submit(
126
  chat_fn, [msg_input, chatbot, session_id], [msg_input, chatbot, session_id, tts_buffer]
127
+ ).then(lambda: load_vault(), None, vault_state).then(
 
 
128
  lambda x: f"https://translate.google.com/translate_tts?ie=UTF-8&tl=vi&client=tw-ob&q={x[:200]}" if x else None,
129
  tts_buffer, audio_out
130
  )
 
131
  new_btn.click(lambda: ([], str(uuid.uuid4())), None, [chatbot, session_id])
132
 
133
  if __name__ == "__main__":