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

Project   F

Complexity

Total Complexity 79

Size/Duplication

Total Lines 232
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
dl 0
loc 232
rs 2.0547
c 3
b 0
f 0
wmc 79

19 Methods

Rating   Name   Duplication   Size   Complexity  
A __iter__() 0 2 1
A get_number_of_entries() 0 4 1
F __next__() 0 28 12
A get_columns() 0 4 2
A init_dict() 0 7 4
A __init__() 0 12 2
A __question_already_answered() 0 5 1
A handleTSV() 0 10 3
A all_tables() 0 5 2
F init_db() 0 42 17
A system_tables() 0 3 1
F export() 0 41 16
A __transform_column() 0 16 4
A get_questions() 0 5 2
A store_answer() 0 5 1
A handleCSV() 0 9 3
A custom_tables() 0 3 3
A __reverse_transform_column() 0 7 3
A get_whole_table() 0 5 1

How to fix   Complexity   

Complex Class

Complex classes like Project often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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