File size: 9,237 Bytes
640af56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

import requests
import json
from transformers import pipeline

# 1) Lista completa das perguntas
questions = [
    {
        "id": 1,
        "question": "1.1 - Unidade do CEU:",
        "type": "radio",
        "options": [
            "CEU itapoã",
            "CEU Recanto",
            "CEU QNR 02",
            "CEU QMN 28",
            "CEU QNN 13",
            "Outro"
        ],
        "otherOption": True,
        "section": "1. Informações Gerais",
        "allowComment": False
    },
    {
        "id": 2,
        "question": "1.2 - Categoria de Participante:",
        "type": "radio",
        "options": [
            "Aluno(a)",
            "Pai/Mãe/Responsável",
            "Professor(a)",
            "Gestor(a)",
            "Monitor(a)",
            "Outro"
        ],
        "otherOption": True,
        "section": "1. Informações Gerais",
        "allowComment": False,
        "interpretation": "A pergunta identifica qual o tipo de envolvimento do participante com o CEU..."
    },
    {
        "id": 3,
        "question": "2.1 - Como você avalia a infraestrutura da unidade do CEU que frequenta?",
        "type": "radio",
        "options": ["Excelente", "Boa", "Regular", "Ruim", "Muito Ruim"],
        "section": "2. Avaliação Geral",
        "allowComment": True,
        "interpretation": "A maioria dos alunos avalia a infraestrutura como boa ou excelente..."
    },
    {
        "id": 4,
        "question": "2.3 - Como você avalia os programas e atividades oferecidos?",
        "type": "radio",
        "options": ["Excelente", "Boa", "Regular", "Ruim", "Muito Ruim"],
        "section": "2. Avaliação Geral",
        "allowComment": True,
        "interpretation": "Os programas e atividades oferecidos são amplamente bem avaliados..."
    },
    {
        "id": 5,
        "question": "2.4 - Os horários das atividades atendem às suas necessidades?",
        "type": "radio",
        "options": ["Sim", "Parcialmente", "Não"],
        "section": "2. Avaliação Geral",
        "allowComment": True,
        "interpretation": "Horários adequados facilitam a participação..."
    },
    {
        "id": 6,
        "question": "2.5 - Você sente que sua participação nas atividades contribui para seu desenvolvimento pessoal/profissional?",
        "type": "radio",
        "options": ["Sim", "Parcialmente", "Não"],
        "section": "2. Avaliação Geral",
        "allowComment": True,
        "interpretation": "A percepção de ganho pessoal/profissional é um indicador..."
    },
    {
        "id": 7,
        "question": "3.1 - Como você avalia o atendimento da equipe do CEU (monitores, professores, gestores)?",
        "type": "radio",
        "options": ["Excelente", "Boa", "Regular", "Ruim", "Muito Ruim"],
        "section": "3. Atendimento e Qualidade do Serviço",
        "allowComment": True,
        "interpretation": "O atendimento da equipe é crucial para a satisfação..."
    },
    {
        "id": 8,
        "question": "3.2 - Você sente que a equipe do CEU está disponível e pronta para ajudar quando necessário?",
        "type": "radio",
        "options": ["Sempre", "Na maioria das vezes", "Às vezes", "Raramente", "Nunca"],
        "section": "3. Atendimento e Qualidade do Serviço",
        "allowComment": True,
        "interpretation": "Disponibilidade e prontidão da equipe refletem diretamente no bem-estar..."
    },
    {
        "id": 9,
        "question": "3.3 - Como você avalia a comunicação da unidade (informação sobre eventos, mudanças, etc.)?",
        "type": "radio",
        "options": ["Excelente", "Boa", "Regular", "Ruim", "Muito Ruim"],
        "section": "3. Atendimento e Qualidade do Serviço",
        "allowComment": True,
        "interpretation": "Uma boa comunicação é essencial para engajamento..."
    },
    {
        "id": 10,
        "question": "4.1 - As atividades do CEU têm impacto positivo na sua vida ou na de seus filhos?",
        "type": "radio",
        "options": ["Sim", "Parcialmente", "Não"],
        "section": "4. Impacto e Satisfação Pessoal",
        "allowComment": True,
        "interpretation": "Medir o impacto positivo demonstra o valor social do CEU..."
    },
    {
        "id": 11,
        "question": "4.2 - Você indicaria o CEU para amigos ou familiares?",
        "type": "radio",
        "options": ["Sim", "Talvez", "Não"],
        "section": "4. Impacto e Satisfação Pessoal",
        "allowComment": True,
        "interpretation": "O indicador de recomendação sugere grau de satisfação..."
    },
    {
        "id": 12,
        "question": "5.1 - Há algo que você gostaria de ver melhorado no CEU?",
        "type": "radio",
        "options": ["Sim", "Não"],
        "section": "5. Sugestões e Melhorias",
        "allowComment": True,
        "interpretation": "Esta pergunta abre espaço para melhorias pontuais e específicas..."
    },
    {
        "id": 13,
        "question": "5.2 - Que tipo de novas atividades ou programas você gostaria de ver no CEU?",
        "type": "radio",
        "options": ["Sim", "Não"],
        "section": "5. Sugestões e Melhorias",
        "allowComment": True,
        "interpretation": "Novas atividades ou programas expandem a atratividade do CEU..."
    },
    {
        "id": 14,
        "question": "5.3 - Há algum outro comentário ou sugestão que gostaria de compartilhar?",
        "type": "radio",
        "options": ["Sim", "Não"],
        "section": "5. Sugestões e Melhorias",
        "allowComment": True,
        "interpretation": "Um espaço aberto para o participante expressar livremente..."
    }
]

