DEPLOY: Improved answer extraction with false word filtering
Browse filesAdded filtering for false words (Otherwise, However, Therefore, etc.) to extract correct LAST meaningful word from long responses
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534"""Dedykowany moduł do ekstrakcji odpowiedzi zgodnych z GAIA.UPDATED: Fixed answer extraction to get LAST meaningful word instead of FIRST."""
import refrom typing import Optional, Dict, Anyimport jsonimport logging
logger = logging.getLogger(__name__)
class GAIAAnswerExtractor: """Ekstraktor odpowiedzi dla formatu GAIA.""" def __init__(self): self.patterns = self._compile_patterns() self.factual_patterns = self._compile_factual_patterns() def _compile_patterns(self) -> Dict[str, re.Pattern]: """Kompiluj wzorce dla różnych typów odpowiedzi.""" return { # Numeryczne 'number': re.compile(r'(?:answer is:|result is:|equals?|=)\s*(-?\d+\.?\d*)', re.I), 'just_number': re.compile(r'^(-?\d+\.?\d*)$'), # Yes/No 'yes_no': re.compile(r'\b(yes|no)\b', re.I), # Finalne odpowiedzi 'final_answer': re.compile(r'(?:final answer|answer):\s*(.+?)(?:\.|$)', re.I), 'the_answer_is': re.compile(r'the final answer is:\s*(.+?)(?:\.|$)', re.I), # Markery odpowiedzi 'answer_markers': re.compile(r'\[ANSWER\](.*?)\[/ANSWER\]', re.IGNORECASE | re.DOTALL), 'answer_tags': re.compile(r'<answer>(.*?)</answer>', re.IGNORECASE | re.DOTALL), # W nawiasach/cudzysłowach 'quoted': re.compile(r'["\'](.*?)["\']'), 'parentheses': re.compile(r'\(([^)]+)\)'), # Listy 'list': re.compile(r'(?:are:|include:|following:)\s*(.+)', re.I) } def _compile_factual_patterns(self) -> Dict[str, re.Pattern]: """Specjalne wzorce dla odpowiedzi faktograficznych.""" return { # Wzorce dla stolic 'capital': re.compile( r'(?:capital of [^is]+is\s+|capital is\s+|capital:\s*)([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)', re.I ), # Wzorce dla nazwisk/imion 'person': re.compile( r'(?:(?:is|was|are|were)\s+)([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)', re.I ), # Wzorce dla miejsc/obiektów 'place_object': re.compile( r'(?:(?:is|was)\s+(?:the\s+)?|answer is\s+(?:the\s+)?)([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)', re.I ), # Wzorzec dla "The X is Y" -> ekstraktuj Y 'the_x_is': re.compile( r'the\s+[^is]+is\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)', re.I ), # Wzorzec dla superlatywów (largest, smallest, etc.) 'superlative': re.compile( r'(?:largest|smallest|biggest|tallest|shortest|longest|oldest|youngest|fastest|slowest)\s+(?:\w+\s+)?(?:is\s+)?(?:the\s+)?([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)', re.I ), # Wzorzec dla "X Ocean/Mountain/River/etc" 'geographic': re.compile( r'([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)\s+(?:Ocean|Sea|Mountain|River|Lake|Desert|Island|Country|City|State)', re.I ) } def extract(self, text: str, question_type: Optional[str] = None) -> str: """ Główna metoda ekstrakcji. Args: text: Tekst z odpowiedzią question_type: Typ pytania (math, yes_no, factual, list) """ # Czyszczenie text = text.strip() if not text: return "" # Najpierw sprawdź markery odpowiedzi marked_answer = self._extract_from_markers(text) if marked_answer != text: text = marked_answer # Auto-detekcja typu jeśli nie podano if not question_type: question_type = self._detect_type(text) # Ekstrakcja według typu extractors = { 'math': self._extract_number, 'yes_no': self._extract_yes_no, 'list': self._extract_list, 'factual': self._extract_factual_improved # ULEPSZONA METODA } extractor = extractors.get(question_type, self._extract_general) result = extractor(text) # Czyszczenie finalne final_result = self._clean_answer(result) logger.debug(f"Extracted '{final_result}' from '{text[:100]}...' (type: {question_type})") return final_result def _extract_from_markers(self, text: str) -> str: """Wyciągnij odpowiedź z markerów.""" # Sprawdź [ANSWER] markery if match := self.patterns['answer_markers'].search(text): return match.group(1).strip() # Sprawdź <answer> tagi if match := self.patterns['answer_tags'].search(text): return match.group(1).strip() # Sprawdź **Answer:** wzorzec if match := re.search(r'\*\*answer\*\*:?\s*(.*?)(?:\n|$)', text, re.IGNORECASE): return match.group(1).strip() return text def _detect_type(self, text: str) -> str: """Wykryj typ odpowiedzi.""" text_lower = text.lower() text_clean = text.strip() # Sprawdź yes/no - musi być krótka odpowiedź if len(text_clean.split()) <= 5: if any(word in text_lower for word in ['yes', 'no']): return 'yes_no' # Sprawdź liczby if re.search(r'^\d+\.?\d*$', text_clean): return 'math' if re.search(r'\d+\.?\d*', text) and any(op in text for op in ['=', 'equals', 'result', 'answer is']): return 'math' # Sprawdź listy if ',' in text and len(text.split(',')) > 1: return 'list' if ' and ' in text_lower and len(text.split()) < 10: return 'list' return 'factual' def _extract_number(self, text: str) -> str: """Ekstraktuj liczbę z tekstu.""" # Sprawdź czy to sama liczba if match := self.patterns['just_number'].search(text.strip()): return match.group(1) # Szukaj w kontekście "answer is", "result is", etc. if match := self.patterns['number'].search(text): return match.group(1) # Szukaj jakiejkolwiek liczby - preferuj ostatnią (często wynik) numbers = re.findall(r'-?\d+\.?\d*', text) if numbers: return numbers[-1] # Fallback - usuń prefiksy i spróbuj ponownie cleaned = self._remove_common_prefixes(text) numbers = re.findall(r'-?\d+\.?\d*', cleaned) if numbers: return numbers[0] return text.strip() def _extract_yes_no(self, text: str) -> str: """Ekstraktuj yes/no.""" text_lower = text.lower().strip() # Bezpośrednie yes/no if text_lower in ['yes', 'no']: return text_lower # Rozpoczynające się od yes/no if text_lower.startswith('yes'): return 'yes' if text_lower.startswith('no'): return 'no' # Szukaj w tekście if match := self.patterns['yes_no'].search(text): return match.group(1).lower() # Heurystyki oparte na kontekście negative_words = ['not', 'no', 'false', 'incorrect', 'wrong', 'negative'] positive_words = ['yes', 'indeed', 'correct', 'true', 'positive', 'affirmative'] for word in negative_words: if word in text_lower: return 'no' for word in positive_words: if word in text_lower: return 'yes' return text.strip() def _extract_factual(self, text: str) -> str: """Ekstraktuj odpowiedź faktograficzną.""" # Sprawdź final answer wzorzec if match := self.patterns['final_answer'].search(text): return match.group(1).strip() # Sprawdź cudzysłowy if match := self.patterns['quoted'].search(text): candidate = match.group(1).strip() if len(candidate) > 0 and len(candidate) < 50: # Rozsądna długość return candidate # Usuń prefiksy cleaned = self._remove_common_prefixes(text) # Jeśli krótki tekst - zwróć cały if len(cleaned.split()) <= 5: return cleaned # Weź pierwsze zdanie sentences = cleaned.split('.') if sentences and len(sentences[0].strip()) > 0: first_sentence = sentences[0].strip() # Sprawdź czy nie jest za długie if len(first_sentence.split()) <= 10: return first_sentence # Fallback - pierwsze 5 słów words = cleaned.split() if len(words) > 5: return ' '.join(words[:5]) return cleaned def _extract_factual_improved(self, text: str) -> str: """ULEPSZONA ekstrakcja odpowiedzi faktograficznych z lepszymi wzorcami.""" # Sprawdź markery odpowiedzi if match := self.patterns['answer_markers'].search(text): candidate = match.group(1).strip() return self._clean_factual_answer(candidate) if match := self.patterns['answer_tags'].search(text): candidate = match.group(1).strip() return self._clean_factual_answer(candidate) # Użyj specjalistycznych wzorców faktograficznych for pattern_name, pattern in self.factual_patterns.items(): if match := pattern.search(text): candidate = match.group(1).strip() if self._is_valid_factual_answer(candidate): logger.debug(f"Factual pattern '{pattern_name}' matched: {candidate}") return self._clean_factual_answer(candidate) # Sprawdź cudzysłowy - często zawierają dokładne odpowiedzi if match := self.patterns['quoted'].search(text): candidate = match.group(1).strip() if self._is_valid_factual_answer(candidate) and len(candidate) < 50: return self._clean_factual_answer(candidate) # Szukaj właściwych nazw na początku tekstu lines = text.split('\n') for line in lines[:3]: # Sprawdź pierwsze 3 linie line = line.strip() if not line: continue # Usuń typowe prefiksy cleaned_line = self._remove_common_prefixes(line) # Sprawdź czy to nazwa własna if re.match(r'^[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*$', cleaned_line): if self._is_valid_factual_answer(cleaned_line): return self._clean_factual_answer(cleaned_line) # Usuń prefiksy z całego tekstu cleaned = self._remove_common_prefixes(text) # Jeśli krótki tekst - zwróć cały po oczyszczeniu if len(cleaned.split()) <= 3: return self._clean_factual_answer(cleaned) # Weź pierwsze zdanie i sprawdź czy zawiera odpowiedź sentences = re.split(r'[.!?]', cleaned) if sentences: first_sentence = sentences[0].strip() # Szukaj nazw własnych w pierwszym zdaniu proper_nouns = re.findall(r'\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b', first_sentence) if proper_nouns: # Weź ostatnią znalezioną nazwę własną (często odpowiedź) candidate = proper_nouns[-1] if self._is_valid_factual_answer(candidate): return self._clean_factual_answer(candidate) # Jeśli pierwsze zdanie jest krótkie, zwróć je if len(first_sentence.split()) <= 8: return self._clean_factual_answer(first_sentence) # Fallback - pierwsze słowa words = cleaned.split() if len(words) > 4: return self._clean_factual_answer(' '.join(words[:4])) return self._clean_factual_answer(cleaned) def _is_valid_factual_answer(self, text: str) -> bool: """Sprawdź czy tekst wygląda na prawidłową odpowiedź faktograficzną.""" if not text or len(text.strip()) == 0: return False text = text.strip() # Za długie odpowiedzi prawdopodobnie zawierają nadmiarowy tekst if len(text) > 100: return False # Sprawdź czy nie zawiera typowych fraz z wyjaśnieniami invalid_phrases = [ 'according to', 'based on', 'it is important', 'please note', 'in conclusion', 'therefore', 'however', 'furthermore', 'as a result', 'on the other hand', 'for example' ] text_lower = text.lower() for phrase in invalid_phrases: if phrase in text_lower: return False return True def _clean_factual_answer(self, text: str) -> str: """Czyść odpowiedź faktograficzną.""" if not text: return "" # Podstawowe czyszczenie text = text.strip() # Usuń znaki interpunkcyjne na końcu (oprócz skrótów) if text.endswith('.') and not re.match(r'.*\b[A-Z]\.$', text): text = text[:-1].strip() # Usuń cudzysłowy zewnętrzne if (text.startswith('"') and text.endswith('"')) or \ (text.startswith("'") and text.endswith("'")): text = text[1:-1].strip() return text def _extract_list(self, text: str) -> str: """Ekstraktuj listę.""" # Usuń prefiksy list if match := self.patterns['list'].search(text): text = match.group(1) text = self._remove_common_prefixes(text) # Obsłuż numerację (1. 2. 3.) if re.search(r'\d+\.', text): items = re.findall(r'\d+\.\s*([^.]+)(?=\d+\.|$)', text) if items: # Czyść każdy element items = [item.strip().rstrip(',') for item in items] return ','.join(items) # Zamień 'and' na przecinki text = re.sub(r'\s+and\s+', ', ', text) # Jeśli już ma przecinki, czyść format if ',' in text: items = [item.strip() for item in text.split(',')] items = [item for item in items if item] # Usuń puste return ','.join(items) return text.strip() def _extract_general(self, text: str) -> str: """Ogólna ekstrakcja.""" cleaned = self._remove_common_prefixes(text) # Jeśli nadal długie - weź pierwsze zdanie if len(cleaned) > 100: sentences = cleaned.split('.') if sentences: cleaned = sentences[0].strip() return cleaned def _remove_common_prefixes(self, text: str) -> str: """Usuń typowe prefiksy.""" prefixes = [ 'the answer is', 'answer:', 'result:', 'final answer:', 'therefore', 'thus', 'so', 'hence', 'conclusion:', 'the result is', 'it is', 'this is', 'that is' ] text_lower = text.lower().strip() original_text = text.strip() for prefix in prefixes: if text_lower.startswith(prefix): # Znajdź pozycję prefiksu w oryginalnym tekście start_pos = text_lower.index(prefix) + len(prefix) result = original_text[start_pos:].strip() # Usuń dwukropek na początku if result.startswith(':'): result = result[1:].strip() return result return original_text def _clean_answer(self, answer: str) -> str: """Finalne czyszczenie odpowiedzi z walidacją.""" # Usuń białe znaki answer = answer.strip() if not answer: return "" # CRITICAL FIX: Check if answer is too long (> 10 words) - extract LAST meaningful word if len(answer.split()) > 10: logger.warning(f"Long answer detected: {answer[:50]}...") # CRUCIAL: Look for "answer is: X" pattern first answer_patterns = [ r'(?:answer is|final answer is)[:\s]*([A-Z][a-zA-Z]*)\s*[.!?]?$', # "answer is: Name" r'(?:answer is|final answer is)[:\s]*([^.!?\n]{1,20})$', # General "answer is: X" at end r'(?:the answer is|the final answer is)[:\s]*([A-Z][a-zA-Z]*)' # "the answer is Name" ] for pattern in answer_patterns: match = re.search(pattern, answer, re.I) if match: extracted = match.group(1).strip() # Clean up the extracted part extracted = re.sub(r'^["\'\s]+|["\'\s]+$', '', extracted) # Remove quotes and spaces if extracted and len(extracted.split()) <= 3 and extracted != 'Based': logger.info(f"Extracted from 'answer is' pattern: {extracted}") return extracted # Try to extract LAST meaningful word/phrase (iterate backwards) words = answer.split() meaningful_words = [] # Collect meaningful words (names, numbers, important words) for word in words: cleaned_word = word.strip('.,!?"\'') if (cleaned_word and len(cleaned_word) > 1 and (cleaned_word[0].isupper() and cleaned_word.isalpha()) or cleaned_word.replace('.','').replace('-','').isdigit()): meaningful_words.append(cleaned_word) # Return LAST meaningful word (most likely the answer) - but avoid common false words if meaningful_words: # Filter out common false positives at end of long answers false_words = {'Otherwise', 'However', 'Therefore', 'Additionally', 'Furthermore', 'Unfortunately', 'Importantly', 'Specifically', 'Generally', 'Obviously', 'Naturally'} # Try to find a good answer, starting from the end for word in reversed(meaningful_words): if word not in false_words and len(word) > 1: logger.info(f"Extracted LAST meaningful word from long answer: {word}") return word # If all words are false positives, return the last one anyway logger.info(f"Extracted LAST meaningful word from long answer: {meaningful_words[-1]}") return meaningful_words[-1] # Fallback - return last non-stop word stop_words = {'the', 'is', 'are', 'was', 'were', 'a', 'an', 'and', 'or', 'but', 'of', 'to', 'in', 'for'} for word in reversed(words): cleaned_word = word.strip('.,!?"\'') if cleaned_word.lower() not in stop_words and len(cleaned_word) > 2: logger.info(f"Extracted last non-stop word: {cleaned_word}") return cleaned_word return "unknown" # Fix common patterns if answer.startswith("The answer is"): answer = answer.replace("The answer is", "").strip() elif answer.startswith("Answer:"): answer = answer.replace("Answer:", "").strip() # Usuń cudzysłowy zewnętrzne if (answer.startswith('"') and answer.endswith('"')) or \ (answer.startswith("'") and answer.endswith("'")): answer = answer[1:-1].strip() # Usuń kropkę na końcu (chyba że to liczba dziesiętna) if answer.endswith('.') and not re.match(r'^\d+\.\d*$', answer): answer = answer[:-1].strip() # Dla liczb - upewnij się że format jest poprawny if re.match(r'^-?\d+\.?\d*$', answer): try: num = float(answer) # Jeśli to liczba całkowita - zwróć bez .0 if num.is_integer(): return str(int(num)) return str(num) except: pass # Dla yes/no - upewnij się że jest lowercase if answer.lower() in ['yes', 'no']: return answer.lower() return answer
# Zachowaj kompatybilność z istniejącym kodemclass AnswerExtractor(GAIAAnswerExtractor): """Alias dla zachowania kompatybilności""" passagent/answer_extractor.pyAdded+534