Spaces:
Sleeping
Sleeping
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
) |