# Mapeia id da pergunta => texto
questions_map = {q["id"]: q["question"] for q in questions}

# URL da API
url = "https://proced.datasavvy.com.br/api/responses"

# Consome a API
response = requests.get(url)
if response.status_code == 200:
    data = response.json()
else:
    print("Erro ao acessar a API:", response.status_code)
    exit()

# Montar lista de associações
associacoes = []
for registro in data:
    if "answers" in registro and "comments" in registro:
        for pergunta_id_str, resposta in registro["answers"].items():
            try:
                pergunta_id = int(pergunta_id_str)
            except ValueError:
                pergunta_id = None
            
            comentario = registro["comments"].get(pergunta_id_str, None)
            
            # Aqui, ao invés de "studentId": registro["studentId"]
            # Usamos o token que está em registro["student_info"]["token"]
            associacoes.append({
                "studentId": registro["student_info"]["token"],  # <== Mudança aqui
                "perguntaId": pergunta_id_str,
                "perguntaTexto": questions_map.get(pergunta_id, f"Pergunta {pergunta_id_str}"),
                "resposta": resposta,
                "comentario": comentario
            })

# Inicializar o pipeline de Zero-Shot Classification
classifier = pipeline(
    task="zero-shot-classification",
    model="joeddav/xlm-roberta-large-xnli"  # modelo multilíngue PT
)

candidate_labels = [
    "sugestões de melhoria",
    "elogios",
    "reclamações",
    "solicitações de serviços ou infraestrutura"
]

classified_comments = []
for registro in data:
    if "comments" not in registro or "answers" not in registro:
        continue
    
    for question_id_str, comment in registro["comments"].items():
        if not comment or not comment.strip():
            continue
        
        answer = registro["answers"].get(question_id_str, "Sem resposta")
        
        try:
            q_id = int(question_id_str)
        except ValueError:
            q_id = None
        
        question_text = questions_map.get(q_id, f"Pergunta {question_id_str}")
        
        text_for_model = f"Pergunta: {question_text}. Comentário: {comment}"
        
        classification_result = classifier(
            text_for_model,
            candidate_labels,
            multi_label=False
        )

        best_label = classification_result["labels"][0]
        best_score = classification_result["scores"][0]

        # Aqui também
        classified_comments.append({
            "studentId": registro["student_info"]["token"],  # <== Mudança aqui
            "questionId": question_id_str,
            "questionText": question_text,
            "answer": answer,
            "comment": comment,
            "classification": best_label,
            "confidence": best_score
        })

# Salvar resultados em JSON
with open("associacoes.json", "w", encoding="utf-8") as assoc_file:
    json.dump(associacoes, assoc_file, indent=4, ensure_ascii=False)
    print("Arquivo 'associacoes.json' criado com sucesso!")

with open("classified_comments.json", "w", encoding="utf-8") as classified_file:
    json.dump(classified_comments, classified_file, indent=4, ensure_ascii=False)
    print("Arquivo 'classified_comments.json' criado com sucesso!")

# Mostra uma amostra
print("\n--- Associações (amostra) ---")
for assoc in associacoes[:5]:
    print(assoc)

print("\n--- Classificações (amostra) ---")
for classified in classified_comments[:5]:
    print(classified)