File size: 6,074 Bytes
6859205
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import requests
import json
import pandas as pd
from typing import List, Dict, Any

class QuestionAnalyzer:
    def __init__(self, api_url: str = "https://agents-course-unit4-scoring.hf.space"):
        self.api_url = api_url
        self.questions_url = f"{api_url}/questions"
        self.questions_data = None
    
    def fetch_questions(self) -> bool:
        """
        Recupera le domande dal server e le salva nell'istanza
        Returns: True se il fetch Γ¨ andato a buon fine, False altrimenti
        """
        print(f"Fetching questions from: {self.questions_url}")
        try:
            response = requests.get(self.questions_url, timeout=15)
            response.raise_for_status()
            self.questions_data = response.json()
            
            if not self.questions_data:
                print("❌ Questions list is empty.")
                return False
                
            print(f"βœ… Successfully fetched {len(self.questions_data)} questions.")
            return True
            
        except requests.exceptions.RequestException as e:
            print(f"❌ Error fetching questions: {e}")
            return False
        except json.JSONDecodeError as e:
            print(f"❌ Error decoding JSON response: {e}")
            return False
        except Exception as e:
            print(f"❌ Unexpected error: {e}")
            return False
    
    def analyze_structure(self) -> None:
        """Analizza la struttura delle domande"""
        if not self.questions_data:
            print("❌ No questions data available. Run fetch_questions() first.")
            return
        
        print("\n" + "="*50)
        print("QUESTION STRUCTURE ANALYSIS")
        print("="*50)
        
        # Analisi generale
        print(f"πŸ“Š Total questions: {len(self.questions_data)}")
        
        if len(self.questions_data) > 0:
            # Analizza il primo elemento per capire la struttura
            first_question = self.questions_data[0]
            print(f"\nπŸ” Keys in each question: {list(first_question.keys())}")
            
            # Mostra il primo esempio completo
            print(f"\nπŸ“ First question example:")
            for key, value in first_question.items():
                if isinstance(value, str) and len(value) > 100:
                    print(f"  {key}: {value[:100]}...")
                else:
                    print(f"  {key}: {value}")
    
    def show_sample_questions(self, n: int = 5) -> None:
        """Mostra n domande di esempio"""
        if not self.questions_data:
            print("❌ No questions data available. Run fetch_questions() first.")
            return
            
        print(f"\n" + "="*50)
        print(f"SAMPLE QUESTIONS (showing first {min(n, len(self.questions_data))})")
        print("="*50)
        
        for i, question in enumerate(self.questions_data[:n]):
            print(f"\n--- Question {i+1} ---")
            task_id = question.get('task_id', 'N/A')
            question_text = question.get('question', 'N/A')
            
            print(f"Task ID: {task_id}")
            print(f"Question: {question_text[:200]}{'...' if len(question_text) > 200 else ''}")
            
            # Mostra altri campi se presenti
            for key, value in question.items():
                if key not in ['task_id', 'question']:
                    if isinstance(value, str) and len(value) > 50:
                        print(f"{key}: {value[:50]}...")
                    else:
                        print(f"{key}: {value}")
    
    def create_summary_dataframe(self) -> pd.DataFrame:
        """Crea un DataFrame riassuntivo delle domande"""
        if not self.questions_data:
            print("❌ No questions data available. Run fetch_questions() first.")
            return pd.DataFrame()
        
        summary_data = []
        for question in self.questions_data:
            summary_row = {
                'task_id': question.get('task_id', 'N/A'),
                'question_length': len(question.get('question', '')),
                'question_preview': question.get('question', '')[:100] + '...' if len(question.get('question', '')) > 100 else question.get('question', ''),
            }
            
            # Aggiungi altri campi se presenti
            for key, value in question.items():
                if key not in ['task_id', 'question']:
                    summary_row[key] = value
            
            summary_data.append(summary_row)
        
        return pd.DataFrame(summary_data)
    
    def save_questions_to_file(self, filename: str = "questions_data.json") -> bool:
        """Salva le domande in un file JSON locale"""
        if not self.questions_data:
            print("❌ No questions data available. Run fetch_questions() first.")
            return False
        
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                json.dump(self.questions_data, f, indent=2, ensure_ascii=False)
            print(f"βœ… Questions saved to {filename}")
            return True
        except Exception as e:
            print(f"❌ Error saving questions: {e}")
            return False


def main():
    """Funzione principale per testare il QuestionAnalyzer"""
    print("πŸš€ Starting Question Analysis...")
    
    # Crea l'analyzer
    analyzer = QuestionAnalyzer()
    
    # Fetch delle domande
    if not analyzer.fetch_questions():
        print("❌ Failed to fetch questions. Exiting.")
        return
    
    # Analizza la struttura
    analyzer.analyze_structure()
    
    # Mostra domande di esempio
    analyzer.show_sample_questions(3)
    
    # Crea e mostra DataFrame riassuntivo
    df = analyzer.create_summary_dataframe()
    if not df.empty:
        print(f"\n" + "="*50)
        print("SUMMARY DATAFRAME")
        print("="*50)
        print(df.head(10))
    
    # Salva le domande localmente
    analyzer.save_questions_to_file()
    
    print(f"\nβœ… Analysis complete!")


if __name__ == "__main__":
    main()