lamgamepro1 commited on
Commit
6d7dcce
·
verified ·
1 Parent(s): 3f62ddd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -145
app.py CHANGED
@@ -1,180 +1,140 @@
1
  import gradio as gr
 
2
  import os
3
- import requests
4
- import json
5
- from datetime import datetime
6
- import hashlib
7
 
8
- groq_key = os.getenv("GROQ_API_KEY")
9
- MODEL = "llama3-groq-70b-8192-tool-use-preview" # Model 2026 preview
 
10
 
11
- # User management
12
- users = {} # {username: {"token": hash, "history": []}}
13
- current_user = None
14
-
15
- status_msg = "❌ Chưa set GROQ_API_KEY"
16
- if groq_key:
17
- status_msg = f"✅ Groq {MODEL} Ready"
18
-
19
- def hash_token(token):
20
- return hashlib.sha256(token.encode()).hexdigest()
21
-
22
- def login(username, password):
23
- global current_user
24
- token = hash_token(f"{username}:{password}")
25
- if token in users:
26
- current_user = username
27
- return f"✅ Đăng nhập thành công: {username}", gr.update(visible=True), gr.update(visible=False)
28
- else:
29
- return "❌ Sai tên đăng nhập/mật khẩu", gr.update(visible=False), gr.update(visible=True)
30
 
