File size: 31,754 Bytes
cdecdab
cd85d8c
 
aa409b7
9717c6f
989f90a
d6d3e62
 
 
 
 
85241d2
9717c6f
d6d3e62
 
 
 
 
aa409b7
cd85d8c
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
85241d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6d3e62
 
 
 
 
 
 
ea38749
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d545b79
d6d3e62
 
 
d545b79
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a986547
d6d3e62
 
d545b79
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b599af
d6d3e62
 
0b599af
d6d3e62
 
 
f6eafcd
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
d6d3e62
 
 
85241d2
d6d3e62
 
 
 
 
 
 
 
 
 
 
f6eafcd
 
d6d3e62
85241d2
 
 
 
 
 
 
 
 
 
f6eafcd
 
 
 
 
d6d3e62
 
 
 
 
f6eafcd
d6d3e62
85241d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6eafcd
 
 
 
d28c29c
f6eafcd
 
d28c29c
f6eafcd
 
 
 
 
 
 
 
 
 
 
 
d6d3e62
d28c29c
f6eafcd
 
 
 
 
 
 
 
 
 
d6d3e62
f6eafcd
 
 
 
 
 
 
d28c29c
f6eafcd
 
 
 
 
 
 
 
 
 
d6d3e62
f6eafcd
 
d6d3e62
 
 
 
f6eafcd
 
d6d3e62
 
f6eafcd
 
 
 
 
 
 
 
 
d6d3e62
 
d28c29c
f6eafcd
 
 
 
d6d3e62
 
 
f6eafcd
 
 
 
d28c29c
 
f6eafcd
 
 
 
 
 
 
 
 
 
 
 
d28c29c
f6eafcd
d28c29c
f6eafcd
d28c29c
f6eafcd
d28c29c
f6eafcd
d28c29c
f6eafcd
d28c29c
f6eafcd
 
 
 
 
 
 
 
 
 
d6d3e62
f6eafcd
 
 
385e2fc
f6eafcd
 
d28c29c
f6eafcd
d28c29c
f6eafcd
 
 
d28c29c
f6eafcd
 
 
 
 
 
 
 
 
 
 
 
 
 
d28c29c
f6eafcd
 
 
 
 
 
d28c29c
f6eafcd
 
 
 
d28c29c
f6eafcd
 
 
 
 
 
d28c29c
f6eafcd
c381e78
d6d3e62
 
b754287
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d28c29c
0b599af
f6eafcd
d6d3e62
 
 
 
 
f6eafcd
e6a5408
 
d6d3e62
 
e6a5408
 
d6d3e62
 
 
e6a5408
d6d3e62
 
 
 
e6a5408
d6d3e62
 
e6a5408
d6d3e62
 
 
e6a5408
d6d3e62
 
 
e6a5408
 
d6d3e62
 
f6eafcd
d6d3e62
 
f6eafcd
e6a5408
 
f6eafcd
 
 
 
e6a5408
d6d3e62
 
 
 
 
f6eafcd
e6a5408
 
 
f6eafcd
 
 
e6a5408
f6eafcd
 
 
 
 
 
 
 
e6a5408
f6eafcd
 
 
e6a5408
f6eafcd
 
 
e6a5408
f6eafcd
 
 
 
 
 
 
 
 
 
 
 
d6d3e62
 
9bba096
d6d3e62
d28c29c
b754287
d545b79
d6d3e62
85241d2
 
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d28c29c
d6d3e62
 
 
 
 
 
d28c29c
d6d3e62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85241d2
d6d3e62
d545b79
d6d3e62
 
 
 
 
ea38749
b754287
d6d3e62
 
 
 
 
85241d2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
import gradio as gr
from sentence_transformers import SentenceTransformer, util
import torch
import logging
import re
import os
from typing import List, Tuple, Dict
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import json
from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# Initialize models
try:
    logger.info("Loading Arabic language model...")
    # Using a more robust Arabic model
    model = SentenceTransformer(
        "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
        device="cuda" if torch.cuda.is_available() else "cpu"
    )
    logger.info(f"Model loaded on {model.device}")
except Exception as e:
    logger.error(f"Model loading failed: {str(e)}")
    raise RuntimeError("Failed to initialize the AI model")

# Initialize Arabic LLM for text generation and rephrasing
try:
    logger.info("Loading Arabic LLM for text generation...")
    # Using ArabianGPT for Arabic text generation
    llm_model_name = "riotu-lab/ArabianGPT-01B"
    
    # Load tokenizer and model
    llm_tokenizer = AutoTokenizer.from_pretrained(llm_model_name)
    llm_model = AutoModelForCausalLM.from_pretrained(
        llm_model_name,
        torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
        device_map="auto" if torch.cuda.is_available() else None
    )
    
    # Create text generation pipeline
    text_generator = pipeline(
        "text-generation",
        model=llm_model,
        tokenizer=llm_tokenizer,
        max_length=512,
        do_sample=True,
        temperature=0.7,
        top_p=0.9,
        pad_token_id=llm_tokenizer.eos_token_id
    )
    
    logger.info("Arabic LLM loaded successfully")
    llm_available = True
    
