Completed
Pull Request — master (#22)
by Jerome
25s
created

CodingUnit   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 22
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

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