lamgamepro1 commited on
Commit
b2dfbe6
·
verified ·
1 Parent(s): b32d324

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +100 -50
app.py CHANGED
@@ -1,23 +1,33 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
 
 
4
 
5
- # 1. Cấu hình Model & Token (Sử dụng Llama-3.2 để Pro hơn)
6
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
7
- model_id = "meta-llama/Llama-3.2-1B-Instruct"
8
  client = InferenceClient(model=model_id, token=HF_TOKEN)
9
 
10
- # 2. CSS tinh chỉnh cho Gradio 6.x
11
  custom_css = """
12
- .header-pro {
13
- background: linear-gradient(135deg, #000428 0%, #004e92 100%);
14
- padding: 20px; border-radius: 15px; color: white; text-align: center; margin-bottom: 20px;
 
 
 
 
 
 
15
  }
16
- .footer-info { font-size: 0.8em; text-align: center; color: #666; margin-top: 10px; }
17
  """
18
 
19
- def chat_fn(message, history):
20
- # Trích xuất text từ định dạng tin nhắn Gradio 6
 
 
 
21
  if isinstance(message, dict):
22
  user_input = message.get("text", "")
23
  elif isinstance(message, list):
@@ -25,66 +35,106 @@ def chat_fn(message, history):
25
  else:
26
  user_input = str(message)
27
 
28
- # Khởi tạo history nếu trống
29
- if history is None: history = []
 
 
30
 
31
- # Format tin nhắn người dùng
32
- user_msg = {"role": "user", "content": [{"type": "text", "text": user_input}]}
33
- history.append(user_msg)
34
 
35
- # Gọi API Inference
 
 
 
 
 
 
 
 
36
  try:
37
- # Sử dụng chat_completion để có kết quả thông minh hơn
38
  response = client.chat_completion(
39
- messages=[{"role": "user", "content": user_input}],
40
- max_tokens=500,
41
  temperature=0.7
42
  )
43
  bot_res = response.choices[0].message.content
44
  except Exception as e:
45
- bot_res = f"⚠️ Lỗi kết nối: Hãy đảm bảo bạn đã add HF_TOKEN vào Settings. (Chi tiết: {str(e)})"
46
 
47
- # Format tin nhắn Bot
48
- bot_msg = {"role": "assistant", "content": [{"type": "text", "text": bot_res}]}
49
- history.append(bot_msg)
50
 
51
- return "", history
 
 
 
 
 
 
 
 
 
52
 
53
  with gr.Blocks(title="NodeAI Pro") as demo:
54
- gr.HTML("""
 
 
 
55
  <div class="header-pro">
56
- <h1 style='margin:0'>🚀 NodeAI Pro</h1>
57
- <p style='margin:0'>High-Performance AI Assistant</p>
58
  </div>
59
  """)
60
-
61
  with gr.Row():
 
62
  with gr.Column(scale=1):
63
- gr.Markdown("### 🛠️ Core Engine")
64
- gr.LoginButton()
65
- gr.Markdown(f"**Engine:** `Llama-3.2-1B`")
66
- gr.Markdown(f"**API Status:** {'🟢 Online' if HF_TOKEN else '🔴 Offline'}")
67
- clear_btn = gr.Button("🗑️ Reset Session", variant="secondary")
68
-
69
- with gr.Column(scale=4):
70
- # Không dùng type="messages" ở đây để tránh TypeError trên một số môi trường
71
- chatbot = gr.Chatbot(label="NodeAI Chat Console", height=500)
72
-
73
- with gr.Row():
74
- msg_input = gr.Textbox(
75
- placeholder="Nhập câu hỏi...",
76
- show_label=False,
77
- scale=8
 
 
78
  )
79
- submit_btn = gr.Button("Send", variant="primary", scale=2)
80
-
81
- gr.HTML("<div class='footer-info'>NodeAI Pro v1.0.9 | Powered by Hugging Face Inference API</div>")
82
 
83
- # Xử lý Logic
84
- msg_input.submit(chat_fn, [msg_input, chatbot], [msg_input, chatbot])
85
- submit_btn.click(chat_fn, [msg_input, chatbot], [msg_input, chatbot])
86
- clear_btn.click(lambda: None, None, chatbot)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  if __name__ == "__main__":
89
- # Đưa CSS vào launch() để fix UserWarning
90
  demo.launch(css=custom_css)
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import os
4
+ import json
5
+ from datetime import datetime
6
 
7
+ # 1. Cấu hình Model & Token
8
  HF_TOKEN = os.getenv("HUGGINGFACE_HUB_TOKEN")
9
+ model_id = "meta-llama/Llama-3.2-1B-Instruct"
10
  client = InferenceClient(model=model_id, token=HF_TOKEN)
11
 
12
+ # 2. CSS Pro (Glassmorphism & Gradients)
13
  custom_css = """
14
+ .header-pro {
15
+ background: linear-gradient(135deg, #000428 0%, #004e92 100%);
16
+ padding: 25px; border-radius: 15px; color: white; text-align: center; margin-bottom: 20px;
17
+ }
18
+ .memory-box {
19
+ background: #f0f4ff; border-left: 5px solid #004e92; padding: 10px; border-radius: 5px;
20
+ }
21
+ .user-status {
22
+ font-weight: bold; color: #004e92;
23
  }
 
24
  """
25
 
