lamgamepro1 commited on
Commit
dc5463b
·
verified ·
1 Parent(s): 773555d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -33
app.py CHANGED
@@ -4,12 +4,11 @@ import os
4
  import uuid
5
  import json
6
 
7
- # 1. CẤU HÌNH MODEL (Sử dụng model ổn định nhất của Hugging Face)
8
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
9
- # Model này cực kỳ ổn định và ít khi bị lỗi "Not supported"
10
- MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.3"
11
  client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
12
- DB_FILE = "nodeai_pro_vault.json"
13
 
14
  def load_vault():
15
  if os.path.exists(DB_FILE):
@@ -22,21 +21,31 @@ 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 GLASSMORPHISM PLATINUM
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.7) !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; box-shadow: 0 4px 15px rgba(249, 115, 22, 0.3) !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; }
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. LOGIC XỬ LÝ ĐA PHƯƠNG TIỆN (Multimodal)
 
 
 
 
 
 
 
 
 
 
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", "")
@@ -46,32 +55,26 @@ def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
46
  yield {"text": ""}, history, session_id, ""
47
  return
48
 
49
- # Xử lý nội dung gửi đi
50
- prompt_content = user_text
51
- if files:
52
- file_list = [os.path.basename(f) for f in files]
53
- prompt_content += f"\n\n[Hệ thống: Người dùng đã gửi các file: {', '.join(file_list)}. Hãy phân tích nếu đó là code hoặc văn bản.]"
54
 
55
  vault = load_vault()
56
  if username not in vault: vault[username] = {}
57
  if session_id not in vault[username]:
58
  vault[username][session_id] = {"title": user_text[:20] if user_text else "File Analysis", "history": []}
59
 
60
- # Xây dựng hội thoại cho model text-only nhưng thông minh
61
- messages = [{"role": "system", "content": f"Bạn là NodeAI Genesis. Master: {username}. Bạn cực giỏi về lập trình Roblox và Web."}]
62
  for msg in history:
63
- # Đảm bảo nội dung là string để tránh lỗi model text-only
64
- content = msg["content"]
65
- if isinstance(content, list):
66
- content = content[0].get("text", "") if content else ""
67
- messages.append({"role": msg["role"], "content": content})
68
 
69
- messages.append({"role": "user", "content": prompt_content})
70
 
71
  try:
72
  ans = ""
73
- # Hiển thị tin nhắn người dùng (kèm ảnh) lên UI
74
- # Gradio tự động hiển thị ảnh nếu chúng ta gửi object message vào history
75
  new_h = history + [{"role": "user", "content": message}]
76
 
77
  for token in client.chat_completion(messages=messages, max_tokens=2048, stream=True):
@@ -84,10 +87,10 @@ def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
84
  save_vault(vault)
85
  yield {"text": ""}, final_h, session_id, ans
86
  except Exception as e:
87
- yield {"text": ""}, history + [{"role": "assistant", "content": f"Lỗi kết nối: {str(e)}"}], session_id, ""
88
 
89
- # 4. GIAO DIỆN
90
- with gr.Blocks(title="NodeAI Genesis Pro") as demo:
91
  session_id = gr.State(str(uuid.uuid4()))
92
  tts_buffer = gr.Textbox(visible=False)
93
  vault_state = gr.State(load_vault())
@@ -95,7 +98,7 @@ with gr.Blocks(title="NodeAI Genesis Pro") as demo:
95
  with gr.Row():
96
  with gr.Column(elem_classes="sidebar-node"):
97
  gr.HTML("<div class='logo-text'>NODEAI GENESIS</div>")
98
- gr.LoginButton(value="Xác thực Nick")
99
  new_btn = gr.Button("+ NEW WORKSPACE", elem_classes="orange-btn")
100
  @gr.render(inputs=[vault_state])
101
  def render_history(current_vault, profile: gr.OAuthProfile | None):
@@ -111,10 +114,8 @@ with gr.Blocks(title="NodeAI Genesis Pro") as demo:
111
  audio_out = gr.Audio(autoplay=True, visible=False)
112
  with gr.Row(elem_classes="input-fixed-bottom"):
113
  msg_input = gr.MultimodalTextbox(
114
- show_label=False,
115
- placeholder="Gửi file hoặc nhắn tin cho AI...",
116
- container=False,
117
- file_types=["image", ".pdf", ".txt", ".py", ".lua"] # Hỗ trợ file Roblox Lua
118
  )
119
 
