Completed
Push — master ( db34c1...589162 )
by Jerome
12s
created

CodingUnit   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 23
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 10
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __init__() 0 8 1
A isFinished() 0 5 3
A __repr__() 0 3 2
A __setitem__() 0 3 1
1
import os
2
import random
3
import sqlite3
4
5
import yaml
6
7
8
class FileNotFoundError(IOError):
9
    pass
10
11
12
class ProjectBuilder(object):
13
    def __init__(self, **kwargs):
14
        if "data" in kwargs:
15
            self.data = kwargs["data"]
16
        else:
17
            self.data = None
18
        if "coder" in kwargs:
19
            self.coder = kwargs["coder"]
20
        else:
21
            self.coder = None
22
        if "config" in kwargs:
23
            self.config = kwargs["config"]
24
        else:
25
            self.config = None
26
27
    def finished(self):
28
        return self.data is not None and self.coder is not None and self.config is not None
29
30
    def build(self):
31
        return Project(data=self.data, coder=self.coder, config=self.config)
32
33
34
class Project(object):
35
    def __init__(self, path=".", file="project.db", coder=None, *args, **kwargs):
36
        # Project file doesn't already exist
37
        self.path = path
38
        self.file = file
39
        self.conn = sqlite3.connect(os.path.join(path, file))
40
        self.init_db(path, *args, **kwargs)
41
        self.current_coding_unit = None
42
        if coder is not None:
43
            self.coder = coder
44
        else:
45
            raise Exception("Please define the coder!")
46
        print("End init")
47
48
    def init_db(self, path, *args, **kwargs):
49
        c = self.conn.cursor()
50
        c.execute("""CREATE TABLE IF NOT EXISTS vars (key text, value text)""")
51
        c.execute("""CREATE TABLE IF NOT EXISTS translation (clear text, translated text, UNIQUE(clear, translated))""")
52
        self.conn.commit()
53
        if "data" in kwargs:
54
            with open(os.path.join(path, kwargs["data"])) as file:
55
                res = Project.handleCSV(file, ";")
56
            if len(res):
57
                titles = list(res[0].keys())
58
                cquery = ["{} {}".format(self.__transform_column(i), "TEXT") for i in titles]
59
                cquery = ", ".join(cquery)
60
                c.execute("""CREATE TABLE IF NOT EXISTS individuals (id INTEGER PRIMARY KEY,{})""".format(cquery))
61
                self.conn.commit()
62
                for row in res:
63
                    columns = []
64
                    values = []
65
                    for column in row:
66
                        if len(row[column].strip()) != 0:
67
                            columns.append(self.__transform_column(column))
68
                            values.append((row[column]))
69
                    aquery = " AND ".join(i + "=?" for i in columns)
70
71
                    if len(values):
72
                        c.execute("""SELECT id FROM individuals WHERE {}""".format(aquery), values)
73
                        identifier = c.fetchone()
74
                        if not identifier:
75
                            c.execute("""INSERT INTO individuals ({}) VALUES ({})""".format(", ".join(columns),
76
                                                                                            " ,".join(
77
                                                                                                "?" for _ in values)),
78
                                      values)
79
                            self.conn.commit()
80
        if "config" in kwargs:
81
            c.execute("""CREATE TABLE IF NOT EXISTS question_assoc (question text, coding text)""")
82
            with open(os.path.join(path, kwargs["config"])) as file:
83
                questions = yaml.load(file)
84
                print(questions)
85
            for question in questions["questions"]:
86
87
                qquery = ", ".join(
88
                    [self.__transform_column(i["criteria"]) + " TEXT" for i in question["coding"]] + ["coder TEXT"])
89
                c.execute("""CREATE TABLE IF NOT EXISTS {} (id INTEGER PRIMARY KEY, {})""".format(
90
                    self.__transform_column(question["text"]), qquery))
91
                for i in question["coding"]:
92
                    c.execute("""INSERT INTO question_assoc SELECT ?,?
93
                                  WHERE NOT EXISTS(SELECT 1 FROM question_assoc WHERE question=? AND coding=?)""",
94
                              (question["text"], i["criteria"], question["text"], i["criteria"]))
95
                self.conn.commit()
96
97
    def get_questions(self, question):
98
        c = self.conn.cursor()
99
        c.execute("""SELECT coding FROM question_assoc WHERE question=?""", (question,))