except Exception as e:
    logger.warning(f"LLM loading failed: {str(e)}. Falling back to basic response generation.")
    text_generator = None
    llm_available = False

# Initialize TF-IDF for hybrid search
tfidf_vectorizer = TfidfVectorizer(
    max_features=1000,
    stop_words=None,  # Keep Arabic stop words
    ngram_range=(1, 2),
    analyzer='word'
)

class KnowledgeBase:
    def __init__(self):
        self.chunks = []
        self.embeddings = None
        self.tfidf_matrix = None
        self.section_mapping = {}
        
    def load_and_process_knowledge(self) -> None:
        """Enhanced knowledge loading with better chunking strategy"""
        try:
            knowledge_file = "knowledge.txt"
            if not os.path.exists(knowledge_file):
                raise FileNotFoundError(f"{knowledge_file} file not found")
                
            with open(knowledge_file, "r", encoding="utf-8") as f:
                content = f.read().strip()
                if not content:
                    raise ValueError(f"{knowledge_file} is empty")
            
            sections = {}
            current_section = "ู…ุนู„ูˆู…ุงุช ุนุงู…ุฉ"
            
            with open(knowledge_file, "r", encoding="utf-8") as f:
                for line in f:
                    line = line.strip()
                    if line.startswith("## "):
                        current_section = line[3:].strip()
                        sections[current_section] = []
                    elif line and current_section:
                        sections[current_section].append(line)
            
            # Enhanced chunking strategy
            self.chunks = []
            chunk_id = 0
            
            for section, content_list in sections.items():
                section_text = " ".join(content_list)
                
                # Split into meaningful chunks while preserving context
                if len(section_text) <= 200:
                    # Small sections: keep as single chunk
                    chunk_text = f"{section}: {section_text}"
                    self.chunks.append(chunk_text)
                    self.section_mapping[chunk_id] = section
                    chunk_id += 1
                else:
                    # Large sections: split intelligently
                    sentences = re.split(r'(?<=[.!?\n])\s+', section_text)
                    current_chunk = ""
                    
                    for sent in sentences:
                        sent = sent.strip()
                        if not sent:
                            continue
                        
                        # Check if adding this sentence exceeds optimal chunk size
                        if len(current_chunk) + len(sent) < 180:
                            current_chunk += " " + sent if current_chunk else sent
                        else:
                            if current_chunk:
                                chunk_text = f"{section}: {current_chunk}"
                                self.chunks.append(chunk_text)
                                self.section_mapping[chunk_id] = section
                                chunk_id += 1
                            current_chunk = sent
                    
                    # Add remaining chunk
                    if current_chunk:
                        chunk_text = f"{section}: {current_chunk}"
                        self.chunks.append(chunk_text)
                        self.section_mapping[chunk_id] = section
                        chunk_id += 1
            
            # Generate embeddings
            self.embeddings = model.encode(self.chunks, convert_to_tensor=True)
            
            # Generate TF-IDF matrix for hybrid search
            self.tfidf_matrix = tfidf_vectorizer.fit_transform(self.chunks)
            
            logger.info(f"Loaded {len(self.chunks)} knowledge chunks from {len(sections)} sections")
            
        except Exception as e:
            logger.error(f"Knowledge loading error: {str(e)}")
            self.chunks = ["ุนุงู…: ุงู„ู†ุธุงู… ุฌุงู‡ุฒ ู„ู„ุฑุฏ ุนู„ู‰ ุงุณุชูุณุงุฑุงุชูƒ. ูŠุฑุฌู‰ ุทุฑุญ ุณุคุงู„ูƒ."]
            self.embeddings = model.encode(self.chunks, convert_to_tensor=True)
            self.tfidf_matrix = tfidf_vectorizer.fit_transform(self.chunks)

# Initialize knowledge base
kb = KnowledgeBase()
kb.load_and_process_knowledge()

