Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/CeibalEncuesta/gtk2/CeibalEncuesta/Globales.py
blob: b04c7b54310b7e5dbd2d3ce149107fb248cd1705 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-

#   Globales.py por:
#   Flavio Danesse <fdanesse@activitycentral.com>

# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import csv
import os
import chardet
import re


def csv_validate(archivo):

    valido = False

    extension = os.path.splitext(os.path.split(archivo)[1])[1]
    if "csv" in extension:
        valido = True

    with open(archivo, 'rb') as csvfile:
        encoding = chardet.detect(csvfile.read())['encoding']
        csvfile.seek(0)
        reader = csv.reader(csvfile, dialect='excel', delimiter=';')
        header = reader.next()
        header = ";".join(header).decode(encoding)
        expected_header = "RUEE;DEPARTAMENTO;NUM_ESC;GRADO;GRUPO;TIPO_GRUPO"
        valido = valido and (expected_header in header)

    return valido


def cargar_encuestados(csvfile):
    """
    Carga y devuelve una lista a encuestar
    desde un archivo csv.
    """

    alumnos = []

    archivo = open(csvfile, 'rb')
    encoding = chardet.detect(archivo.read())['encoding']
    archivo.seek(0)
    reader = csv.reader(archivo, dialect='excel', delimiter=';')

    for index, row in enumerate(reader):
        row = [x.decode(encoding) for x in row]
        alumnos.append(row)

    return alumnos


def evaluar(values, form):
    """
    Devuelve true o false para dependencias
    cumplidas. (values y form son la dependecia de una pregunta).
    """

    values = filter(lambda v: v != '' and v is not None, values)

    # dependencia normal, llega [True] o llega [False]
    if len(values) == 1:
        return values[0]

    values = map(lambda x: x.lower() if not isinstance(x, bool) else x, values)
    values = map(lambda x: str(x) if isinstance(x, bool) else x, values)

    if form == 4:
        __str = ' '.join(values)
        return eval(__str.strip(' '))

    elif form == 3 or len(values) == 3:
        __str = "( %s ) %s" % (
            ' '.join(values[0:3]),
            ' '.join(values[3:len(values)]),
        )
        return eval(__str.strip(' '))

    elif form == 2:
        __str = "( %s ) %s" % (
            ' '.join(values[0:5]),
            ' '.join(values[5:len(values)]),
        )
        return eval(__str.strip(' '))

    elif form == 1:
        __str = "( %s ) %s ( %s )" % (
            ' '.join(values[0:3]),
            values[3],
            ' '.join(values[4:len(values)]),
        )
        return eval(__str.strip(' '))


def convert(dependencia, opciones_activas):
    """
    Convierte los valores str de una dependencia
    a una operación lógica evaluable.
    """

    valor = list(dependencia['values'])
    forma = dependencia['form']

    for val in valor:
        if val == 'OR' or val == 'AND':
            continue

        else:
            indice = valor.index(val)

            if val in opciones_activas:
                valor[indice] = True

            else:
                valor[indice] = False

    return valor, forma

# EJEMPLO de Encuesta Contestada:
"""
{
"1101236 MONTEVIDEO 236 2 A 1 46415902 WILLIAM OPORTO": {},
"1101236 MONTEVIDEO 236 2 A 1 46415902 IGNACIO PEREZ": {
    "1": {
        "fields": {
            "0": {
                "widget_type": "DropDownList",
                "default": ["00003"],
                "options": {
                    "00004": {"text": "No"},
                    "00003": {"text": "Si"}},
                "dependence": "",
                "name": "\u00bfRecibiste en Alg\u00fan Momento tu XO?"}},
        "name": "Uso de la XO"}}, . . .

En caso de una pregunta cuyo widget es un entry,
se agrega clave newtext:

        "fields": {
                "0": {
                    "widget_type": "TextInput",
                    "default": ["00017"],
                    "options": {
                        "00017": {"newtext": "hola", "text": ""}},
                    "name": "Comentarios",
                    "dependence": ""}},
            "name": "Comentarios"}}
"""


class Encuesta(object):

    def __init__(self):
        self.finalizada = False

    def finalizar(self):
        self.finalizada = True

    def set_grupo(self, grupo):
        self.grupo = grupo


class Encuestado(object):

    def __init__(self, encuestado_str):
        self.encuestado_str = encuestado_str

    def get_tipo_grupo(self):
        match = re.search(r'\w+ (?P<num_esc>\d)+', self.encuestado_str)
        second = self.encuestado_str[match.end() + 1:]
        tipo_grupo = second.split()[2]
        return int(tipo_grupo)

    def get_id(self):
        return self.encuestado_str.decode("utf-8")


class GrupoDeEncuestados(object):

    TIPO_SUSTITUTO = 2
    TIPO_ORIGINAL = 1

    def get_tipo(self):
        tipos = {
            GrupoDeEncuestados.TIPO_ORIGINAL: 'original',
            GrupoDeEncuestados.TIPO_SUSTITUTO: 'sustituto'
        }
        return tipos[self.tipo]

    def set_tipo(self, tipo):
        self.tipo = tipo