Really-amin commited on
Commit
cb6a352
·
verified ·
1 Parent(s): 666e68a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +363 -128
app.py CHANGED
@@ -1,132 +1,367 @@
1
  import streamlit as st
2
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
3
-
4
- # تنظیمات ادمین
5
- ADMIN_USERNAME = "admin"
6
- ADMIN_PASSWORD = "password"
7
-
8
- # CSS برای ظاهر برنامه
9
- CUSTOM_CSS = """
10
- <style>
11
- body {
12
- font-family: 'Vazir', sans-serif;
13
- background: linear-gradient(135deg, #e8effa, #ffffff);
14
- }
15
- .chat-container {
16
- max-width: 400px;
17
- margin: 0 auto;
18
- border-radius: 15px;
19
- box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
20
- }
21
- .header {
22
- background: linear-gradient(135deg, #4a90e2, #50e3c2);
23
- color: white;
24
- padding: 10px;
25
- text-align: center;
26
- font-weight: bold;
27
- font-size: 18px;
28
- }
29
- .message {
30
- padding: 12px 15px;
31
- margin: 10px 0;
32
- border-radius: 15px;
33
- width: fit-content;
34
- max-width: 80%;
35
- font-size: 15px;
36
- }
37
- .message.user {
38
- align-self: flex-end;
39
- background: #4a90e2;
40
- color: white;
41
- }
42
- .message.bot {
43
- align-self: flex-start;
44
- background: #ff6b6b;
45
- color: white;
46
- }
47
- .footer {
48
- display: flex;
49
- padding: 10px;
50
- background: #f5f5f5;
51
- align-items: center;
52
  }
53
- .footer input[type="text"] {
54
- flex: 1;
55
- padding: 10px;
56
- border: none;
57
- border-radius: 20px;
58
- background: #ffffff;
59
- margin-right: 10px;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  }
61
- </style>
62
- """
63
- st.markdown(CUSTOM_CSS, unsafe_allow_html=True)
64
-
65
- class ModernChatbot:
66
- def __init__(self):
67
- # تنظیم بارگذاری تنبل مدل
68
- if "model_loaded" not in st.session_state:
69
- st.session_state.model_loaded = False
70
-
71
- def load_model(self):
72
- """بارگذاری مدل و توکنایزر تنها در صورت نیاز"""
73
- if not st.session_state.model_loaded:
74
- model_name = "HuggingFaceH4/zephyr-7b-beta"
75
- st.session_state.tokenizer = AutoTokenizer.from_pretrained(model_name)
76
- st.session_state.model = AutoModelForCausalLM.from_pretrained(model_name)
77
- st.session_state.chat_pipeline = pipeline(
78
- "text-generation",
79
- model=st.session_state.model,
80
- tokenizer=st.session_state.tokenizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  )
82
- st.session_state.model_loaded = True
83
-
84
- def generate_response(self, message):
85
- """تولید پاسخ با مدل بارگذاری شده"""
86
- self.load_model()
87
- response = st.session_state.chat_pipeline(
88
- message, max_length=50, num_return_sequences=1
89
- )[0]['generated_text']
90
- return response
91
-
92
- def login_admin(self, username, password):
93
- """ورود به عنوان مدیر"""
94
- return username == ADMIN_USERNAME and password == ADMIN_PASSWORD
95
-
96
- # ذخیره تاریخچه مکالمات و وضعیت ورود ادمین در session_state
97
- if "conversation_history" not in st.session_state:
98
- st.session_state.conversation_history = []
99
-
100
- # ایجاد نمونه چت‌بات
101
- chatbot = ModernChatbot()
102
-
103
- # آیکون و پاپ‌آپ ورود ادمین
104
- if st.sidebar.button("ورود ادمین"):
105
- username = st.sidebar.text_input("نام کاربری")
106
- password = st.sidebar.text_input("رمز عبور", type="password")
107
- if st.sidebar.button("تایید"):
108
- if chatbot.login_admin(username, password):
109
- st.session_state.admin_logged_in = True
110
- st.sidebar.success("ورود موفقیت‌آمیز بود")
111
- else:
112
- st.sidebar.error("نام کاربری یا رمز عبور اشتباه است")
113
-
114
- # نمایش مکالمات
115
- st.markdown("<div class='chat-container'><div class='header'>چت‌بات هوشمند</div>", unsafe_allow_html=True)
116
- for sender, message in st.session_state.conversation_history:
117
- align_class = "user" if sender == "شما" else "bot"
118
- st.markdown(f"<div class='message {align_class}'>{sender}: {message}</div>", unsafe_allow_html=True)
119
- st.markdown("</div>", unsafe_allow_html=True)
120
-
121
- # ورودی پیام کاربر
122
- user_message = st.text_input("پیام خود را اینجا بنویسید...", key="user_message")
123
- if st.button("ارسال") and user_message:
124
- st.session_state.conversation_history.append(("شما", user_message))
125
- response = chatbot.generate_response(user_message)
126
- st.session_state.conversation_history.append(("ربات", response))
127
- st.experimental_rerun()
128
-
129
- # پاک‌سازی مکالمات
130
- if st.sidebar.button("پاک کردن تاریخچه مکالمات"):
131
- st.session_state.conversation_history = []
132
- st.experimental_rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import gradio as gr
3
+ from datetime import datetime
4
+ import persianutils as pu
5
+ from transformers import pipeline
6
+
7
+ # تنظیمات پایه
8
+ SETTINGS = {
9
+ "dark_mode": False,
10
+ "font_size": 14,
11
+ "language": "fa",
12
+ "theme_color": "#fa8721"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  }
14
+
15
+ # پیام‌های پیش‌فرض
16
+ DEFAULT_MESSAGES = [
17
+ "سلام! چطور می‌تونم کمکتون کنم؟",
18
+ "خوشحالم که اینجا هستید!",
19
+ "بفرمایید، در خدمتم"
20
+ ]
21
+
22
+ # آیکون‌های SVG
23
+ ICONS = {
24
+ 'settings': '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
25
+ <circle cx="12" cy="12" r="3"/>
26
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
27
+ </svg>''',
28
+ 'user': '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
29
+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
30
+ <circle cx="12" cy="7" r="4"/>
31
+ </svg>''',
32
+ 'send': '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
33
+ <line x1="22" y1="2" x2="11" y2="13"/>
34
+ <polygon points="22 2 15 22 11 13 2 9 22 2"/>
35
+ </svg>'''
36
  }
37
+
38
+ # تابع پردازش پیام و تاریخ
39
+ def chat_assistant(message, history):
40
+ """پردازش پیام و تولید پاسخ"""
41
+ current_time = pu.convert_en_numbers(datetime.now().strftime("%H:%M"))
42
+ response = DEFAULT_MESSAGES[0] # پیام پیش‌فرض
43
+ history = history + [(message, response)]
44
+ return "", history
45
+
46
+ # تابع ساخت رابط کاربری
47
+ def create_interface():
48
+ """ساخت رابط کاربری"""
49
+ with gr.Blocks(css=get_custom_css()) as demo:
50
+ # هدر
51
+ gr.HTML(create_header())
52
+
53
+ # بخش چت
54
+ chatbox = gr.Chatbot(
55
+ elem_id="chatbox",
56
+ label="چت با دستیار",
57
+ placeholder="پیام خود را تایپ کنید...",
58
+ height="70vh"
59
+ )
60
+
61
+ # بخش ورودی
62
+ with gr.Row():
63
+ with gr.Column(scale=10):
64
+ msg_box = gr.Textbox(
65
+ show_label=False,
66
+ placeholder="پیام خود را بنویسید...",
67
+ elem_id="message-box"
68
+ )
69
+ with gr.Column(scale=2):
70
+ send_btn = gr.Button(
71
+ "ارسال",
72
+ variant="primary",
73
+ elem_id="send-button"
74
+ )
75
+
76
+ # تنظیمات
77
+ with gr.Accordion("تنظیمات", open=False):
78
+ dark_mode = gr.Checkbox(
79
+ label="حالت شب",
80
+ value=SETTINGS["dark_mode"]
81
+ )
82
+ font_size = gr.Slider(
83
+ minimum=12,
84
+ maximum=20,
85
+ value=SETTINGS["font_size"],
86
+ label="اندازه فونت"
87
  )
88
+ language = gr.Dropdown(
89
+ choices=["فارسی", "English"],
90
+ value="فارسی",
91
+ label="زبان"
92
+ )
93
+
94
+ # رویدادها
95
+ msg_box.submit(
96
+ chat_assistant,
97
+ [msg_box, chatbox],
98
+ [msg_box, chatbox]
99
+ )
100
+ send_btn.click(
101
+ chat_assistant,
102
+ [msg_box, chatbox],
103
+ [msg_box, chatbox]
104
+ )
105
+
106
+ return demo
107
+
108
+ # تابع برای اضافه کردن استایل‌های سفارشی
109
+ def get_custom_css():
110
+ """استایل‌های سفارشی"""
111
+ return """
112
+ @font-face {
113
+ font-family: 'Vazir';
114
+ src: url('https://cdn.jsdelivr.net/gh/rastikerdar/[email protected]/dist/Vazir.woff2') format('woff2');
115
+ }
116
+
117
+ * {
118
+ font-family: 'Vazir', Arial, sans-serif;
119
+ direction: rtl;
120
+ }
121
+
122
+ .container {
123
+ max-width: 800px;
124
+ margin: 0 auto;
125
+ padding: 20px;
126
+ }
127
+
128
+ .chat-area {
129
+ height: 500px;
130
+ overflow-y: auto;
131
+ padding: 20px;
132
+ background: #f5f5f5;
133
+ border-radius: 10px;
134
+ }
135
+
136
+ .message {
137
+ margin: 10px 0;
138
+ padding: 10px;
139
+ border-radius: 10px;
140
+ animation: fadeIn 0.3s ease-out;
141
+ }
142
+
143
+ .user-message {
144
+ background: white;
145
+ margin-left: 20%;
146
+ }
147
+
148
+ .bot-message {
149
+ background: #fa8721;
150
+ color: white;
151
+ margin-right: 20%;
152
+ }
153
+
154
+ @keyframes fadeIn {
155
+ from { opacity: 0; transform: translateY(10px); }
156
+ to { opacity: 1; transform: translateY(0); }
157
+ }
158
+ """
159
+
160
+ # تابع برای ساخت هدر
161
+ def create_header():
162
+ """ساخت هدر"""
163
+ return f"""
164
+ <div class="header">
165
+ <div class="logo">
166
+ {ICONS['user']}
167
+ <h1>دستیار هوشمند</h1>
168
+ </div>
169
+ <div class="settings">
170
+ {ICONS['settings']}
171
+ </div>
172
+ </div>
173
+ """
174
+
175
+ # تنظیمات صفحه Streamlit
176
+ def setup_page():
177
+ st.set_page_config(
178
+ page_title="دستیار هوشمند فارسی",
179
+ page_icon="🤖",
180
+ layout="centered"
181
+ )
182
+
183
+ # استایل‌های سفارشی Streamlit
184
+ def apply_custom_styles():
185
+ st.markdown("""
186
+ <style>
187
+ @font-face {
188
+ font-family: 'Vazir';
189
+ src: url('https://cdn.jsdelivr.net/gh/rastikerdar/[email protected]/dist/Vazir.woff2') format('woff2');
190
+ }
191
+
192
+ body {
193
+ font-family: 'Vazir', Arial, sans-serif;
194
+ direction: rtl;
195
+ background: #f4f4f4;
196
+ color: #333;
197
+ margin: 0;
198
+ padding: 0;
199
+ }
200
+
201
+ .chat-container {
202
+ max-width: 900px;
203
+ margin: 50px auto;
204
+ padding: 20px;
205
+ background-color: white;
206
+ border-radius: 10px;
207
+ box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
208
+ }
209
+
210
+ .header {
211
+ display: flex;
212
+ justify-content: space-between;
213
+ padding: 10px;
214
+ }
215
+
216
+ .logo {
217
+ display: flex;
218
+ align-items: center;
219
+ }
220
+
221
+ .logo h1 {
222
+ margin-left: 10px;
223
+ }
224
+
225
+ .send-button {
226
+ background-color: #fa8721;
227
+ color: white;
228
+ padding: 12px 16px;
229
+ border-radius: 50%;
230
+ border: none;
231
+ cursor: pointer;
232
+ transition: background-color 0.3s ease;
233
+ }
234
+
235
+ .send-button:hover {
236
+ background-color: #f78f34;
237
+ }
238
+ </style>
239
+ """, unsafe_allow_html=True)
240
+
241
+ # هدر صفحه
242
+ def display_header():
243
+ st.markdown("""
244
+ <div class="container">
245
+ <div class="header">
246
+ <div class="header-icons">
247
+ <div class="icon">
248
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 20h.01"></path><path d="M7 20v-4"></path><path d="M12 20v-8"></path><path d="M17 20V8"></path></svg>
249
+ </div>
250
+ <div class="icon">
251
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 20h.01"></path><path d="M2 8.82a15 15 0 0 1 20 0"></path><path d="M5 12.859a10 10 0 0 1 14 0"></path><path d="M8.5 16.429a5 5 0 0 1 7 0"></path></svg>
252
+ </div>
253
+ <div class="icon">
254
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="16" height="10" x="2" y="7" rx="2" ry="2"></rect><line x1="22" x2="22" y1="11" y2="13"></line></svg>
255
+ </div>
256
+ <div class="settings-button">
257
+ <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2a10 10 0 0 1 10 10c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2"></path><circle cx="12" cy="12" r="3"></circle><path d="M12 8v1M12 15v1M8 12h1M15 12h1"></path></svg>
258
+ </div>
259
+ </div>
260
+ <div class="header-buttons">
261
+ <button>
262
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
263
+ <circle cx="12" cy="12" r="5"/>
264
+ <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"/>
265
+ </svg>
266
+ </button>
267
+ <button>
268
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
269
+ <path d="M3 12h18M3 6h18M3 18h18"/>
270
+ </svg>
271
+ </button>
272
+ </div>
273
+ <h1>
274
+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
275
+ <path d="M12 2a10 10 0 0 1 10 10c0 5.523-4.477 10-10 10S2 17.523 2 12 6.477 2 12 2"/>
276
+ <circle cx="12" cy="12" r="3"/>
277
+ <path d="M12 8v1M12 15v1M8 12h1M15 12h1"/>
278
+ </svg>
279
+ دستیار هوشمند
280
+ </h1>
281
+ <div class="admin-avatar">
282
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
283
+ <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
284
+ <circle cx="12" cy="7" r="4"/>
285
+ </svg>
286
+ </div>
287
+ </div>
288
+ </div>
289
+ """, unsafe_allow_html=True)
290
+
291
+ # بخش چت
292
+ def display_chat():
293
+ st.markdown("""
294
+ <div class="chat-container">
295
+ <div class="chat-bubble left">
296
+ سلام! من دستیار هوشمند شما هستم. چطور میتونم کمکتون کنم؟
297
+ </div>
298
+ <div class="chat-bubble right">
299
+ سلام، خوشحالم که اینجایی
300
+ </div>
301
+ <div class="chat-bubble left">
302
+ ممنون! من آماده‌ام به سوالات شما پاسخ بدم
303
+ </div>
304
+ <div class="typing-indicator">
305
+ <div class="typing-dot"></div>
306
+ <div class="typing-dot"></div>
307
+ <div class="typing-dot"></div>
308
+ </div>
309
+ </div>
310
+ """, unsafe_allow_html=True)
311
+
312
+ # بخش ورودی
313
+ def display_input():
314
+ st.markdown("""
315
+ <div class="input-container">
316
+ <input type="text" placeholder="پیام خود را بنویسید..." id="user-input">
317
+ <button onclick="sendMessage()">
318
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
319
+ <line x1="22" y1="2" x2="11" y2="13"/>
320
+ <polygon points="22 2 15 22 11 13 2 9 22 2"/>
321
+ </svg>
322
+ </button>
323
+ </div>
324
+ """, unsafe_allow_html=True)
325
+
326
+ st.markdown("""
327
+ <script>
328
+ function sendMessage() {
329
+ const userInput = document.getElementById('user-input').value;
330
+ if (userInput) {
331
+ const chatContainer = document.querySelector('.chat-container');
332
+ const userMessage = document.createElement('div');
333
+ userMessage.classList.add('chat-bubble', 'right');
334
+ userMessage.textContent = userInput;
335
+ chatContainer.appendChild(userMessage);
336
+
337
+ // Simulate bot response
338
+ setTimeout(() => {
339
+ const botMessage = document.createElement('div');
340
+ botMessage.classList.add('chat-bubble', 'left');
341
+ botMessage.textContent = 'پاسخ به پیام شما: ' + userInput;
342
+ chatContainer.appendChild(botMessage);
343
+ chatContainer.scrollTop = chatContainer.scrollHeight;
344
+ }, 1000);
345
+
346
+ document.getElementById('user-input').value = '';
347
+ }
348
+ }
349
+ </script>
350
+ """, unsafe_allow_html=True)
351
+
352
+ # اجرای توابع
353
+ setup_page()
354
+ apply_custom_styles()
355
+ display_header()
356
+ display_chat()
357
+ display_input()
358
+
359
+ # اجرای برنامه Gradio
360
+ if __name__ == "__main__":
361
+ # توکن احراز هویت Hugging Face را اینجا قرار دهید
362
+ token = "YOUR_HUGGINGFACE_TOKEN"
363
+
364
+ # استفاده از توکن برای دسترسی به مدل خصوصی
365
+ nlp_pipeline = pipeline("text-generation", model="HooshvareLab/gpt2-fa-zwnj", token=token)
366
+
367
+ create_interface().launch(share=True)