class ArabicQueryProcessor:
    def __init__(self):
        # Enhanced Arabic text normalization patterns
        self.normalization_patterns = {
            # Normalize Arabic characters
            r'[ุฃุฅุขุง]': 'ุง',
            r'[ู‰ูŠ]': 'ูŠ',
            r'[ุคูˆ]': 'ูˆ',
            r'[ุฉู‡]': 'ู‡',
            
            # Question word normalization
            r'\bู…ุงู‡ูŠ\b': 'ู…ุง ู‡ูŠ',
            r'\bู…ุงู‡ูˆ\b': 'ู…ุง ู‡ูˆ',
            r'\bูƒูŠููŠุฉ\b': 'ูƒูŠู',
            r'\bุทุฑูŠู‚ุฉ\b': 'ูƒูŠู',
            r'\bุงุฑูŠุฏ\b': 'ูƒูŠู ูŠู…ูƒู†',
            r'\bุนุงูˆุฒ\b': 'ูƒูŠู ูŠู…ูƒู†',
            r'\bุนุงูŠุฒ\b': 'ูƒูŠู ูŠู…ูƒู†',
            r'\bุงุฒุงูŠ\b': 'ูƒูŠู',
            r'\bุงูŠู‡\b': 'ู…ุง',
            r'\bู…ูŠู†\b': 'ู…ู†',
            r'\bููŠู†\b': 'ุฃูŠู†',
            r'\bุงู…ุชู‰\b': 'ู…ุชู‰',
            
            # Common variations
            r'\bุงู„ู…ูˆุงุฒู†ู‡\b': 'ุงู„ู…ูˆุงุฒู†ุฉ',
            r'\bุงู„ุดูุงููŠู‡\b': 'ุงู„ุดูุงููŠุฉ',
            r'\bุงู„ู…ุดุงุฑูƒู‡\b': 'ุงู„ู…ุดุงุฑูƒุฉ',
        }
        
        # Question type classification
        self.question_types = {
            'definition': [r'\bู…ุง ู‡ูŠ\b', r'\bู…ุง ู‡ูˆ\b', r'\bุชุนุฑูŠู\b', r'\bู…ุนู†ู‰\b'],
            'how': [r'\bูƒูŠู\b', r'\bูƒูŠููŠุฉ\b', r'\bุทุฑูŠู‚ุฉ\b'],
            'why': [r'\bู„ู…ุงุฐุง\b', r'\bู„ูŠู‡\b', r'\bุณุจุจ\b'],
            'who': [r'\bู…ู†\b', r'\bู…ูŠู†\b'],
            'when': [r'\bู…ุชู‰\b', r'\bุงู…ุชู‰\b'],
            'where': [r'\bุฃูŠู†\b', r'\bููŠู†\b'],
            'list': [r'\bุงุฐูƒุฑ\b', r'\bุนุฏุฏ\b', r'\bู‚ุงุฆู…ุฉ\b', r'\bุฃู†ูˆุงุน\b']
        }
    
    def normalize_text(self, text: str) -> str:
        """Apply comprehensive Arabic text normalization"""
        text = text.strip()
        
        # Apply normalization patterns
        for pattern, replacement in self.normalization_patterns.items():
            text = re.sub(pattern, replacement, text)
        
        # Remove extra whitespace and punctuation
        text = re.sub(r'[ุŸ\?ุŒ,\.]+', '', text)
        text = re.sub(r'\s+', ' ', text)
        
        return text.strip()
    
    def classify_question_type(self, question: str) -> str:
        """Classify the type of question to improve response generation"""
        question_lower = question.lower()
        
        for q_type, patterns in self.question_types.items():
            for pattern in patterns:
                if re.search(pattern, question_lower):
                    return q_type
        
        return 'general'
    
    def extract_keywords(self, question: str) -> List[str]:
        """Extract key terms from the question for better matching"""
        # Remove common question words and focus on content words
        stop_words = {
            'ู…ุง', 'ู‡ูŠ', 'ู‡ูˆ', 'ูƒูŠู', 'ู„ู…ุงุฐุง', 'ู…ุชู‰', 'ุฃูŠู†', 'ู…ู†', 'ููŠ', 'ุนู„ู‰', 'ุฅู„ู‰',
            'ุนู†', 'ู…ุน', 'ู‡ุฐุง', 'ู‡ุฐู‡', 'ุฐู„ูƒ', 'ุชู„ูƒ', 'ุงู„ุชูŠ', 'ุงู„ุฐูŠ', 'ูŠู…ูƒู†', 'ูŠุฌุจ'
        }
        
        words = question.split()
        keywords = [word for word in words if word not in stop_words and len(word) > 2]
        
        return keywords

# Initialize query processor
query_processor = ArabicQueryProcessor()

class HybridRetriever:
    def __init__(self, kb: KnowledgeBase, alpha: float = 0.7):
        self.kb = kb
        self.alpha = alpha  # Weight for semantic similarity vs TF-IDF
    
    def retrieve(self, question: str, top_k: int = 5) -> List[Tuple[str, float, str]]:
        """Hybrid retrieval combining semantic and lexical matching"""
        try:
            # Semantic search using sentence transformers
            question_embedding = model.encode(question, convert_to_tensor=True)
            semantic_scores = util.cos_sim(question_embedding, self.kb.embeddings)[0]
            
            # Lexical search using TF-IDF
            question_tfidf = tfidf_vectorizer.transform([question])
            lexical_scores = cosine_similarity(question_tfidf, self.kb.tfidf_matrix)[0]
            
            # Combine scores
            combined_scores = []
            for i in range(len(self.kb.chunks)):
                semantic_score = semantic_scores[i].item()
                lexical_score = lexical_scores[i]
                
                # Weighted combination
                combined_score = self.alpha * semantic_score + (1 - self.alpha) * lexical_score
                combined_scores.append((i, combined_score, semantic_score))
            
            # Sort by combined score
            combined_scores.sort(key=lambda x: x[1], reverse=True)
            
            # Return top results with minimum threshold
            results = []
            for idx, combined_score, semantic_score in combined_scores[:top_k]:
                if combined_score > 0.3:  # Adjusted threshold
                    chunk = self.kb.chunks[idx]
                    section = self.kb.section_mapping.get(idx, "ุนุงู…")
                    results.append((chunk, combined_score, section))
            
            logger.info(f"Retrieved {len(results)} relevant chunks (top score: {combined_scores[0][1]:.3f})")
            return results
            
        except Exception as e:
            logger.error(f"Retrieval failed: {str(e)}")
            return []