120
  msg_input.submit(
 
4
  import uuid
5
  import json
6
 
7
+ # 1. CẤU HÌNH MODEL (Model Zephyr cực kỳ ổn định cho Chat)
8
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
9
+ MODEL_ID = "HuggingFaceH4/zephyr-7b-beta"
 
10
  client = InferenceClient(model=MODEL_ID, token=HF_TOKEN)
11
+ DB_FILE = "nodeai_ultimate_vault.json"
12
 
13
  def load_vault():
14
  if os.path.exists(DB_FILE):
 
21
  with open(DB_FILE, "w", encoding="utf-8") as f:
22
  json.dump(data, f, ensure_ascii=False, indent=4)
23
 
24
+ # 2. UI GLASSMORPHISM DIAMOND
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
+ .gradio-container { background: radial-gradient(circle at 50% 0%, #0f172a 0%, #020617 100%) !important; font-family: 'Plus Jakarta Sans', sans-serif !important; color: white !important; }
28
+ .sidebar-node { position: fixed !important; left: 0 !important; top: 0 !important; width: 280px !important; height: 100vh !important; background: rgba(15, 23, 42, 0.7) !important; backdrop-filter: blur(25px) !important; border-right: 1px solid rgba(255, 255, 255, 0.1) !important; z-index: 1000 !important; padding: 25px !important; }
29
  .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; }
30
+ .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; cursor: pointer !important; }
31
  .chat-main { margin-left: 280px !important; width: calc(100% - 280px) !important; height: 100vh !important; padding: 0 20px !important; box-sizing: border-box !important; }
32
  .gr-chatbot { background: transparent !important; border: none !important; height: 75vh !important; margin-bottom: 110px !important; }
33
+ .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; backdrop-filter: blur(10px) !important; border: 1px solid rgba(56, 189, 248, 0.3) !important; border-radius: 20px !important; padding: 5px 15px !important; z-index: 2000 !important; }
34
  footer { display: none !important; }
35
  @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; } }
36
  """
37
 
38
+ # 3. LOGIC XỬ LÝ FILE VÀ CHAT
39
+ def read_file_content(file_path):
40
+ try:
41
+ # Nếu là file văn bản, đọc nội dung bên trong
42
+ if file_path.lower().endswith(('.txt', '.py', '.lua', '.html', '.css', '.js', '.json')):
43
+ with open(file_path, "r", encoding="utf-8") as f:
44
+ return f"\n--- Nội dung file {os.path.basename(file_path)} ---\n{f.read()}\n----------------------\n"
45
+ return f"\n[Gửi kèm file: {os.path.basename(file_path)} (Định dạng này AI chỉ ghi nhận tên)]\n"
46
+ except:
47
+ return ""
48
+
49
  def chat_fn(message, history, session_id, profile: gr.OAuthProfile | None):
50
  username = profile.username if profile else "Master_Phuc"
51
  user_text = message.get("text", "")
 
55
  yield {"text": ""}, history, session_id, ""
56
  return
57
 
58
+ # Tổng hợp nội dung: Văn bản + Nội dung bên trong file
59
+ full_prompt = user_text
60
+ for f in files:
61
+ full_prompt += read_file_content(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 "File Analysis", "history": []}
67
 
68
+ # Format tin nhắn chuẩn Zephyr
69
+ messages = [{"role": "system", "content": f"Bạn là NodeAI Genesis. Master: {username}. Bạn hỗ trợ chuyên sâu về Roblox (Lua) và Web Development. Hãy đọc kỹ nội dung file nếu Master gửi kèm."}]
70
  for msg in history:
71
+ messages.append({"role": msg["role"], "content": msg["content"]})
 
 
 
 
72
 
73
+ messages.append({"role": "user", "content": full_prompt})
74
 
75
  try:
76
  ans = ""
77
+ # Hiển thị tin nhắn (kèm ảnh/icon file) lên giao diện
 
78
  new_h = history + [{"role": "user", "content": message}]
79
 
80
  for token in client.chat_completion(messages=messages, max_tokens=2048, stream=True):
 
87
  save_vault(vault)
88
  yield {"text": ""}, final_h, session_id, ans
89
  except Exception as e:
90
+ yield {"text": ""}, history + [{"role": "assistant", "content": f"Lỗi hệ thống: {str(e)}"}], session_id, ""
91
 
92
+ # 4. DỰNG GIAO DIỆN
93
+ with gr.Blocks(title="NodeAI Ultimate") as demo:
94
  session_id = gr.State(str(uuid.uuid4()))
95
  tts_buffer = gr.Textbox(visible=False)
96
  vault_state = gr.State(load_vault())
 
98
  with gr.Row():
99
  with gr.Column(elem_classes="sidebar-node"):
100
  gr.HTML("<div class='logo-text'>NODEAI GENESIS</div>")
101
+ gr.LoginButton(value="Xác thực")
102
  new_btn = gr.Button("+ NEW WORKSPACE", elem_classes="orange-btn")
103
  @gr.render(inputs=[vault_state])
104
  def render_history(current_vault, profile: gr.OAuthProfile | None):
 
114
  audio_out = gr.Audio(autoplay=True, visible=False)
115
  with gr.Row(elem_classes="input-fixed-bottom"):
116
  msg_input = gr.MultimodalTextbox(
117
+ show_label=False, placeholder="Gửi script Roblox hoặc tin nhắn...", container=False,
118
+ file_types=["image", ".lua", ".py", ".txt", ".js"]
 
 
119
  )
120
 
121
  msg_input.submit(