Update response_generator.py
Browse files29 unmodified lines303132333435363738394041424344454647484950515253545556575859605 unmodified lines66676869707172737475767778798081822 unmodified lines858687888990918 unmodified lines1001011021031041051061071081093 unmodified lines1131141151161171181194 unmodified lines1241251261271281291301311321332 unmodified lines13613713813914014129 unmodified lines"""Smart extraction with sentence selection"""# Get top chunkstop_chunks = relevant_docs.head(3)# Extract query keywordsquery_keywords = self._extract_keywords(query)# Find best sentencesbest_sentences = []for idx, row in top_chunks.iterrows():content = row['content']similarity = row.get('similarity_score', 0)# Split into sentencessentences = self._split_sentences(content)# Score each sentencefor sentence in sentences:if len(sentence.strip()) < 20: # Skip very short sentencescontinue# Calculate sentence scorescore = similarity# Boost if contains query keywordssentence_lower = sentence.lower()for keyword in query_keywords:if keyword in sentence_lower:5 unmodified lines'chunk_id': idx})# Sort by scorebest_sentences.sort(key=lambda x: x['score'], reverse=True)# Take top 3 sentencestop_sentences = best_sentences[:3]# Format answerif not top_sentences:return self._format_simple_answer(top_chunks)# Build answeranswer_parts = ["**الإجابة:**\n"]for i, sent in enumerate(top_sentences, 1):2 unmodified lineselse:answer_parts.append(f"\n{sent['text']}")# Add metadataanswer_parts.append("\n\n---")scores = top_chunks['similarity_score'].values if 'similarity_score' in top_chunks.columns else []8 unmodified lines"""Extract meaningful keywords from query"""# Remove stop wordsstop_words = {'ما', 'هي', 'هو', 'في', 'من', 'إلى', 'على', 'عن', 'ال', 'و', 'أو'}# Split and cleanwords = query.lower().split()keywords = [w for w in words if len(w) > 2 and w not in stop_words]3 unmodified lines"""Split text into sentences"""# Split by Arabic and English punctuationsentences = re.split(r'[.؟!]\s+', text)return [s.strip() for s in sentences if s.strip()]4 unmodified linesbest_chunk = top_chunks.iloc[0]content = best_chunk['content']# Truncate if too longif len(content) > 400:content = content[:400]# Try to end at sentencelast_period = max(content.rfind('.'), content.rfind('؟'), content.rfind('!'))if last_period > 100:content = content[:last_period + 1]2 unmodified linesscore = best_chunk.get('similarity_score', 0)return f"""**الإجابة:**{content}29 unmodified lines3031323334353637383940414243444546474849505152535 unmodified lines596061626364656667686970712 unmodified lines7475767778798 unmodified lines88899091929394953 unmodified lines991001011021031044 unmodified lines1091101111121131141151162 unmodified lines11912012112212312429 unmodified lines"""Smart extraction with sentence selection"""top_chunks = relevant_docs.head(3)query_keywords = self._extract_keywords(query)best_sentences = []for idx, row in top_chunks.iterrows():content = row['content']similarity = row.get('similarity_score', 0)sentences = self._split_sentences(content)for sentence in sentences:if len(sentence.strip()) < 20:continuescore = similaritysentence_lower = sentence.lower()for keyword in query_keywords:if keyword in sentence_lower:5 unmodified lines'chunk_id': idx})best_sentences.sort(key=lambda x: x['score'], reverse=True)top_sentences = best_sentences[:3]if not top_sentences:return self._format_simple_answer(top_chunks)answer_parts = ["**الإجابة:**\n"]for i, sent in enumerate(top_sentences, 1):2 unmodified lineselse:answer_parts.append(f"\n{sent['text']}")answer_parts.append("\n\n---")scores = top_chunks['similarity_score'].values if 'similarity_score' in top_chunks.columns else []8 unmodified lines"""Extract meaningful keywords from query"""stop_words = {'ما', 'هي', 'هو', 'في', 'من', 'إلى', 'على', 'عن', 'ال', 'و', 'أو'}words = query.lower().split()keywords = [w for w in words if len(w) > 2 and w not in stop_words]3 unmodified lines"""Split text into sentences"""sentences = re.split(r'[.؟!]\s+', text)return [s.strip() for s in sentences if s.strip()]4 unmodified linesbest_chunk = top_chunks.iloc[0]content = best_chunk['content']if len(content) > 400:content = content[:400]last_period = max(content.rfind('.'), content.rfind('؟'), content.rfind('!'))if last_period > 100:content = content[:last_period + 1]2 unmodified linesscore = best_chunk.get('similarity_score', 0)answer = f"**الإجابة:**\n\n{content}\n\n---\n**دقة المطابقة:** {score:.0%}"return answer
response_generator.py+4-21