File size: 3,495 Bytes
314fc0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from dataclasses import dataclass
from typing import Optional, Dict, Any
import json


@dataclass
class TaskItem:
    """
    Model representing a task/question item from the evaluation system.
    
    Attributes:
        task_id: Unique identifier for the task
        question: The question text to be answered
        level: Difficulty level of the task (default: "1")
        file_name: Associated file name if any (default: empty string)
    """
    task_id: str
    question: str
    level: str = "1"
    file_name: str = ""
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'TaskItem':
        """
        Create TaskItem from dictionary/JSON data.
        
        Args:
            data: Dictionary containing task data
            
        Returns:
            TaskItem instance
            
        Raises:
            ValueError: If required fields are missing
        """
        if not data.get("task_id"):
            raise ValueError("task_id is required")
        if not data.get("question"):
            raise ValueError("question is required")
            
        return cls(
            task_id=data["task_id"],
            question=data["question"],
            level=data.get("Level", "1"),  # Note: JSON uses "Level" not "level"
            file_name=data.get("file_name", "")
        )
    
    @classmethod
    def from_json(cls, json_str: str) -> 'TaskItem':
        """
        Create TaskItem from JSON string.
        
        Args:
            json_str: JSON string containing task data
            
        Returns:
            TaskItem instance
        """
        data = json.loads(json_str)
        return cls.from_dict(data)
    
    def to_dict(self) -> Dict[str, Any]:
        """
        Convert TaskItem to dictionary format.
        
        Returns:
            Dictionary representation of the task
        """
        return {
            "task_id": self.task_id,
            "question": self.question,
            "Level": self.level,  # Maintain original JSON key format
            "file_name": self.file_name
        }
    
    def to_json(self) -> str:
        """
        Convert TaskItem to JSON string.
        
        Returns:
            JSON string representation of the task
        """
        return json.dumps(self.to_dict(), indent=2)
    
    def is_valid(self) -> bool:
        """
        Check if the TaskItem has valid required fields.
        
        Returns:
            True if task_id and question are non-empty, False otherwise
        """
        return bool(self.task_id and self.question)
    
    def __str__(self) -> str:
        """String representation showing task ID and truncated question."""
        question_preview = self.question[:50] + "..." if len(self.question) > 50 else self.question
        return f"TaskItem(id={self.task_id}, level={self.level}, question='{question_preview}')"


# Example usage and testing
if __name__ == "__main__":
    # Example JSON data
    sample_json = {
        'task_id': '8e867cd7-cff9-4e6c-867a-ff5ddc2550be',
        'question': 'How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia.',
        'Level': '1',
        'file_name': ''
    }
    
    # Create TaskItem from dictionary
    task = TaskItem.from_dict(sample_json)
    print("Created TaskItem:")
    print(task)
    print("\nIs valid:", task.is_valid())
    print("\nBack to dict:", task.to_dict())