100
        res = [i[0] for i in c.fetchall()]
101
        return res
102
103
    def __transform_column(self, column):
104
        column = column.strip()
105
        before = column
106
        for i in "?()-,;[].=":
107
            column = column.replace(i, "_")
108
        columns = column.split(" ")
109
        columns = list(map(str.lower, columns))
110
        kw = ["alter"]
111
        for i in range(len(columns)):
112
            if columns[i] in kw:
113
                columns[i] = "_".join([columns[i][:-1], columns[i][-1]])
114
        column = "_".join(columns)
115
        c = self.conn.cursor()
116
        c.execute("""INSERT OR IGNORE INTO translation (clear, translated) VALUES (?,?)""", (before, column))
117
        self.conn.commit()
118
        return column
119
120
    def __reverse_transform_column(self, column):
121
        c = self.conn.cursor()
122
        c.execute("""SELECT clear FROM translation WHERE translated=?""", (column,))
123
        res = c.fetchone()
124
        if res is not None and len(res) > 0:
125
            return str(res[0])
126
        return str(None)
127
128
    def init_dict(self, init_kwargs, **kwargs):
129
        for i in kwargs:
130
            if i not in self.state:
131
                if i in init_kwargs:
132
                    self.state[i] = init_kwargs[i]
133
                else:
134
                    self.state[i] = kwargs[i]
135
136
    @staticmethod
137
    def handleCSV(file, separator):
138
        res = []
139
        titles = []
140
        for i, j in enumerate(file):
141
            if i == 0:
142
                titles = j.strip("\n").split(separator)
143
            else:
144
                res.append(dict(zip(titles, j.strip("\n").split(separator))))
145
        return res
146
147
    @property
148
    def all_tables(self):
149
        c = self.conn.cursor()
150
        c.execute("""SELECT name FROM sqlite_master WHERE type='table'""")
151
        return [self.__transform_column(i[0]) for i in c.fetchall()]
152
153
    @property
154
    def custom_tables(self):
155
        return [i for i in self.all_tables if i not in self.system_tables]
156
157
    @property
158
    def system_tables(self):
159
        return ["vars", "individuals", "question_assoc", "translation"]
160
161
    def get_columns(self, table):
162
        c = self.conn.cursor()
163
        c.execute("""PRAGMA table_info({})""".format(table))
164
        return [i[1] for i in c.fetchall()]
165
166
    def get_number_of_entries(self, table):
167
        c = self.conn.cursor()
168
        c.execute("""SELECT count(*) FROM individuals""".format(self.__transform_column(table)))
169
        return c.fetchall()[0][0]
170
171
    def get_whole_table(self, table):
172
        colums = self.get_columns(table)
173
        c = self.conn.cursor()
174
        c.execute("""SELECT {} FROM {}""".format(", ".join(colums), table))
175
        return c.fetchall()
176
177
    def __iter__(self):
178
        return self
179
180
    def __next__(self):
181
        if self.current_coding_unit is not None:
182
            if not self.current_coding_unit.isFinished():
183
                return self.current_coding_unit
184
        amount_of_individuals = self.get_number_of_entries("individuals")
185
        for table in self.custom_tables:
186
            c = self.conn.cursor()
187
            c.execute("""SELECT * FROM {}""".format(table))
188
189
            ids_in_table = c.fetchall()
190
            ids_in_table[:] = [i for i in ids_in_table if None not in i]
191
            if amount_of_individuals > len(ids_in_table):
192
                entries = set(range(amount_of_individuals)) - set([i[0] for i in ids_in_table])
193
                entry = random.choice(list(entries))
194
                c.execute("""SELECT {} FROM individuals""".format(table))
195
                coding_answer = c.fetchall()[entry][0]
196
                coding_question = self.__reverse_transform_column(table)
197
                questions = self.get_questions(coding_question)
198
                questions[:] = [i for i in questions if not self.__question_already_answered(coding_question, i, entry)]
199
                if len(questions) == 0:
200
                    c.execute("""SELECT * FROM question_assoc""")
201
                    res = c.fetchall()
202
                    for i in res:
203
                        print(i, len(i[0]), len(coding_question), repr(coding_question))
204
                    raise Exception("This should not happen")
205
                self.current_coding_unit = CodingUnit(self, coding_question, coding_answer, questions, entry)