# Initialize retriever
retriever = HybridRetriever(kb)

class ResponseGenerator:
    def __init__(self):
        self.response_templates = {
            'definition': {
                'icon': 'ุงู„ุชุนุฑูŠู',
                'title': 'ุงู„ุชุนุฑูŠู ูˆุงู„ู…ูู‡ูˆู…',
                'structure': 'definition'
            },
            'how': {
                'icon': 'ุงู„ุขู„ูŠุฉ',
                'title': 'ุงู„ุขู„ูŠุฉ ูˆุงู„ุทุฑูŠู‚ุฉ',
                'structure': 'process'
            },
            'why': {
                'icon': 'ุงู„ุฃุณุจุงุจ',
                'title': 'ุงู„ุฃุณุจุงุจ ูˆุงู„ู…ุจุฑุฑุงุช',
                'structure': 'reasons'
            },
            'who': {
                'icon': 'ุงู„ุฃุดุฎุงุต',
                'title': 'ุงู„ุฃุดุฎุงุต ูˆุงู„ุฌู‡ุงุช',
                'structure': 'entities'
            },
            'when': {
                'icon': 'ุงู„ุชูˆู‚ูŠุช',
                'title': 'ุงู„ุชูˆู‚ูŠุช ูˆุงู„ู…ุฑุงุญู„',
                'structure': 'timeline'
            },
            'list': {
                'icon': 'ุงู„ู‚ุงุฆู…ุฉ',
                'title': 'ุงู„ู‚ุงุฆู…ุฉ ูˆุงู„ุนู†ุงุตุฑ',
                'structure': 'list'
            },
            'general': {
                'icon': 'ู…ุนู„ูˆู…ุงุช',
                'title': 'ู…ุนู„ูˆู…ุงุช ุนุงู…ุฉ',
                'structure': 'general'
            }
        }
    
    def generate_response(self, question: str, retrieved_chunks: List[Tuple[str, float, str]], question_type: str) -> str:
        """Generate professionally formatted Arabic responses with LLM enhancement"""
        try:
            if not retrieved_chunks:
                return self._generate_fallback_response(question)
            
            # Group chunks by section
            sections = {}
            for chunk, score, section in retrieved_chunks:
                if section not in sections:
                    sections[section] = []
                sections[section].append((chunk, score))
            
            # Get template info
            template_info = self.response_templates.get(question_type, self.response_templates['general'])
            
            # Extract raw content for LLM processing
            raw_content = self._extract_raw_content(sections)
            
            # Use LLM to enhance and rephrase the response if available
            if llm_available and raw_content:
                enhanced_response = self._generate_llm_enhanced_response(question, raw_content, template_info)
                if enhanced_response:
                    return enhanced_response
            
            # Fallback to original response generation
            response = self._build_response_header(question, template_info)
            response += self._build_main_content(sections, template_info)
            response += self._build_additional_info(sections)
            response += self._build_suggestions(sections.keys(), question_type)
            response += self._build_footer()
            
            return response
            
        except Exception as e:
            logger.error(f"Response generation failed: {str(e)}")
            return self._generate_error_response()
    
    def _extract_raw_content(self, sections: Dict) -> str:
        """Extract raw content from sections for LLM processing"""
        content_parts = []
        for section, chunks in sections.items():
            for chunk, score in chunks[:2]:  # Take top 2 chunks per section
                if ":" in chunk:
                    content = chunk.split(":", 1)[1].strip()
                    content_parts.append(content)
        
        return " ".join(content_parts[:3])  # Limit to avoid token limits
    
    def _generate_llm_enhanced_response(self, question: str, raw_content: str, template_info: Dict) -> str:
        """Generate enhanced response using LLM"""
        try:
            # Create a prompt for the LLM
            prompt = f"""ุจู†ุงุกู‹ ุนู„ู‰ ุงู„ู…ุนู„ูˆู…ุงุช ุงู„ุชุงู„ูŠุฉุŒ ุฃุฌุจ ุนู„ู‰ ุงู„ุณุคุงู„ ุจุทุฑูŠู‚ุฉ ู…ู‡ู†ูŠุฉ ูˆู…ูุตู„ุฉ:

ุงู„ุณุคุงู„: {question}

ุงู„ู…ุนู„ูˆู…ุงุช ุงู„ู…ุชุงุญุฉ: {raw_content}

ุงู„ุฅุฌุงุจุฉ ุงู„ู…ุทู„ูˆุจุฉ ูŠุฌุจ ุฃู† ุชูƒูˆู†:
- ู…ู‡ู†ูŠุฉ ูˆู…ู†ุธู…ุฉ
- ุจุงู„ู„ุบุฉ ุงู„ุนุฑุจูŠุฉ ุงู„ูุตุญู‰
- ุชุญุชูˆูŠ ุนู„ู‰ ุชูุงุตูŠู„ ู…ููŠุฏุฉ
- ู…ู†ุงุณุจุฉ ู„ู…ูˆุถูˆุน ุงู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉ ูˆุงู„ุดูุงููŠุฉ ุงู„ู…ุงู„ูŠุฉ

ุงู„ุฅุฌุงุจุฉ:"""

            # Generate response using LLM
            generated = text_generator(
                prompt,
                max_length=400,
                num_return_sequences=1,
                temperature=0.7,
                do_sample=True,
                pad_token_id=llm_tokenizer.eos_token_id
            )
            
            if generated and len(generated) > 0:
                full_response = generated[0]['generated_text']
                # Extract only the answer part after "ุงู„ุฅุฌุงุจุฉ:"
                if "ุงู„ุฅุฌุงุจุฉ:" in full_response:
                    answer = full_response.split("ุงู„ุฅุฌุงุจุฉ:")[-1].strip()
                    
                    # Format the enhanced response
                    formatted_response = f"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘  {template_info["icon"]} **{template_info["title"]}**
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

