File size: 13,995 Bytes
3f1068e | 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 | """
Analizator pytań GAIA - klasyfikacja i dekompozycja.
"""
import re
from typing import Dict, List, Tuple, Optional
from dataclasses import dataclass
import logging
logger = logging.getLogger(__name__)
@dataclass
class QuestionAnalysis:
"""Wynik analizy pytania."""
question_type: str # math, factual, yes_no, list, multi_step, comparison, temporal
keywords: List[str]
requires_tools: List[str]
expected_format: str
complexity: int # 1-5
confidence: float # 0.0-1.0
class GAIAQuestionAnalyzer:
"""Analizator pytań dla benchmarku GAIA."""
def __init__(self):
self.patterns = self._load_patterns()
self.tool_keywords = self._load_tool_keywords()
def _load_patterns(self) -> Dict[str, List[str]]:
"""Załaduj wzorce pytań."""
return {
'math': [
r'calculate\s+\d+', r'what is \d+\s*[+\-*/×÷]\s*\d+', r'how much is',
r'\d+\s*percent of', r'\d+%\s*of', r'sum of', r'product of',
r'\d+\s*[+\-*/×÷]\s*\d+', r'multiply', r'divide', r'add', r'subtract',
r'what is.*\d+.*\d+', r'calculate.*\d+', r'compute'
],
'yes_no': [
r'^is \w+', r'^are \w+', r'^was \w+', r'^were \w+', r'^do \w+', r'^does \w+',
r'^can \w+', r'^could \w+', r'^will \w+', r'^would \w+', r'^has \w+', r'^have \w+',
r'true or false', r'yes or no', r'is it true', r'is this correct'
],
'temporal': [
r'what year', r'when did', r'what date', r'in what year',
r'how old.*in \d{4}', r'born in', r'died in', r'happened in',
r'is \d{4} a leap year', r'leap year', r'what day of the week'
],
'comparison': [
r'which is \w+er', r'which is more', r'which is less',
r'taller', r'shorter', r'bigger', r'smaller', r'larger', r'higher', r'lower',
r'compare', r'difference between', r'better than', r'worse than',
r'faster than', r'slower than', r'older than', r'younger than'
],
'list': [
r'list all', r'name all', r'what are all', r'give me all',
r'enumerate', r'how many.*are there', r'all the.*that',
r'which.*include', r'what.*contain'
],
'factual': [
r'what is the capital', r'who is', r'what is.*called',
r'where is', r'what does.*mean', r'what is the name of',
r'which country', r'which city', r'what language'
]
}
def _load_tool_keywords(self) -> Dict[str, List[str]]:
"""Załaduj słowa kluczowe dla narzędzi."""
return {
'calculator': [
'calculate', 'compute', 'add', 'subtract', 'multiply', 'divide',
'percent', '%', 'sum', 'product', 'total', 'average', 'mean'
],
'web_search': [
'current', 'latest', 'recent', 'today', 'now', '2024', '2025',
'president', 'prime minister', 'ceo', 'leader', 'population'
],
'datetime': [
'leap year', 'day of the week', 'what day', 'calendar',
'date', 'time', 'year', 'month', 'day'
],
'wikipedia': [
'who is', 'what is', 'history of', 'biography', 'definition',
'meaning', 'explanation', 'origin', 'founded'
]
}
def analyze(self, question: str) -> QuestionAnalysis:
"""Analizuj pytanie GAIA."""
q_lower = question.lower().strip()
# Określ typ pytania
question_type, type_confidence = self._determine_type(q_lower)
# Wyodrębnij słowa kluczowe
keywords = self._extract_keywords(question)
# Określ potrzebne narzędzia
tools = self._determine_tools(q_lower, question_type, keywords)
# Określ format odpowiedzi
expected_format = self._determine_format(question_type, q_lower)
# Oceń złożoność
complexity = self._assess_complexity(question, tools, question_type)
analysis = QuestionAnalysis(
question_type=question_type,
keywords=keywords,
requires_tools=tools,
expected_format=expected_format,
complexity=complexity,
confidence=type_confidence
)
logger.debug(f"Question analysis: {question[:50]}... -> {question_type} "
f"(confidence: {type_confidence:.2f}, complexity: {complexity})")
return analysis
def _determine_type(self, question: str) -> Tuple[str, float]:
"""Określ typ pytania z poziomem pewności."""
type_scores = {}
# Sprawdź każdy wzorzec
for q_type, patterns in self.patterns.items():
score = 0
matched_patterns = 0
for pattern in patterns:
if re.search(pattern, question, re.IGNORECASE):
score += 1
matched_patterns += 1
# Normalizuj wynik
if matched_patterns > 0:
type_scores[q_type] = score / len(patterns)
# Dodatkowe heurystyki
self._apply_heuristics(question, type_scores)
if not type_scores:
# Fallback na podstawie struktury pytania
return self._fallback_type_detection(question)
# Wybierz typ z najwyższym wynikiem
best_type = max(type_scores, key=type_scores.get)
confidence = type_scores[best_type]
return best_type, min(confidence, 1.0)
def _apply_heuristics(self, question: str, type_scores: Dict[str, float]) -> None:
"""Zastosuj dodatkowe heurystyki klasyfikacji."""
# Pytania matematyczne
if re.search(r'\d+.*\d+', question) and any(op in question for op in ['+', '-', '*', '/', '×', '÷', 'percent', '%']):
type_scores['math'] = type_scores.get('math', 0) + 0.5
# Pytania yes/no - struktura
if question.startswith(('is ', 'are ', 'was ', 'were ', 'do ', 'does ', 'can ', 'could ')):
type_scores['yes_no'] = type_scores.get('yes_no', 0) + 0.3
# Pytania porównawcze
if ' or ' in question and ('which' in question or 'what' in question):
type_scores['comparison'] = type_scores.get('comparison', 0) + 0.2
# Pytania o lata
if re.search(r'\b(19|20)\d{2}\b', question):
type_scores['temporal'] = type_scores.get('temporal', 0) + 0.2
# Długie pytania prawdopodobnie multi-step
if len(question.split()) > 25:
type_scores['multi_step'] = type_scores.get('multi_step', 0) + 0.3
def _fallback_type_detection(self, question: str) -> Tuple[str, float]:
"""Fallback detekcja typu gdy wzorce nie pasują."""
# Krótkie pytania z liczbami -> prawdopodobnie math
if len(question.split()) < 10 and re.search(r'\d+', question):
return 'math', 0.3
# Pytania zaczynające się od typowych słów
question_starters = {
'what': 'factual',
'who': 'factual',
'where': 'factual',
'when': 'temporal',
'how': 'factual',
'which': 'comparison',
'why': 'factual'
}
first_word = question.split()[0].lower() if question.split() else ''
if first_word in question_starters:
return question_starters[first_word], 0.4
# Długie skomplikowane pytania
if len(question.split()) > 20:
return 'multi_step', 0.3
# Default
return 'factual', 0.2
def _extract_keywords(self, question: str) -> List[str]:
"""Wyodrębnij kluczowe słowa do wyszukiwania."""
keywords = []
# Stop words do pominięcia
stop_words = {
'the', 'a', 'an', 'is', 'are', 'was', 'were', 'what', 'which', 'who', 'where',
'when', 'why', 'how', 'do', 'does', 'did', 'can', 'could', 'will', 'would',
'should', 'in', 'on', 'at', 'for', 'with', 'by', 'from', 'to', 'of', 'and',
'or', 'but', 'if', 'then', 'than', 'as', 'like', 'this', 'that', 'these',
'those', 'i', 'you', 'he', 'she', 'it', 'we', 'they', 'me', 'him', 'her'
}
# Znajdź nazwy własne (wielkie litery) - bardzo ważne
proper_nouns = re.findall(r'\b[A-Z][a-zA-Z]+(?:\s+[A-Z][a-zA-Z]+)*\b', question)
keywords.extend(proper_nouns)
# Znajdź frazy w cudzysłowach - bardzo ważne
quoted_phrases = re.findall(r'"([^"]*)"', question)
keywords.extend(quoted_phrases)
# Znajdź lata i liczby
years = re.findall(r'\b(19|20)\d{2}\b', question)
keywords.extend(years)
numbers = re.findall(r'\b\d+\b', question)
keywords.extend(numbers[:3]) # Max 3 liczby
# Znajdź ważne słowa (pomiń stop words)
words = re.findall(r'\b\w+\b', question.lower())
important_words = [w for w in words if w not in stop_words and len(w) > 3]
keywords.extend(important_words[:5]) # Max 5 dodatkowych słów
# Usuń duplikaty zachowując kolejność
seen = set()
unique_keywords = []
for kw in keywords:
if kw.lower() not in seen:
seen.add(kw.lower())
unique_keywords.append(kw)
return unique_keywords[:10] # Max 10 keywords
def _determine_tools(self, question: str, q_type: str, keywords: List[str]) -> List[str]:
"""Określ potrzebne narzędzia."""
tools = set()
# Narzędzia na podstawie typu pytania
type_to_tools = {
'math': ['calculator'],
'yes_no': ['web_search'], # Mogą wymagać weryfikacji
'temporal': ['datetime', 'web_search'],
'comparison': ['web_search'],
'list': ['web_search'],
'factual': ['web_search', 'wikipedia'],
'multi_step': ['web_search', 'calculator', 'wikipedia']
}
base_tools = type_to_tools.get(q_type, ['web_search'])
tools.update(base_tools)
# Dodatkowe narzędzia na podstawie słów kluczowych
for tool, tool_keywords in self.tool_keywords.items():
if any(kw.lower() in question for kw in tool_keywords):
tools.add(tool)
# Specjalne przypadki
if 'leap year' in question:
tools.add('datetime')
tools.discard('web_search') # datetime wystarczy
if re.search(r'\d+\s*[+\-*/×÷%]\s*\d+', question):
tools.add('calculator')
if any(word in question for word in ['image', 'picture', 'photo', 'painting', 'drawing']):
tools.add('image_analyzer')
# Usuń zbędne narzędzia dla prostych pytań
if q_type == 'math' and 'calculator' in tools:
tools.discard('web_search')
tools.discard('wikipedia')
return list(tools)
def _determine_format(self, q_type: str, question: str) -> str:
"""Określ oczekiwany format odpowiedzi."""
formats = {
'math': 'number',
'yes_no': 'yes_or_no',
'list': 'comma_separated',
'temporal': 'date_or_year',
'factual': 'short_text',
'comparison': 'entity_name',
'multi_step': 'short_text'
}
base_format = formats.get(q_type, 'short_text')
# Doprecyzowanie na podstawie pytania
if 'percent' in question or '%' in question:
return 'percentage'
if re.search(r'\bhow many\b', question):
return 'number'
if 'name' in question and q_type == 'factual':
return 'entity_name'
return base_format
def _assess_complexity(self, question: str, tools: List[str], q_type: str) -> int:
"""Oceń złożoność pytania (1-5)."""
score = 1
# Bazowa złożoność według typu
type_complexity = {
'math': 1,
'yes_no': 1,
'factual': 2,
'temporal': 2,
'comparison': 3,
'list': 3,
'multi_step': 4
}
score = type_complexity.get(q_type, 2)
# Długość pytania
word_count = len(question.split())
if word_count > 15:
score += 1
if word_count > 30:
score += 1
# Liczba narzędzi
if len(tools) > 2:
score += 1
if len(tools) > 3:
score += 1
# Wieloetapowość
multi_step_indicators = [
'and then', 'after that', 'following', 'next', 'subsequently',
'first', 'second', 'finally', 'in addition', 'furthermore'
]
for indicator in multi_step_indicators:
if indicator in question.lower():
score += 1
break
# Obecność obrazów/plików
if any(word in question.lower() for word in ['image', 'picture', 'file', 'document']):
score += 1
# Wymaganie precyzji
if any(word in question.lower() for word in ['exact', 'precise', 'specifically', 'exactly']):
score += 1
return min(score, 5) # Max 5
# Zachowaj kompatybilność z istniejącym kodem
class QuestionAnalyzer(GAIAQuestionAnalyzer):
"""Alias dla zachowania kompatybilności"""
pass |