26
+ def chat_fn(message, history, memory, profile: gr.OAuthProfile | None):
27
+ # Kiểm tra đăng nhập
28
+ user_name = profile.name if profile else "Guest"
29
+
30
+ # Định dạng Input của Gradio 6.9.0
31
  if isinstance(message, dict):
32
  user_input = message.get("text", "")
33
  elif isinstance(message, list):
 
35
  else:
36
  user_input = str(message)
37
 
38
+ # Xử lý Memory: Kết hợp bộ nhớ vào Prompt hệ thống
39
+ system_prompt = f"Bạn là NodeAI Pro. Đang trò chuyện với {user_name}. "
40
+ if memory:
41
+ system_prompt += f"Bộ nhớ quan trọng cần nhớ: {memory}"
42
 
43
+ # Tạo hội thoại gửi lên API
44
+ messages = [{"role": "system", "content": system_prompt}]
 
45
 
46
+ # Thêm lịch sử (convert Gradio format sang API format)
47
+ for turn in history:
48
+ role = turn["role"]
49
+ content = turn["content"][0]["text"]
50
+ messages.append({"role": role, "content": content})
51
+
52
+ messages.append({"role": "user", "content": user_input})
53
+
54
+ # Gọi API
55
  try:
 
56
  response = client.chat_completion(
57
+ messages=messages,
58
+ max_tokens=512,
59
  temperature=0.7
60
  )
61
  bot_res = response.choices[0].message.content
62
  except Exception as e:
63
+ bot_res = f"⚠️ Lỗi kết nối: {str(e)}"
64
 
65
+ # Cập nhật History theo format Gradio 6
66
+ history.append({"role": "user", "content": [{"type": "text", "text": user_input}]})
67
+ history.append({"role": "assistant", "content": [{"type": "text", "text": bot_res}]})
68
 
69
+ return "", history, memory
70
+
71
+ def save_chat(history, profile: gr.OAuthProfile | None):
72
+ if not profile:
73
+ return "⚠️ Vui lòng đăng nhập để lưu cuộc trò chuyện!"
74
+
75
+ filename = f"chat_history_{profile.name}.json"
76
+ with open(filename, "w", encoding="utf-8") as f:
77
+ json.dump(history, f, ensure_ascii=False, indent=4)
78
+ return f"✅ Đã lưu {len(history)//2} tin nhắn vào {filename}"
79
 
80
  with gr.Blocks(title="NodeAI Pro") as demo:
81
+ # State để lưu Memory dài hạn trong phiên làm việc
82
+ memory_state = gr.State("")
83
+
84
+ gr.HTML(f"""
85
  <div class="header-pro">
86
+ <h1 style='margin:0'>🤖 NodeAI Pro v2.0</h1>
87
+ <p style='margin:0; opacity:0.8'>Bản nâng cấp: Persistent Memory & OAuth Secure</p>
88
  </div>
89
  """)
90
+
91
  with gr.Row():
92
+ # SIDEBAR: Quản lý người dùng & Memory
93
  with gr.Column(scale=1):
94
+ with gr.Group():
95
+ gr.Markdown("### 👤 User Profile")
96
+ login_btn = gr.LoginButton()
97
+
98
+ # Hiển thị thông tin sau khi đăng nhập
99
+ @gr.render(inputs=login_btn)
100
+ def show_user_info(p: gr.OAuthProfile | None):
101
+ if p:
102
+ return gr.Markdown(f"Chào mừng, <span class='user-status'>{p.name}</span>!")
103
+ return gr.Markdown("Vui lòng đăng nhập để lưu lịch sử.")
104
+
105
+ with gr.Group():
106
+ gr.Markdown("### 🧠 AI Memory")
107
+ memory_input = gr.Textbox(
108
+ label="Ghi chú để AI ghi nhớ (Sở thích, tên, dự án...)",
109
+ placeholder="Ví dụ: Tôi thích code Python...",
110
+ lines=3
111
  )
112
+ gr.Markdown("<div class='memory-box'>Memory giúp AI không quên thông tin quan trọng qua các lần chat.</div>")
 
 
113
 
114
+ save_btn = gr.Button("💾 Lưu cuộc trò chuyện", variant="secondary")
115
+ status_msg = gr.Markdown("")
116
+ clear_btn = gr.Button("🗑️ Reset")
117
+
118
+ # MAIN CHAT
119
+ with gr.Column(scale=3):
120
+ chatbot = gr.Chatbot(label="NodeAI Console", height=550)
121
+ with gr.Row():
122
+ msg_input = gr.Textbox(placeholder="Nhập tin nhắn...", show_label=False, scale=8)
123
+ submit_btn = gr.Button("Gửi", variant="primary", scale=2)
124
+
125
+ # LOGIC XỬ LÝ
126
+ # Khi nhấn Gửi: Truyền thêm memory_input và OAuth profile
127
+ input_params = [msg_input, chatbot, memory_input]
128
+ output_params = [msg_input, chatbot, memory_state]
129
+
130
+ msg_input.submit(chat_fn, input_params, output_params)
131
+ submit_btn.click(chat_fn, input_params, output_params)
132
+
133
+ # Lưu chat
134
+ save_btn.click(save_chat, [chatbot], [status_msg])
135
+
136
+ # Xóa chat
137
+ clear_btn.click(lambda: ([], ""), None, [chatbot, memory_input])
138
 
139
  if __name__ == "__main__":
 
140
  demo.launch(css=custom_css)