**ุงุณุชุนู„ุงู…ูƒ:** {question}

## ุงู„ุฅุฌุงุจุฉ ุงู„ู…ุทูˆุฑุฉ

{answer}

---
**ู„ู„ู…ุฒูŠุฏ ู…ู† ุงู„ู…ุนู„ูˆู…ุงุช:** ุชูˆุงุตู„ ู…ุน ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ ูˆุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉ
**ุงู„ู…ุตุฏุฑ:** ูˆุฒุงุฑุฉ ุงู„ู…ุงู„ูŠุฉ - ุฌู…ู‡ูˆุฑูŠุฉ ู…ุตุฑ ุงู„ุนุฑุจูŠุฉ
"""
                    return formatted_response
            
        except Exception as e:
            logger.error(f"LLM enhancement failed: {str(e)}")
        
        return None
    
    def _build_response_header(self, question: str, template_info: Dict) -> str:
        """Build professional response header"""
        header = f"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘  {template_info["icon"]} **{template_info["title"]}**
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

**ุงุณุชุนู„ุงู…ูƒ:** {question}

"""
        return header
    
    def _build_main_content(self, sections: Dict, template_info: Dict) -> str:
        """Build the main content section"""
        if not sections:
            return ""
        
        # Find the most relevant section
        main_section = max(sections.keys(), 
                          key=lambda k: max(score for _, score in sections[k]))
        
        content = f"## {main_section}\n\n"
        
        # Format main content based on structure type
        main_content = self._format_section_content_professional(
            sections[main_section], template_info['structure']
        )
        
        content += main_content + "\n\n"
        content += "---\n\n"
        
        return content
    
    def _build_additional_info(self, sections: Dict) -> str:
        """Build additional information section"""
        other_sections = list(sections.keys())[1:3]  # Take up to 2 additional sections
        
        if not other_sections:
            return ""
        
        content = "## ู…ุนู„ูˆู…ุงุช ุฅุถุงููŠุฉ ุฐุงุช ุตู„ุฉ\n\n"
        
        for i, section in enumerate(other_sections, 1):
            content += f"### {i}. **{section}**\n"
            section_content = self._format_section_content_professional(
                sections[section][:2], 'general'
            )
            content += section_content + "\n\n"
        
        content += "---\n\n"
        return content
    
    def _build_suggestions(self, available_sections: List[str], question_type: str) -> str:
        """Build suggestions section"""
        suggestions = []
        
        # Section-based suggestions
        for section in list(available_sections)[:3]:
            if len(section.split()) <= 4:
                suggestions.append(f"ุงู„ู…ุฒูŠุฏ ุญูˆู„ {section}")
        
        # Type-based suggestions
        type_suggestions = {
            'definition': ["ุงู„ุฃู‡ุฏุงู ูˆุงู„ููˆุงุฆุฏ", "ุงู„ุชุทุจูŠู‚ ุงู„ุนู…ู„ูŠ"],
            'how': ["ุงู„ุฎุทูˆุงุช ุงู„ุชูุตูŠู„ูŠุฉ", "ุงู„ู…ุชุทู„ุจุงุช ูˆุงู„ุดุฑูˆุท"],
            'who': ["ุงู„ุฃุฏูˆุงุฑ ูˆุงู„ู…ุณุคูˆู„ูŠุงุช", "ุงู„ุชูˆุงุตู„ ูˆุงู„ุงุชุตุงู„"],
            'when': ["ุงู„ุฌุฏูˆู„ ุงู„ุฒู…ู†ูŠ", "ุงู„ู…ุฑุงุญู„ ุงู„ู‚ุงุฏู…ุฉ"]
        }
        
        if question_type in type_suggestions:
            suggestions.extend(type_suggestions[question_type])
        
        if suggestions:
            content = "## ุงู‚ุชุฑุงุญุงุช ู„ู„ุงุณุชูุณุงุฑุงุช ุงู„ุฅุถุงููŠุฉ\n\n"
            for i, suggestion in enumerate(suggestions[:4], 1):
                content += f"{i}. {suggestion}\n"
            content += "\n"
            return content
        
        return ""
    
    def _build_footer(self) -> str:
        """Build response footer"""
        footer = """
---
๐Ÿ“ž **ู„ู„ู…ุฒูŠุฏ ู…ู† ุงู„ู…ุนู„ูˆู…ุงุช:** ุชูˆุงุตู„ ู…ุน ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ ูˆุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉ
๐ŸŒ **ุงู„ู…ุตุฏุฑ:** ูˆุฒุงุฑุฉ ุงู„ู…ุงู„ูŠุฉ - ุฌู…ู‡ูˆุฑูŠุฉ ู…ุตุฑ ุงู„ุนุฑุจูŠุฉ
"""
        return footer
    
    def _format_section_content_professional(self, chunk_list: List[Tuple[str, float]], structure_type: str) -> str:
        """Format content professionally based on structure type"""
        content_parts = []
        
        for chunk, score in sorted(chunk_list, key=lambda x: x[1], reverse=True)[:3]:
            if ":" in chunk:
                content = chunk.split(":", 1)[1].strip()
                
                if structure_type == 'definition':
                    content_parts.append(f"- **{content}**")
                elif structure_type == 'process':
                    content_parts.append(f"- {content}")
                elif structure_type == 'list':
                    content_parts.append(f"- {content}")
                elif structure_type == 'entities':
                    content_parts.append(f"- {content}")
                elif structure_type == 'timeline':
                    content_parts.append(f"- {content}")
                else:  # general
                    content_parts.append(f"- {content}")
        
        return "\n\n".join(content_parts)
    
    def _extract_topic(self, question: str) -> str:
        """Extract the main topic from the question"""
        keywords = query_processor.extract_keywords(question)
        if keywords:
            return " ".join(keywords[:2])
        return "ุงู„ู…ูˆุถูˆุน ุงู„ู…ุทู„ูˆุจ"
    
    def _generate_fallback_response(self, question: str) -> str:
        """Generate professional fallback response"""
        return f"""
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘  ุงู„ุจุญุซ ููŠ ู‚ุงุนุฏุฉ ุงู„ู…ุนุฑูุฉ
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

**ุงุณุชุนู„ุงู…ูƒ:** {question}

## ู„ู… ูŠุชู… ุงู„ุนุซูˆุฑ ุนู„ู‰ ู†ุชุงุฆุฌ ู…ุทุงุจู‚ุฉ

ู„ู… ุฃุชู…ูƒู† ู…ู† ุงู„ุนุซูˆุฑ ุนู„ู‰ ู…ุนู„ูˆู…ุงุช ู…ุญุฏุฏุฉ ุชุฌูŠุจ ุนู„ู‰ ุงุณุชูุณุงุฑูƒ ููŠ ู‚ุงุนุฏุฉ ุงู„ู…ุนุฑูุฉ ุงู„ุญุงู„ูŠุฉ.

## ุงู‚ุชุฑุงุญุงุช ู„ุชุญุณูŠู† ุงู„ุจุญุซ

1. **ุฅุนุงุฏุฉ ุตูŠุงุบุฉ ุงู„ุณุคุงู„:** ุฌุฑุจ ุงุณุชุฎุฏุงู… ูƒู„ู…ุงุช ู…ูุชุงุญูŠุฉ ู…ุฎุชู„ูุฉ
2. **ุงู„ุจุญุซ ููŠ ุงู„ู…ูˆุถูˆุนุงุช ุงู„ุฑุฆูŠุณูŠุฉ:** 
   - ุงู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉ
   - ุงู„ุดูุงููŠุฉ ุงู„ู…ุงู„ูŠุฉ
   - ุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉ
   - ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ

3. **ุฃู…ุซู„ุฉ ุนู„ู‰ ุฃุณุฆู„ุฉ ู…ููŠุฏุฉ:**
   - ู…ุง ู‡ูŠ ุฃู‡ุฏุงู ุงู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉุŸ
   - ูƒูŠู ูŠู…ูƒู† ู„ู„ู…ูˆุงุทู† ุงู„ู…ุดุงุฑูƒุฉุŸ
   - ู…ู† ู‡ู… ุฃุนุถุงุก ูุฑูŠู‚ ุงู„ุนู…ู„ุŸ

---
๐Ÿ“ž **ู„ู„ู…ุฒูŠุฏ ู…ู† ุงู„ู…ุนู„ูˆู…ุงุช:** ุชูˆุงุตู„ ู…ุน ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ ูˆุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉ
"""
    
    def _generate_error_response(self) -> str:
        """Generate professional error response"""
        return """
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
โ•‘  ุฎุทุฃ ููŠ ุงู„ู†ุธุงู…
โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

ุญุฏุซ ุฎุทุฃ ุบูŠุฑ ู…ุชูˆู‚ุน ุฃุซู†ุงุก ู…ุนุงู„ุฌุฉ ุงุณุชูุณุงุฑูƒ.

## ุงู„ุฎุทูˆุงุช ุงู„ู…ู‚ุชุฑุญุฉ

1. ุชุฃูƒุฏ ู…ู† ุตุญุฉ ุตูŠุงุบุฉ ุงู„ุณุคุงู„
2. ุฃุนุฏ ุงู„ู…ุญุงูˆู„ุฉ ุจุนุฏ ู‚ู„ูŠู„
3. ุชูˆุงุตู„ ู…ุน ุงู„ุฏุนู… ุงู„ูู†ูŠ ุฅุฐุง ุงุณุชู…ุฑ ุงู„ุฎุทุฃ

---
๐Ÿ“ž **ุงู„ุฏุนู… ุงู„ูู†ูŠ:** ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ ูˆุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉ
"""