206
                return self.current_coding_unit
207
        raise StopIteration
208
209
    def __question_already_answered(self, coding_question, question, id_):
210
        c = self.conn.cursor()
211
        c.execute("""SELECT {} FROM {} WHERE id=?""".format(self.__transform_column(question),
212
                                                            self.__transform_column(coding_question)), (id_,))
213
        res = c.fetchone()
214
        return res is not None and res[0] is not None
215
216
    def store_answer(self, coding_question, question, answer, id_):
217
        c = self.conn.cursor()
218
        c.execute("""INSERT OR IGNORE INTO {} (id,{}) VALUES (?,?)""".format(self.__transform_column(coding_question),
219
                                                                             self.__transform_column(question)),
220
                  (id_, answer))
221
        c.execute("""UPDATE {} SET id=?,{}=? WHERE id=?""".format(self.__transform_column(coding_question),
222
                                                                  self.__transform_column(question)),
223
                  (id_, answer, id_))
224
        self.conn.commit()
225
226
    def export(self, filename="out.txt"):
227
        with open(os.path.join(self.path, filename), "w") as file:
228
            file.write("\t".join([self.__reverse_transform_column(i) for i in self.get_columns("individuals") if
229
                                  i not in self.custom_tables + ["id"]]
230
                                 + ["Question to participant", "Participant Answer", "Coder", "Coding Questions",
231
                                    "Coding Answer", "\n"]))
232
            for individual in self.get_whole_table("individuals"):
233
                column = self.get_columns("individuals")
234
                individual = dict(zip(column, individual))
235
                for question in self.custom_tables:
236
                    for i in self.get_whole_table(question):
237
                        column = self.get_columns(question)
238
                        coding_questions = dict(zip(column, i))
239
                        if coding_questions["id"] == individual["id"]:
240
                            for coding_question in coding_questions:
241
                                if coding_question != "id" and coding_question != "coder":
242
                                    file.write("\t".join([str(individual[i]) for i in self.get_columns("individuals") if
243
                                                          i not in self.custom_tables + ["id"]]
244
                                                         + [str(self.__reverse_transform_column(question)),
245
                                                            str(individual[question]), coding_questions["coder"],
246
                                                            self.__reverse_transform_column(coding_question),
247
                                                            coding_questions[coding_question], "\n"]))
248
249
        titles = list()
250
        for i in ["individuals"] + self.custom_tables:
251
            for j in self.get_columns(i):
252
                titles.append((i, j))
253
        """
254
        columns = [i[1] for i in titles if i[0] == "individuals" and i[1] not
255
         in [self.__transform_column(i[0]) for i in self.custom_tables]]
256
        print(len(columns),columns)
257
        """
258
        '''
259
        command = """SELECT {} FROM individuals\n""".format(", ".join(list(map(".".join, titles)))) + "".join(
260
            ["""INNER JOIN {} ON {}\n""".format(i, """{}.id = individuals.id""".format(i)) for i in self.custom_tables])
261
        '''
262
        """
263
        print(command)
264
        c = self.conn.cursor()
265
        c.execute(command)
266
        res = c.fetchall()
267
        print(res)
268
        for i in res:
269
            print(i)
270
        print( titles )
271
        print([(i[0],self.__reverse_transform_column(i[1])) for i in titles])
272
273
        #with open(os.path.join(self.path,filename)):
274
        #    pass
275
        """
276
277
278
class CodingUnit(object):
279
    def __init__(self, project, question, answer, coding_questions, id_):
280
        self.question = question
281
        self.answer = answer
282
        self.coding_questions = coding_questions
283
        self.coding_answers = dict()
284
        self.id = id_
285
        self.project = project
286
        self["coder"] = project.coder
287
288
    def isFinished(self):
289
        res = True
290
        res &= all(i in self.coding_answers.keys() for i in self.coding_questions)
291
        res &= all(self.coding_answers[i] is not None for i in self.coding_answers)
292
        return res
293
294
    def __setitem__(self, key, value):
295
        self.coding_answers[key] = value
296
        self.project.store_answer(self.question, key, value, self.id)
297
298
    def __repr__(self):
299
        return "\n".join(["Coding unit: {} -> {}".format(self.question, self.answer)] + [
300
            "-{}\n\t-> {}".format(i, self.coding_answers.get(i, None)) for i in self.coding_questions])
301