|
Download gaia_test_parser.md from maribiel/Final_Assignment_Template: direct link, hf CLI and curl.
- Browser
- Download file 13.8 kB
-
https://huggingface.co/maribiel/Final_Assignment_Template/resolve/main/gaia_test_parser.md
- Command line
-
hf download hf://maribiel/Final_Assignment_Template/gaia_test_parser.md
-
curl -L -o gaia_test_parser.md https://huggingface.co/maribiel/Final_Assignment_Template/resolve/main/gaia_test_parser.md
13.8 kB
| Struktura datasetu GAIA | |
| Co znajduje się w repozytorium: | |
| 2023/test/ | |
| ├── metadata.jsonl # Metadane wszystkich zadań | |
| ├── 00a7aa96-b0c1-4483... # Pliki z pytaniami (każde zadanie osobno) | |
| ├── 00f1e8bb-29e9-4532... # Mogą zawierać obrazy, pliki CSV itp. | |
| └── ... | |
| Format metadata.jsonl: | |
| json{ | |
| "task_id": "00a7aa96-b0c1-4483-a935-82e17b96f3c8", | |
| "question": "What is the capital of the country...", | |
| "level": "1", | |
| "final_answer": "Paris", | |
| "file_name": "image.png", // opcjonalne | |
| "file_path": "00a7aa96-b0c1-4483-a935-82e17b96f3c8" | |
| } | |
| 🛠️ Parser dla GAIA Dataset | |
| Utwórz agent/gaia_dataset.py: | |
| python# agent/gaia_dataset.py | |
| """ | |
| Parser i loader dla oficjalnego datasetu GAIA. | |
| """ | |
| import json | |
| import os | |
| import requests | |
| from typing import List, Dict, Optional, Tuple | |
| from pathlib import Path | |
| import hashlib | |
| from dataclasses import dataclass | |
| @dataclass | |
| class GAIATask: | |
| """Pojedyncze zadanie GAIA.""" | |
| task_id: str | |
| question: str | |
| level: int | |
| final_answer: str | |
| file_name: Optional[str] = None | |
| file_path: Optional[str] = None | |
| def has_file(self) -> bool: | |
| """Czy zadanie ma plik dodatkowy.""" | |
| return self.file_name is not None | |
| class GAIADataset: | |
| """Loader dla datasetu GAIA z HuggingFace.""" | |
| BASE_URL = "https://huggingface.co/datasets/gaia-benchmark/GAIA/resolve/main" | |
| def __init__(self, cache_dir: str = ".gaia_cache"): | |
| """ | |
| Inicjalizacja loadera. | |
| Args: | |
| cache_dir: Katalog cache dla pobranych plików | |
| """ | |
| self.cache_dir = Path(cache_dir) | |
| self.cache_dir.mkdir(exist_ok=True) | |
| self.tasks = [] | |
| self.metadata_cache = self.cache_dir / "metadata.jsonl" | |
| def load_metadata(self, split: str = "test", year: str = "2023", force_download: bool = False) -> List[GAIATask]: | |
| """ | |
| Załaduj metadane zadań GAIA. | |
| Args: | |
| split: test/validation | |
| year: rok datasetu | |
| force_download: wymuś ponowne pobranie | |
| """ | |
| # Sprawdź cache | |
| if not force_download and self.metadata_cache.exists(): | |
| print(f"Loading metadata from cache: {self.metadata_cache}") | |
| return self._parse_metadata(self.metadata_cache) | |
| # Pobierz metadata | |
| metadata_url = f"{self.BASE_URL}/{year}/{split}/metadata.jsonl" | |
| print(f"Downloading metadata from: {metadata_url}") | |
| try: | |
| response = requests.get(metadata_url, timeout=30) | |
| response.raise_for_status() | |
| # Zapisz do cache | |
| self.metadata_cache.write_text(response.text) | |
| # Parse metadata | |
| return self._parse_metadata(self.metadata_cache) | |
| except Exception as e: | |
| print(f"Error downloading metadata: {e}") | |
| raise | |
| def _parse_metadata(self, metadata_file: Path) -> List[GAIATask]: | |
| """Parsuj plik metadata.jsonl.""" | |
| tasks = [] | |
| with open(metadata_file, 'r') as f: | |
| for line in f: | |
| if line.strip(): | |
| data = json.loads(line) | |
| task = GAIATask( | |
| task_id=data['task_id'], | |
| question=data['question'], | |
| level=int(data['level']), | |
| final_answer=data.get('final_answer', ''), # Może być ukryte w test set | |
| file_name=data.get('file_name'), | |
| file_path=data.get('file_path') | |
| ) | |
| tasks.append(task) | |
| self.tasks = tasks | |
| print(f"Loaded {len(tasks)} tasks") | |
| return tasks | |
| def get_level_tasks(self, level: int) -> List[GAIATask]: | |
| """Pobierz zadania konkretnego poziomu.""" | |
| return [task for task in self.tasks if task.level == level] | |
| def download_task_file(self, task: GAIATask, split: str = "test", year: str = "2023") -> Optional[Path]: | |
| """ | |
| Pobierz plik związany z zadaniem. | |
| Args: | |
| task: Zadanie GAIA | |
| split: test/validation | |
| year: rok datasetu | |
| Returns: | |
| Ścieżka do pobranego pliku lub None | |
| """ | |
| if not task.has_file(): | |
| return None | |
| # Ścieżka w cache | |
| file_cache_path = self.cache_dir / task.file_name | |
| # Jeśli już istnieje | |
| if file_cache_path.exists(): | |
| return file_cache_path | |
| # URL do pliku | |
| file_url = f"{self.BASE_URL}/{year}/{split}/{task.file_path}/{task.file_name}" | |
| try: | |
| print(f"Downloading file: {task.file_name}") | |
| response = requests.get(file_url, timeout=30) | |
| response.raise_for_status() | |
| # Zapisz plik | |
| file_cache_path.write_bytes(response.content) | |
| return file_cache_path | |
| except Exception as e: | |
| print(f"Error downloading file: {e}") | |
| return None | |
| def get_sample_tasks(self, n: int = 5, level: Optional[int] = None) -> List[GAIATask]: | |
| """ | |
| Pobierz próbkę zadań. | |
| Args: | |
| n: liczba zadań | |
| level: konkretny poziom (1, 2, 3) lub None dla wszystkich | |
| """ | |
| tasks = self.get_level_tasks(level) if level else self.tasks | |
| return tasks[:n] | |
| def validate_answer(self, task_id: str, answer: str) -> bool: | |
| """ | |
| Sprawdź odpowiedź (jeśli mamy ground truth). | |
| Args: | |
| task_id: ID zadania | |
| answer: Odpowiedź agenta | |
| Returns: | |
| True jeśli odpowiedź jest poprawna | |
| """ | |
| task = next((t for t in self.tasks if t.task_id == task_id), None) | |
| if not task or not task.final_answer: | |
| return False | |
| # Normalizuj odpowiedzi | |
| expected = task.final_answer.lower().strip() | |
| actual = answer.lower().strip() | |
| # Dokładne dopasowanie | |
| return expected == actual | |
| def generate_submission(self, agent_answers: Dict[str, str]) -> List[Dict]: | |
| """ | |
| Generuj format submission dla GAIA. | |
| Args: | |
| agent_answers: Dict {task_id: answer} | |
| Returns: | |
| Lista odpowiedzi w formacie GAIA | |
| """ | |
| submission = [] | |
| for task_id, answer in agent_answers.items(): | |
| submission.append({ | |
| "task_id": task_id, | |
| "model_answer": answer | |
| }) | |
| return submission | |
| 🧪 Tester na prawdziwych danych GAIA: | |
| python# tests/test_gaia_real.py | |
| """ | |
| Tester na oficjalnych danych GAIA. | |
| """ | |
| import sys | |
| import time | |
| from pathlib import Path | |
| sys.path.append(str(Path(__file__).parent.parent)) | |
| from agent.gaia_dataset import GAIADataset | |
| from agent.gaia_agent import ClaudeGAIAAgent | |
| def test_on_gaia_level1(max_questions: int = 20): | |
| """Test agenta na prawdziwych pytaniach GAIA Level 1.""" | |
| print("="*60) | |
| print("GAIA LEVEL 1 - OFFICIAL TEST") | |
| print("="*60) | |
| # Załaduj dataset | |
| print("\n1. Loading GAIA dataset...") | |
| dataset = GAIADataset() | |
| try: | |
| # Pobierz metadane (używa validation set bo test set nie ma odpowiedzi) | |
| tasks = dataset.load_metadata(split="validation", year="2023") | |
| level1_tasks = dataset.get_level_tasks(level=1) | |
| print(f"Found {len(level1_tasks)} Level 1 tasks") | |
| except Exception as e: | |
| print(f"Error loading dataset: {e}") | |
| print("Trying test set instead...") | |
| tasks = dataset.load_metadata(split="test", year="2023") | |
| level1_tasks = dataset.get_level_tasks(level=1) | |
| # Inicjalizuj agenta | |
| print("\n2. Initializing agent...") | |
| agent = ClaudeGAIAAgent() | |
| # Testuj na próbce | |
| print(f"\n3. Testing on {min(max_questions, len(level1_tasks))} questions...") | |
| print("-"*60) | |
| results = [] | |
| correct = 0 | |
| for i, task in enumerate(level1_tasks[:max_questions], 1): | |
| print(f"\n[{i}/{min(max_questions, len(level1_tasks))}] Task: {task.task_id[:8]}...") | |
| print(f"Question: {task.question[:100]}{'...' if len(task.question) > 100 else ''}") | |
| # Pobierz plik jeśli jest | |
| if task.has_file(): | |
| print(f"📎 Has attachment: {task.file_name}") | |
| file_path = dataset.download_task_file(task, split="validation") | |
| if file_path: | |
| print(f" Downloaded to: {file_path}") | |
| # Uruchom agenta | |
| start_time = time.time() | |
| try: | |
| answer = agent(task.question) | |
| elapsed = time.time() - start_time | |
| print(f"Agent answer: {answer}") | |
| print(f"Time: {elapsed:.2f}s") | |
| # Sprawdź odpowiedź (jeśli mamy ground truth) | |
| if task.final_answer: | |
| is_correct = dataset.validate_answer(task.task_id, answer) | |
| status = "✅" if is_correct else "❌" | |
| print(f"Expected: {task.final_answer}") | |
| print(f"Result: {status}") | |
| if is_correct: | |
| correct += 1 | |
| results.append({ | |
| 'task_id': task.task_id, | |
| 'question': task.question[:50], | |
| 'agent_answer': answer, | |
| 'expected': task.final_answer, | |
| 'correct': is_correct, | |
| 'time': elapsed | |
| }) | |
| else: | |
| print("Ground truth not available (test set)") | |
| results.append({ | |
| 'task_id': task.task_id, | |
| 'question': task.question[:50], | |
| 'agent_answer': answer, | |
| 'time': elapsed | |
| }) | |
| except Exception as e: | |
| print(f"❌ Error: {e}") | |
| results.append({ | |
| 'task_id': task.task_id, | |
| 'error': str(e) | |
| }) | |
| # Podsumowanie | |
| print("\n" + "="*60) | |
| print("SUMMARY") | |
| print("="*60) | |
| if any('correct' in r for r in results): | |
| total_with_answers = len([r for r in results if 'correct' in r]) | |
| accuracy = (correct / total_with_answers * 100) if total_with_answers > 0 else 0 | |
| print(f"Accuracy: {correct}/{total_with_answers} ({accuracy:.1f}%)") | |
| # Analiza błędów | |
| errors = [r for r in results if 'correct' in r and not r['correct']] | |
| if errors: | |
| print("\n❌ Failed questions:") | |
| for e in errors[:5]: # Pokaż max 5 błędów | |
| print(f" Q: {e['question']}...") | |
| print(f" Expected: {e['expected']}") | |
| print(f" Got: {e['agent_answer']}") | |
| print() | |
| # Statystyki czasowe | |
| times = [r['time'] for r in results if 'time' in r] | |
| if times: | |
| print(f"\nPerformance:") | |
| print(f" Avg time: {sum(times)/len(times):.2f}s") | |
| print(f" Min time: {min(times):.2f}s") | |
| print(f" Max time: {max(times):.2f}s") | |
| return results | |
| def test_specific_types(): | |
| """Test konkretnych typów pytań z GAIA.""" | |
| dataset = GAIADataset() | |
| tasks = dataset.load_metadata(split="validation", year="2023") | |
| # Kategoryzuj pytania | |
| math_tasks = [t for t in tasks if any(w in t.question.lower() for w in ['calculate', 'how many', 'sum'])] | |
| yes_no_tasks = [t for t in tasks if any(w in t.question.lower() for w in ['is it', 'is there', 'yes or no'])] | |
| print(f"Found {len(math_tasks)} math questions") | |
| print(f"Found {len(yes_no_tasks)} yes/no questions") | |
| # Test każdej kategorii... | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Test GAIA agent on real data") | |
| parser.add_argument("--max", type=int, default=10, help="Max questions to test") | |
| parser.add_argument("--types", action="store_true", help="Test specific types") | |
| args = parser.parse_args() | |
| if args.types: | |
| test_specific_types() | |
| else: | |
| test_on_gaia_level1(max_questions=args.max) | |
| 🚀 Uruchomienie na prawdziwych danych: | |
| bash# Podstawowy test (10 pytań) | |
| python tests/test_gaia_real.py --max 10 | |
| # Test większej próbki | |
| python tests/test_gaia_real.py --max 50 | |
| # Test typów pytań | |
| python tests/test_gaia_real.py --types | |
| 📊 Integracja z główną aplikacją: | |
| python# Dodaj do app.py możliwość testowania na GAIA | |
| def test_on_official_gaia(): | |
| """Funkcja do testowania na oficjalnych danych.""" | |
| from agent.gaia_dataset import GAIADataset | |
| dataset = GAIADataset() | |
| # Użyj validation set (ma odpowiedzi) | |
| tasks = dataset.load_metadata(split="validation") | |
| level1 = dataset.get_level_tasks(level=1) | |
| # Testuj agenta | |
| agent = ClaudeGAIAAgent() | |
| results = [] | |
| for task in level1[:20]: # Test na 20 pytaniach | |
| answer = agent(task.question) | |
| is_correct = dataset.validate_answer(task.task_id, answer) | |
| results.append({ | |
| 'task_id': task.task_id, | |
| 'correct': is_correct | |
| }) | |
| # Oblicz wynik | |
| accuracy = sum(r['correct'] for r in results) / len(results) | |
| return accuracy, results | |
| UWAGA: Test set nie ma odpowiedzi (final_answer), więc do walidacji używaj validation set. Test set służy do finalnej submisji na leaderboard. | |
| Ten parser da Ci możliwość: | |
| Testowania na prawdziwych pytaniach GAIA | |
| Analizy typów pytań gdzie agent słabo sobie radzi | |
| Generowania oficjalnych submisji | |
| Cache'owania plików lokalnie |