# Initialize response generator
response_generator = ResponseGenerator()

def answer_question(question: str) -> str:
    """Enhanced question answering with improved processing pipeline"""
    try:
        # Input validation
        if not question or len(question.strip()) < 3:
            return "ุงู„ุฑุฌุงุก ุฅุฏุฎุงู„ ุณุคุงู„ ูˆุงุถุญ (3 ูƒู„ู…ุงุช ุนู„ู‰ ุงู„ุฃู‚ู„)"
        
        # Preprocess question
        normalized_question = query_processor.normalize_text(question)
        question_type = query_processor.classify_question_type(normalized_question)
        
        logger.info(f"Processing question: '{normalized_question}' (type: {question_type})")
        
        # Retrieve relevant content
        retrieved_chunks = retriever.retrieve(normalized_question, top_k=6)
        
        # Generate response
        response = response_generator.generate_response(
            normalized_question, retrieved_chunks, question_type
        )
        
        return response
        
    except Exception as e:
        logger.error(f"Question processing failed: {str(e)}")
        return "ุญุฏุซ ุฎุทุฃ ุบูŠุฑ ู…ุชูˆู‚ุน. ูŠุฑุฌู‰ ุงู„ู…ุญุงูˆู„ุฉ ู…ุฑุฉ ุฃุฎุฑู‰."