31
- return "❌ Lỗi đăng nhập", gr.update(visible=False), gr.update(visible=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- def logout():
34
- global current_user
35
- current_user = None
36
- return "👋 Đã đăng xuất", gr.update(visible=False), gr.update(visible=True), []
37
 
38
- def save_chat(username, message, reply):
39
- """Lưu tin nhắn vào history user"""
40
- if username not in users:
41
- users[username] = {"history": []}
42
 
43
- users[username]["history"].append({
44
- "timestamp": datetime.now().strftime("%H:%M"),
45
  "user": message,
46
- "ai": reply
47
  })
48
 
49
- # Giữ 50 tin nhắn gần nhất
50
- if len(users[username]["history"]) > 50:
51
- users[username]["history"] = users[username]["history"][-50:]
52
 
53
- def load_history(username):
54
- """Load lịch sử chat"""
55
- if username in users and users[username]["history"]:
 
 
 
 
 
56
  return [
57
- [{"role": "user", "content": h["user"]},
58
- {"role": "assistant", "content": h["ai"]}]
59
- for h in users[username]["history"][-10:]
 
 
60
  ]
61
  return []
62
 
63
- def call_groq(messages):
64
- url = "https://api.groq.com/openai/v1/chat/completions"
65
- headers = {
66
- "Authorization": f"Bearer {groq_key}",
67
- "Content-Type": "application/json"
68
- }
69
-
70
- data = {
71
- "model": MODEL,
72
- "messages": messages,
73
- "temperature": 0.7,
74
- "max_tokens": 500
75
- }
76
-
77
- try:
78
- response = requests.post(url, headers=headers, json=data, timeout=20)
79
- if response.status_code == 200:
80
- return response.json()["choices"][0]["message"]["content"]
81
- return f"❌ Lỗi {response.status_code}"
82
- except:
83
- return "❌ Không kết nối Groq"
84
-
85
- def respond(message, history, username):
86
- global current_user
87
-
88
- if not current_user:
89
- return "", history, "❌ Vui lòng đăng nhập!"
90
-
91
- # Simple messages (no complex history)
92
- messages = [
93
- {"role": "system", "content": "Bạn là NodeAI - trợ lý AI tiếng Việt thông minh, hữu ích."},
94
- {"role": "user", "content": message}
95
- ]
96
-
97
- reply = call_groq(messages)
98
-
99
- # Lưu history
100
- save_chat(current_user, message, reply)
101
-
102
- new_history = history + [{"role": "user", "content": message}, {"role": "assistant", "content": reply}]
103
- return "", new_history, f"👤 {current_user}"
104
-
105
- def load_user_history(username):
106
- return load_history(username)
107
 
108
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
109
- gr.Markdown("# 🚀 NodeAI - AI Chat với Login & History")
110
- gr.Markdown(f"**Status:** {status_msg}")
111
 
112
  with gr.Row():
113
  # Sidebar - Login & History
114
- with gr.Column(scale=1, min_width=300):
115
- gr.Markdown("## 👤 Tài khoản")
116
 
117
- with gr.Group(visible=True) as login_group:
118
- username = gr.Textbox(label="Tên đăng nhập", placeholder="yourname")
119
- password = gr.Textbox(label="Mật khẩu", type="password")
120
- login_btn = gr.Button("🔐 Đăng nhập", variant="primary")
121
 
122
- with gr.Group(visible=False) as user_group:
123
- gr.Markdown("### ✅ Đã đăng nhập")
124
- user_info = gr.Markdown("**Chưa có user**")
125
- logout_btn = gr.Button("🚪 Đăng xuất", variant="stop")
126
- load_history_btn = gr.Button("📚 Load History")
127
 
128
- history_display = gr.Chatbot(
129
- height=300,
130
- label="Lịch sử chat",
131
- visible=False
132
  )
 
 
 
133
 
134
- # Main Chat
135
  with gr.Column(scale=4):
136
- chatbot = gr.Chatbot(height=500, avatar_images=("👤", "🤖"))
137
- status_display = gr.Markdown("**Chưa đăng nhập**")
138
-
139
- with gr.Row():
140
- msg = gr.Textbox(placeholder="Hỏi NodeAI...", scale=7)
141
- send_btn = gr.Button("Gửi", variant="primary", scale=1)
142
- clear_btn = gr.Button("🗑️", scale=1)
143
-
144
- # Events
145
- login_btn.click(
146
- login,
147
- inputs=[username, password],
148
- outputs=[status_display, user_group, login_group]
149
- )
150
-
151
- logout_btn.click(
152
- logout,
153
- outputs=[status_display, login_group, user_group, history_display]
154
- )
155
 
156
- load_history_btn.click(
157
- load_user_history,
158
- inputs=gr.State(),
159
- outputs=history_display
160
- ).then(
161
- lambda x: gr.update(visible=True),
162
- outputs=[history_display]
163
- )
164
 
165
- send_btn.click(
166
- respond,
167
- inputs=[msg, chatbot, gr.State()],
168
- outputs=[msg, chatbot, status_display]
169
  )
170
 
171
- msg.submit(
172
- respond,
173
- inputs=[msg, chatbot, gr.State()],
174
- outputs=[msg, chatbot, status_display]
175
  )
176
-
177
- clear_btn.click(lambda: [], outputs=chatbot)
178
 
179
  if __name__ == "__main__":
180
  demo.launch()
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
  import os
 
 
 
 
4
 
5
+ # Config
6
+ MODEL = "microsoft/DialoGPT-medium" # Hoặc model HF Inference API khác
7
+ GROQ_KEY = os.getenv("GROQ_API_KEY") # Fallback nếu cần
8
 
9
+ def respond(message, history, system_message, max_tokens, temperature, top_p, hf_token):
10
+ """Chat với HF Inference API + OAuth token"""
11
+ if not hf_token or not hf_token.token:
12
+ yield "❌ Vui lòng đăng nhập Hugging Face!"
13
+ return
14
+
15
+ client = InferenceClient(token=hf_token.token, model=MODEL)
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ messages = [{"role": "system", "content": system_message}]
18
+ messages.extend(history)
19
+ messages.append({"role": "user", "content": message})
20
+
21
+ response = ""
22
+ try:
23
+ for message in client.chat_completion(
24
+ messages,
25
+ max_tokens=max_tokens,
26
+ stream=True,
27
+ temperature=temperature,
28
+ top_p=top_p,
29
+ ):
30
+ choices = message.choices
31
+ token = ""
32
+ if len(choices) and choices[0].delta.content:
33
+ token = choices[0].delta.content
34
+ response += token
35
+ yield response
36
+ except Exception as e:
37
+ yield f"❌ Lỗi: {str(e)}"
38
 
39
+ # User history storage
40
+ chat_history = {}
 
 
41
 
42
+ def save_chat(user_id, message, full_response):
43
+ """Lưu lịch sử chat theo user"""
44
+ if user_id not in chat_history:
45
+ chat_history[user_id] = []
46
 
47
+ chat_history[user_id].append({
48
+ "timestamp": "14:35", # Có thể dùng datetime.now()
49
  "user": message,
50
+ "ai": full_response[-1] if full_response else "Lỗi"
51
  })
52
 
53
+ # Giữ 20 tin nhắn gần nhất
54
+ if len(chat_history[user_id]) > 20:
55
+ chat_history[user_id] = chat_history[user_id][-20:]
56
 
57
+ def load_user_history(hf_token):
58
+ """Load lịch sử từ HF token (user_id)"""
59
+ if not hf_token or not hf_token.token:
60
+ return []
61
+
62
+ # Dùng hash token làm user_id
63
+ user_id = hash(hf_token.token) % 1000000
64
+ if user_id in chat_history:
65
  return [
66
+ [
67
+ {"role": "user", "content": chat["user"]},
68
+ {"role": "assistant", "content": chat["ai"]}
69
+ ]
70
+ for chat in chat_history[user_id][-10:]
71
  ]
72
  return []
73
 
74
+ def clear_user_history(hf_token):
75
+ """Xóa lịch sử user"""
76
+ if hf_token and hf_token.token:
77
+ user_id = hash(hf_token.token) % 1000000
78
+ chat_history[user_id] = []
79
+ return []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
82
+ gr.Markdown("# 🚀 NodeAI - HF Login + Chat History")
 
83
 
84
  with gr.Row():
85
  # Sidebar - Login & History
86
+ with gr.Column(scale=1, min_width=350):
87
+ gr.Markdown("## 🔐 Hugging Face Login")
88
 
89
+ with gr.Row():
90
+ gr.LoginButton(containers=[demo])
91
+ gr.LogoutButton(containers=[demo])
 
92
 
93
+ gr.Markdown("---")
94
+ gr.Markdown("## 📚 Lịch sử Chat")
 
 
 
95
 
96
+ history_chatbot = gr.Chatbot(
97
+ height=350,
98
+ label="Lịch sử tin nhắn",
99
+ avatar_images=("👤", "🤖")
100
  )
101
+
102
+ history_btn = gr.Button("📥 Load History", variant="secondary")
103
+ clear_history_btn = gr.Button("🗑️ Clear History", variant="stop")
104
 
105
+ # Main Chat Area
106
  with gr.Column(scale=4):
107
+ chatbot = gr.ChatInterface(
108
+ respond,
109
+ additional_inputs=[
110
+ gr.Textbox(
111
+ value="Bạn là NodeAI - trợ lý AI thông minh, trả lời tiếng Việt.",
112
+ label="System Message"
113
+ ),
114
+ gr.Slider(1, 2048, value=512, step=1, label="Max Tokens"),
115
+ gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature"),
116
+ gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p"),
117
+ ],
118
+ title="NodeAI Chat",
119
+ description="Đăng nhập Hugging Face để chat và lưu lịch sử!"
120
+ )
 
 
 
 
 
121
 
122
+ # History Events
123
+ def update_history(hf_token):
124
+ history = load_user_history(hf_token)
125
+ return history
 
 
 
 
126
 
127
+ history_btn.click(
128
+ update_history,
129
+ inputs=gr.OAuthToken(),
130
+ outputs=history_chatbot
131
  )
132
 
133
+ clear_history_btn.click(
134
+ clear_user_history,
135
+ inputs=gr.OAuthToken(),
136
+ outputs=history_chatbot
137
  )
 
 
138
 
139
  if __name__ == "__main__":
140
  demo.launch()