Mokolislam1 commited on
Commit
d100f2e
·
verified ·
1 Parent(s): 9d9805f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +560 -0
app.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ বাংলা AI চ্যাটবট - Hugging Face Space ভার্সন
3
+ সম্পূর্ণ একটি ফাইলে
4
+ """
5
+
6
+ import gradio as gr
7
+ import sqlite3
8
+ import json
9
+ import numpy as np
10
+ import joblib
11
+ import bcrypt
12
+ import re
13
+ from datetime import datetime
14
+ import os
15
+
16
+ # ============================
17
+ # SIMPLE BENGALI NLP ENGINE
18
+ # ============================
19
+
20
+ class SimpleBengaliNLP:
21
+ def __init__(self):
22
+ self.bengali_stopwords = {
23
+ "এবং", "অথবা", "কিন্তু", "যদি", "তবে", "যে", "এই", "সে", "তার", "আমার",
24
+ "তোমার", "আমি", "তুমি", "আপনি", "কে", "কী", "কি", "কেন", "কিভাবে", "কোথায়",
25
+ "কখন", "হয়ে", "হয়", "একটি", "একটা", "কিছু", "সব", "না", "হ্যাঁ", "না"
26
+ }
27
+
28
+ self.intent_keywords = {
29
+ "greeting": ["হ্যালো", "হাই", "নমস্কার", "আসসালামু", "কেমন", "শুভ", "ভালো"],
30
+ "farewell": ["বিদায়", "বাই", "শুভরাত্রি", "ভালোথাকো", "আবারদেখা"],
31
+ "thanks": ["ধন্যবাদ", "থ্যাংকস", "শুকরিয়া", "কৃতজ্ঞ"],
32
+ "what": ["কী", "কি", "জানতে", "বলুন", "বর্ণনা", "উত্তর"],
33
+ "why": ["কেন", "কারণ", "কিসের", "কেনো"],
34
+ "how": ["কিভাবে", "কেমন", "উপায়", "পদ্ধতি"],
35
+ "where": ["কোথায়", "কোথা", "স্থান", "অবস্থান"],
36
+ "when": ["কখন", "সময়", "তারিখ"],
37
+ "who": ["কে", "কারা", "ব্যক্তি"]
38
+ }
39
+
40
+ def extract_keywords(self, text):
41
+ """বাংলা কীওয়ার্ড এক্সট্র্যাক্ট করুন"""
42
+ words = re.findall(r'[\u0980-\u09FF]{2,}', text.lower())
43
+ keywords = [word for word in words if word not in self.bengali_stopwords]
44
+ return list(set(keywords))[:10] # Maximum 10 keywords
45
+
46
+ def analyze_intent(self, text):
47
+ """প্রশ্নের উদ্দেশ্য বিশ্লেষণ"""
48
+ text_lower = text.lower()
49
+
50
+ for intent, keywords in self.intent_keywords.items():
51
+ for keyword in keywords:
52
+ if keyword in text_lower:
53
+ return intent
54
+
55
+ return "general"
56
+
57
+ def calculate_similarity(self, text1, text2):
58
+ """সিম্পল সিমিলারিটি ক্যালকুলেট করুন"""
59
+ words1 = set(self.extract_keywords(text1))
60
+ words2 = set(self.extract_keywords(text2))
61
+
62
+ if not words1 or not words2:
63
+ return 0.0
64
+
65
+ common = len(words1.intersection(words2))
66
+ total = len(words1.union(words2))
67
+
68
+ return common / total if total > 0 else 0.0
69
+
70
+ # ============================
71
+ # DATABASE MANAGER
72
+ # ============================
73
+
74
+ class DatabaseManager:
75
+ def __init__(self):
76
+ self.conn = sqlite3.connect('chatbot.db', check_same_thread=False)
77
+ self.init_tables()
78
+ self.initialize_data()
79
+
80
+ def init_tables(self):
81
+ cursor = self.conn.cursor()
82
+
83
+ # Users table
84
+ cursor.execute('''
85
+ CREATE TABLE IF NOT EXISTS users (
86
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
87
+ username TEXT UNIQUE NOT NULL,
88
+ email TEXT UNIQUE NOT NULL,
89
+ password_hash TEXT NOT NULL,
90
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
91
+ )
92
+ ''')
93
+
94
+ # Knowledge base
95
+ cursor.execute('''
96
+ CREATE TABLE IF NOT EXISTS knowledge (
97
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
98
+ question TEXT,
99
+ answer TEXT NOT NULL,
100
+ category TEXT,
101
+ source TEXT DEFAULT 'system',
102
+ confidence REAL DEFAULT 1.0,
103
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
104
+ )
105
+ ''')
106
+
107
+ # Chat history
108
+ cursor.execute('''
109
+ CREATE TABLE IF NOT EXISTS chats (
110
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
111
+ user_id INTEGER,
112
+ query TEXT NOT NULL,
113
+ response TEXT NOT NULL,
114
+ is_correct INTEGER DEFAULT 1,
115
+ feedback TEXT,
116
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
117
+ )
118
+ ''')
119
+
120
+ # Learning patterns
121
+ cursor.execute('''
122
+ CREATE TABLE IF NOT EXISTS patterns (
123
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
124
+ pattern_text TEXT NOT NULL,
125
+ response_template TEXT NOT NULL,
126
+ match_count INTEGER DEFAULT 1,
127
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
128
+ )
129
+ ''')
130
+
131
+ self.conn.commit()
132
+
133
+ def initialize_data(self):
134
+ cursor = self.conn.cursor()
135
+
136
+ # Check if knowledge is empty
137
+ cursor.execute("SELECT COUNT(*) FROM knowledge")
138
+ if cursor.fetchone()[0] == 0:
139
+ # Default QA pairs
140
+ default_qa = [
141
+ ("তোমার নাম কি", "আমার নাম বাংলা AI সহায়ক", "introduction"),
142
+ ("তুমি কে", "আমি একটি বাংলা AI চ্যাটবট", "introduction"),
143
+ ("তুমি কি করতে পার", "আমি বাংলা প্রশ্নের উত্তর দিতে পারি", "capability"),
144
+ ("হ্যালো", "হ্যালো! আমি বাংলা AI সহায়ক", "greeting"),
145
+ ("ধন্যবাদ", "আপনাকেও ধন্যবাদ", "greeting"),
146
+ ("বিদায়", "বিদায়! ভালো থাকবেন", "greeting"),
147
+ ("কেমন আছ", "আমি ভালো আছি, ধন্যবাদ", "greeting"),
148
+ ("বাংলাদেশের রাজধানী", "বাংলাদেশের রাজধানী ঢাকা", "geography"),
149
+ ("বাংলাদেশের প্রধানমন্ত্রী", "বাংলাদেশের প্রধানমন্ত্রী শেখ হাসিনা", "politics"),
150
+ ("তুমি কি বাংলা বলতে পার", "হ্যাঁ, আমি বাংলা বলতে পারি", "language"),
151
+ ("তোমার বয়স কত", "আমার বয়স নেই, আমি AI", "about"),
152
+ ("তুমি কি শিখতে পার", "হ্যাঁ, আমি ফিডব্যাক থেকে শিখতে পারি", "learning"),
153
+ ("কোডিং কি", "কোডিং হচ্ছে কম্পিউটার প্রোগ্রামিং", "education"),
154
+ ("পাইথন কি", "পাইথন একটি প্রোগ্রামিং ভাষা", "education"),
155
+ ("আইটি কি", "আইটি মানে ইনফরমেশন টেকনোলজি", "education"),
156
+ ("ইন্টারনেট কি", "ইন্টারনেট হলো বিশ্বব্যাপী নেটওয়ার্ক", "technology"),
157
+ ("এআই কি", "এআই মানে আর্টিফিশিয়াল ইন্টেলিজেন্স", "technology"),
158
+ ("মেশিন লার্নিং কি", "মেশিন লার্নিং AI-এর একটি শাখা", "technology"),
159
+ ("ডেটা সায়েন্স কি", "ডেটা সায়েন্স ডেটা বিশ্লেষণের বিজ্ঞান", "technology"),
160
+ ("ওয়েবসাইট কি", "ওয়েবসাইট হলো ইন্টারনেটে একটি পেজ", "technology"),
161
+ ]
162
+
163
+ for question, answer, category in default_qa:
164
+ cursor.execute(
165
+ "INSERT INTO knowledge (question, answer, category) VALUES (?, ?, ?)",
166
+ (question, answer, category)
167
+ )
168
+
169
+ self.conn.commit()
170
+
171
+ def add_user(self, username, email, password):
172
+ try:
173
+ password_hash = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
174
+ cursor = self.conn.cursor()
175
+ cursor.execute(
176
+ "INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)",
177
+ (username, email, password_hash)
178
+ )
179
+ self.conn.commit()
180
+ return cursor.lastrowid, None
181
+ except sqlite3.IntegrityError:
182
+ return None, "ইউজারনেম বা ইমেইল ইতিমধ্যে রয়েছে"
183
+ except Exception as e:
184
+ return None, str(e)
185
+
186
+ def authenticate_user(self, username, password):
187
+ cursor = self.conn.cursor()
188
+ cursor.execute(
189
+ "SELECT id, password_hash FROM users WHERE username = ?",
190
+ (username,)
191
+ )
192
+ user = cursor.fetchone()
193
+
194
+ if user and bcrypt.checkpw(password.encode('utf-8'), user[1]):
195
+ return user[0], username
196
+ return None, None
197
+
198
+ def search_knowledge(self, query, keywords=None):
199
+ cursor = self.conn.cursor()
200
+ results = []
201
+
202
+ if keywords:
203
+ for keyword in keywords:
204
+ cursor.execute(
205
+ "SELECT question, answer, confidence FROM knowledge WHERE question LIKE ? OR answer LIKE ? ORDER BY confidence DESC LIMIT 5",
206
+ (f"%{keyword}%", f"%{keyword}%")
207
+ )
208
+ results.extend(cursor.fetchall())
209
+
210
+ # Also search by full query
211
+ cursor.execute(
212
+ "SELECT question, answer, confidence FROM knowledge WHERE question LIKE ? ORDER BY confidence DESC LIMIT 5",
213
+ (f"%{query}%",)
214
+ )
215
+ results.extend(cursor.fetchall())
216
+
217
+ # Remove duplicates
218
+ unique_results = []
219
+ seen = set()
220
+ for result in results:
221
+ if result[1] not in seen:
222
+ seen.add(result[1])
223
+ unique_results.append(result)
224
+
225
+ return unique_results
226
+
227
+ def save_chat(self, user_id, query, response):
228
+ cursor = self.conn.cursor()
229
+ cursor.execute(
230
+ "INSERT INTO chats (user_id, query, response) VALUES (?, ?, ?)",
231
+ (user_id, query, response)
232
+ )
233
+ self.conn.commit()
234
+ return cursor.lastrowid
235
+
236
+ def add_feedback(self, chat_id, is_correct, corrected_text=None):
237
+ cursor = self.conn.cursor()
238
+
239
+ # Update chat
240
+ cursor.execute(
241
+ "UPDATE chats SET is_correct = ?, feedback = ? WHERE id = ?",
242
+ (1 if is_correct else 0, corrected_text, chat_id)
243
+ )
244
+
245
+ # If wrong with correction, add to knowledge
246
+ if not is_correct and corrected_text:
247
+ # Get original query
248
+ cursor.execute("SELECT query FROM chats WHERE id = ?", (chat_id,))
249
+ original_query = cursor.fetchone()
250
+
251
+ if original_query:
252
+ cursor.execute(
253
+ "INSERT INTO knowledge (question, answer, source, confidence) VALUES (?, ?, 'user_feedback', 0.9)",
254
+ (original_query[0], corrected_text)
255
+ )
256
+
257
+ self.conn.commit()
258
+
259
+ def add_knowledge(self, question, answer, category="user_added"):
260
+ cursor = self.conn.cursor()
261
+ cursor.execute(
262
+ "INSERT INTO knowledge (question, answer, category, source) VALUES (?, ?, ?, 'user')",
263
+ (question, answer, category)
264
+ )
265
+ self.conn.commit()
266
+ return cursor.lastrowid
267
+
268
+ # ============================
269
+ # CHATBOT CORE
270
+ # ============================
271
+
272
+ class BengaliChatBot:
273
+ def __init__(self):
274
+ self.db = DatabaseManager()
275
+ self.nlp = SimpleBengaliNLP()
276
+ self.current_user = {"id": None, "username": None}
277
+
278
+ # Response templates
279
+ self.templates = {
280
+ "greeting": "{}! আমি বাংলা AI সহায়ক। কিভাবে আপনাকে সাহায্য করতে পারি?",
281
+ "farewell": "{}! ভালো থাকবেন। আবার কথা হবে।",
282
+ "thanks": "{}! আমি আপনাকে সাহায্য করতে পেরে খুশি।",
283
+ "default": "দুঃখিত, আমি এই প্রশ্নের উত্তর এখনও জানি না। {}"
284
+ }
285
+
286
+ def process_query(self, query):
287
+ """প্রশ্ন প্রসেস করুন এবং উত্তর তৈরি করুন"""
288
+ if not self.current_user["id"]:
289
+ return "দয়া করে প্রথমে লগইন করুন।", None
290
+
291
+ # Analyze query
292
+ intent = self.nlp.analyze_intent(query)
293
+ keywords = self.nlp.extract_keywords(query)
294
+
295
+ # Search for answer
296
+ knowledge_results = self.db.search_knowledge(query, keywords)
297
+
298
+ if knowledge_results:
299
+ # Find best match
300
+ best_answer = None
301
+ best_score = 0
302
+
303
+ for question, answer, confidence in knowledge_results:
304
+ if question: # If it's a QA pair
305
+ similarity = self.nlp.calculate_similarity(query, question)
306
+ score = similarity * confidence
307
+
308
+ if score > best_score:
309
+ best_score = score
310
+ best_answer = answer
311
+ else: # If it's just information
312
+ if confidence > best_score:
313
+ best_score = confidence
314
+ best_answer = answer
315
+
316
+ if best_answer and best_score > 0.3:
317
+ response = best_answer
318
+ else:
319
+ response = self.get_default_response(intent)
320
+ else:
321
+ response = self.get_default_response(intent)
322
+
323
+ # Save to history
324
+ chat_id = self.db.save_chat(self.current_user["id"], query, response)
325
+
326
+ return response, chat_id
327
+
328
+ def get_default_response(self, intent):
329
+ """���িফল্ট রেসপন্স দিন"""
330
+ if intent in self.templates:
331
+ return self.templates[intent].format("আপনাকে স্বাগতম" if intent == "greeting" else "ধন্যবাদ")
332
+
333
+ return self.templates["default"].format("আপনি অন্য কোন প্রশ্ন করতে পারেন।")
334
+
335
+ def learn_from_feedback(self, chat_id, is_correct, correction=None):
336
+ """ফিডব্যাক থেকে শিখুন"""
337
+ self.db.add_feedback(chat_id, is_correct, correction)
338
+
339
+ if not is_correct and correction:
340
+ # Extract pattern and learn
341
+ self.learn_pattern(chat_id, correction)
342
+
343
+ return "ফিডব্যাক সংরক্ষিত হয়েছে"
344
+
345
+ def learn_pattern(self, chat_id, correction):
346
+ """নতুন প্যাটার্ন শিখুন"""
347
+ cursor = self.db.conn.cursor()
348
+
349
+ # Get the original query
350
+ cursor.execute("SELECT query FROM chats WHERE id = ?", (chat_id,))
351
+ result = cursor.fetchone()
352
+
353
+ if result:
354
+ query = result[0]
355
+ keywords = self.nlp.extract_keywords(query)
356
+
357
+ if keywords:
358
+ # Create pattern from keywords
359
+ pattern = " ".join(keywords[:3])
360
+
361
+ # Save pattern
362
+ cursor.execute(
363
+ "INSERT INTO patterns (pattern_text, response_template) VALUES (?, ?)",
364
+ (pattern, correction)
365
+ )
366
+ self.db.conn.commit()
367
+
368
+ # ============================
369
+ # GRADIO INTERFACE
370
+ # ============================
371
+
372
+ def create_interface():
373
+ chatbot = BengaliChatBot()
374
+
375
+ with gr.Blocks(title="বাংলা AI চ্যাটবট", theme=gr.themes.Soft()) as demo:
376
+ gr.Markdown("# 🇧🇩 বাংলা AI চ্যাটবট")
377
+ gr.Markdown("বাংলা প্রশ্ন করুন, বাংলায় উত্তর পান")
378
+
379
+ # State variables
380
+ chat_id_state = gr.State(value=None)
381
+
382
+ with gr.Tabs():
383
+ # Tab 1: Chat
384
+ with gr.TabItem("💬 চ্যাট"):
385
+ # Status display
386
+ status_display = gr.Markdown("### ⚠️ দয়া করে প্রথমে লগইন করুন")
387
+
388
+ # Chat interface
389
+ chat_interface = gr.ChatInterface(
390
+ fn=lambda msg, history: chatbot.process_query(msg)[0],
391
+ examples=[
392
+ "তোমার নাম কি",
393
+ "বাংলাদেশের রাজধানী",
394
+ "হ্যালো",
395
+ "কেমন আছ"
396
+ ],
397
+ title="বাংলায় লিখুন"
398
+ )
399
+
400
+ # Feedback section
401
+ with gr.Row():
402
+ gr.Markdown("### 👍👎 উত্তর সম্পর্কে মতামত")
403
+
404
+ correct_btn = gr.Button("👍 সঠিক")
405
+ wrong_btn = gr.Button("👎 ভুল")
406
+
407
+ correction_box = gr.Textbox(
408
+ label="সঠিক উত্তর লিখুন",
409
+ placeholder="যদি উত্তর ভুল হয়...",
410
+ visible=False
411
+ )
412
+
413
+ submit_correction = gr.Button("✅ সংরক্ষণ করুন", visible=False)
414
+ feedback_msg = gr.Markdown("")
415
+
416
+ # Feedback handlers
417
+ def mark_correct():
418
+ if chatbot.current_user["id"] and chat_id_state.value:
419
+ chatbot.learn_from_feedback(chat_id_state.value, True)
420
+ return "✅ উত্তর সঠিক বলে চিহ্নিত করা হয়েছে"
421
+ return "⚠️ প্রথমে একটি প্রশ্ন করুন"
422
+
423
+ def show_correction():
424
+ return gr.update(visible=True), gr.update(visible=True)
425
+
426
+ def save_correction(correction):
427
+ if chatbot.current_user["id"] and chat_id_state.value and correction:
428
+ chatbot.learn_from_feedback(chat_id_state.value, False, correction)
429
+ return "✅ সংশোধন সংরক্ষিত হয়েছে", gr.update(visible=False), gr.update(visible=False)
430
+ return "⚠️ দয়া করে সংশোধন লিখুন", gr.update(), gr.update()
431
+
432
+ correct_btn.click(mark_correct, outputs=[feedback_msg])
433
+ wrong_btn.click(show_correction, outputs=[correction_box, submit_correction])
434
+ submit_correction.click(save_correction, inputs=[correction_box], outputs=[feedback_msg, correction_box, submit_correction])
435
+
436
+ # Tab 2: Account
437
+ with gr.TabItem("👤 অ্যাকাউন্ট"):
438
+ with gr.Row():
439
+ # Registration
440
+ with gr.Column():
441
+ gr.Markdown("### নতুন অ্যাকাউন্ট")
442
+
443
+ reg_user = gr.Textbox(label="ইউজারনেম")
444
+ reg_email = gr.Textbox(label="ইমেইল")
445
+ reg_pass = gr.Textbox(label="পাসওয়ার্ড", type="password")
446
+ reg_confirm = gr.Textbox(label="পাসওয়ার্ড আবার", type="password")
447
+
448
+ reg_btn = gr.Button("📝 রেজিস্টার")
449
+ reg_status = gr.Markdown("")
450
+
451
+ # Login
452
+ with gr.Column():
453
+ gr.Markdown("### লগইন")
454
+
455
+ login_user = gr.Textbox(label="ইউজারনেম")
456
+ login_pass = gr.Textbox(label="পাসওয়ার্ড", type="password")
457
+
458
+ login_btn = gr.Button("🔐 লগইন")
459
+ logout_btn = gr.Button("🚪 লগআউট")
460
+
461
+ login_status = gr.Markdown("")
462
+
463
+ # Handlers
464
+ def register(username, email, password, confirm):
465
+ if password != confirm:
466
+ return "❌ পাসওয়ার্ড মিলছে না"
467
+
468
+ if len(password) < 6:
469
+ return "❌ পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে"
470
+
471
+ user_id, error = chatbot.db.add_user(username, email, password)
472
+
473
+ if user_id:
474
+ return "✅ রেজিস্ট্রেশন সফল! এখন লগইন করুন"
475
+ else:
476
+ return f"❌ {error}"
477
+
478
+ def login(username, password):
479
+ user_id, username_msg = chatbot.db.authenticate_user(username, password)
480
+
481
+ if user_id:
482
+ chatbot.current_user = {"id": user_id, "username": username_msg}
483
+ return f"✅ লগইন সফল! স্বাগতম {username_msg}", f"### 👤 লগইন করেছেন: {username_msg}"
484
+ else:
485
+ return "❌ ভুল ইউজারনেম বা পাসওয়ার্ড", "### ⚠️ দয়া করে লগইন করুন"
486
+
487
+ def logout():
488
+ chatbot.current_user = {"id": None, "username": None}
489
+ return "✅ লগআউট সফল", "### ⚠️ দয়া করে লগইন করুন"
490
+
491
+ reg_btn.click(register, inputs=[reg_user, reg_email, reg_pass, reg_confirm], outputs=[reg_status])
492
+ login_btn.click(login, inputs=[login_user, login_pass], outputs=[login_status, status_display])
493
+ logout_btn.click(logout, outputs=[login_status, status_display])
494
+
495
+ # Tab 3: Knowledge Base
496
+ with gr.TabItem("📚 জ্ঞানভাণ্ডার"):
497
+ gr.Markdown("### জ্ঞানভাণ্ডার ব্যবস্থাপনা")
498
+
499
+ know_question = gr.Textbox(label="প্রশ্ন (ঐচ্ছিক)")
500
+ know_answer = gr.Textbox(label="উত্তর/তথ্য", lines=3)
501
+ know_category = gr.Textbox(label="বিষয় (ঐচ্ছিক)")
502
+
503
+ add_know_btn = gr.Button("➕ যোগ করুন")
504
+ know_status = gr.Markdown("")
505
+
506
+ search_box = gr.Textbox(label="খুঁজুন")
507
+ search_btn = gr.Button("🔍 অনুসন্ধান")
508
+ search_results = gr.Markdown("")
509
+
510
+ def add_knowledge(question, answer, category):
511
+ if not answer:
512
+ return "❌ উত্তর/তথ্য লিখুন"
513
+
514
+ if chatbot.current_user["id"]:
515
+ chatbot.db.add_knowledge(question if question else "", answer, category if category else "general")
516
+ return "✅ তথ্য যোগ করা হয়েছে"
517
+ else:
518
+ return "❌ লগইন প্রয়োজন"
519
+
520
+ def search_knowledge(query):
521
+ if not query:
522
+ return "খুঁজার জন্য কিছু লিখুন"
523
+
524
+ results = chatbot.db.search_knowledge(query, chatbot.nlp.extract_keywords(query))
525
+
526
+ if results:
527
+ text = "### 🔍 ফলাফল:\n\n"
528
+ for i, (question, answer, confidence) in enumerate(results[:5], 1):
529
+ text += f"{i}. "
530
+ if question:
531
+ text += f"**প্রশ্ন:** {question}\n"
532
+ text += f" **উত্তর:** {answer}\n\n"
533
+ return text
534
+ else:
535
+ return "কোন ফলাফল পাওয়া যায়নি"
536
+
537
+ add_know_btn.click(add_knowledge, inputs=[know_question, know_answer, know_category], outputs=[know_status])
538
+ search_btn.click(search_knowledge, inputs=[search_box], outputs=[search_results])
539
+
540
+ # Update chat ID after each response
541
+ def update_chat_id(history):
542
+ response, chat_id = chatbot.process_query(history[-1][0]) if history else ("", None)
543
+ return gr.update(value=chat_id)
544
+
545
+ chat_interface.chatbot.change(update_chat_id, inputs=[chat_interface.chatbot], outputs=[chat_id_state])
546
+
547
+ return demo
548
+
549
+ # ============================
550
+ # MAIN EXECUTION
551
+ # ============================
552
+
553
+ if __name__ == "__main__":
554
+ # Create and launch interface
555
+ demo = create_interface()
556
+ demo.launch(
557
+ server_name="0.0.0.0",
558
+ server_port=7860,
559
+ share=False
560
+ )