# Enhanced UI with better styling for professional responses
css = """
.arabic-ui {
    direction: rtl;
    text-align: right;
    font-family: 'Tahoma', 'Arial', sans-serif;
    line-height: 1.8;
    background-color: #2c3e50; /* Dark background for overall consistency */
    color: #ecf0f1; /* Light text for readability */
}
.header {
    background: #34495e; /* Slightly lighter dark for header */
    color: #ecf0f1;
    padding: 25px;
    border-radius: 12px;
    margin-bottom: 25px;
    box-shadow: 0 4px 6px rgba(0,0,0,0.3);
}
.footer {
    margin-top: 25px;
    font-size: 0.9em;
    color: #bdc3c7;
    text-align: center;
    padding: 15px;
    background: #34495e; /* Consistent dark background for footer */
    border-radius: 8px;
}
.example-box {
    border: 2px solid #34495e; /* Darker border */
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    background: #34495e; /* Dark background for example box */
    color: #ecf0f1;
}
.answer-box {
    min-height: 300px;
    line-height: 1.8;
    font-size: 14px;
    font-family: 'Tahoma', 'Arial', monospace;
    background: #2c3e50; /* Dark background for answer box */
    border: 1px solid #34495e; /* Darker border for answer box */
    border-radius: 8px;
    padding: 15px;
    white-space: pre-wrap;
    overflow-y: auto;
    color: #ecf0f1;
}
.question-input {
    font-size: 16px;
    padding: 12px;
    border-radius: 8px;
    font-family: 'Tahoma', 'Arial', sans-serif;
    background-color: #34495e; /* Dark background for input */
    border: 1px solid #2c3e50; /* Darker border */
    color: #ecf0f1;
}
/* Enhanced markdown support for Arabic */
.answer-box h1, .answer-box h2, .answer-box h3 {
    color: #ecf0f1;
    margin-top: 20px;
    margin-bottom: 10px;
}
.answer-box h2 {
    border-bottom: 2px solid #3498db;
    padding-bottom: 5px;
}
.answer-box h3 {
    color: #bdc3c7;
}
.answer-box hr {
    border: none;
    border-top: 1px solid #7f8c8d;
    margin: 20px 0;
}
.answer-box strong {
    color: #ecf0f1;
    font-weight: bold;
}
.answer-box ul, .answer-box ol {
    margin: 10px 0;
    padding-right: 20px;
}
.answer-box li {
    margin: 5px 0;
}
/* Box drawing characters support */
.answer-box {
    font-feature-settings: "liga" 1, "calt" 1;
}
"""

