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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Dedykowany moduł do ekstrakcji odpowiedzi zgodnych z GAIA.
"""

import re
from typing import Optional, Dict, Any
import json
import 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)
            if meaningful_words:
                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 kodem
class AnswerExtractor(GAIAAnswerExtractor):
    """Alias dla zachowania kompatybilności"""
    pass