# Create Gradio interface
with gr.Blocks(css=css, title="ุงู„ู…ุณุงุนุฏ ุงู„ุขู„ูŠ ู„ู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉ") as demo:
    with gr.Column(elem_classes="arabic-ui"):
        gr.Markdown("""
        <div class="header">
        <h1>ุงู„ู…ุณุงุนุฏ ุงู„ุขู„ูŠ ุงู„ู…ุทูˆุฑ ู„ู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉ ู…ุน ุงู„ุฐูƒุงุก ุงู„ุงุตุทู†ุงุนูŠ</h1>
        <p>ู†ุณุฎุฉ ู…ุญุณู‘ู†ุฉ ู…ุน ู†ู…ูˆุฐุฌ ู„ุบูˆูŠ ุฐูƒูŠ ู„ุฅุนุงุฏุฉ ุตูŠุงุบุฉ ุงู„ุฅุฌุงุจุงุช ูˆุชูˆู„ูŠุฏ ู…ุญุชูˆู‰ ุฃูƒุซุฑ ุฏู‚ุฉ ูˆู…ู‡ู†ูŠุฉ</p>
        </div>
        """)
        
        with gr.Row():
            question = gr.Textbox(
                label="ุงูƒุชุจ ุณุคุงู„ูƒ ู‡ู†ุง",
                placeholder="ู…ุซุงู„: ู…ุง ู‡ูŠ ู…ุฑุงุญู„ ุชุทุจูŠู‚ ุงู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉ ููŠ ู…ุตุฑุŸ",
                lines=3,
                elem_classes="question-input"
            )
        
        with gr.Row():
            submit_btn = gr.Button("ุฅุฑุณุงู„ ุงู„ุณุคุงู„", variant="primary", size="lg")
            clear_btn = gr.Button("ู…ุณุญ", variant="secondary")
        
        answer = gr.Textbox(
            label="ุงู„ุฅุฌุงุจุฉ ุงู„ู…ุทูˆุฑุฉ",
            interactive=False,
            lines=12,
            elem_classes="answer-box"
        )
        
        with gr.Column(elem_classes="example-box"):
            gr.Markdown("**ุฃุณุฆู„ุฉ ู…ู‚ุชุฑุญุฉ ู„ู„ุชุฌุฑุจุฉ:**")
            gr.Examples(
                examples=[
                    ["ู…ุง ู‡ูŠ ุฃู‡ุฏุงู ุงู„ู…ูˆุงุฒู†ุฉ ุงู„ุชุดุงุฑูƒูŠุฉุŸ"],
                    ["ูƒูŠู ูŠู…ูƒู† ู„ู„ู…ูˆุงุทู† ุงู„ู…ุดุงุฑูƒุฉ ููŠ ุตู†ุน ุงู„ู‚ุฑุงุฑ ุงู„ู…ุงู„ูŠุŸ"],
                    ["ู…ุง ู‡ูŠ ุฃู‡ู… ุฅู†ุฌุงุฒุงุช ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ ูˆุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉุŸ"],
                    ["ู…ู† ู‡ู… ุฃุนุถุงุก ูุฑูŠู‚ ุนู…ู„ ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉุŸ"],
                    ["ูƒูŠู ุชุทูˆุฑ ุฃุฏุงุก ู…ุตุฑ ููŠ ู…ุคุดุฑุงุช ุงู„ุดูุงููŠุฉ ุงู„ุฏูˆู„ูŠุฉุŸ"],
                    ["ู…ุง ู‡ูŠ ุงู„ูˆุซุงุฆู‚ ุงู„ู…ุชุงุญุฉ ู„ู„ุฌู…ู‡ูˆุฑ ููŠ ุงู„ู…ูˆุงุฒู†ุฉุŸ"]
                ],
                inputs=question,
                label=""
            )
        
        gr.Markdown("""
        <div class="footer">
        <p><strong>ูˆุญุฏุฉ ุงู„ุดูุงููŠุฉ ูˆุงู„ู…ุดุงุฑูƒุฉ ุงู„ู…ุฌุชู…ุนูŠุฉ - ูˆุฒุงุฑุฉ ุงู„ู…ุงู„ูŠุฉ</strong></p>
        <p>ู†ุณุฎุฉ ู…ุญุณู‘ู†ุฉ ู…ุน ู†ู…ูˆุฐุฌ ู„ุบูˆูŠ ุฐูƒูŠ ู„ุฅุนุงุฏุฉ ุตูŠุงุบุฉ ุงู„ุฅุฌุงุจุงุช ูˆุชูˆู„ูŠุฏ ู…ุญุชูˆู‰ ุฃูƒุซุฑ ุฏู‚ุฉ ูˆู…ู‡ู†ูŠุฉ</p>
        </div>
        """)
    
    # Event handlers
    submit_btn.click(answer_question, inputs=question, outputs=answer)
    clear_btn.click(lambda: ("", ""), outputs=[question, answer])
    question.submit(answer_question, inputs=question, outputs=answer)

if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False,
        show_error=True
    )