main.py 13.3 KB
Newer Older
Siddharth Thorat's avatar
Siddharth Thorat committed
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
import tkinter as tk
from tkinter import filedialog
from tkinter import BOTTOM, RIDGE, RIGHT, Label, Menu, Toplevel, ttk
from tkinter.messagebox import showwarning
from tkinter.font import NORMAL
from tkinter.messagebox import showinfo
from tkinter.filedialog import askopenfilename
from tkinter import DISABLED

import csv
import xlsxwriter
import tkinter

##import sentence_transformers

import pandas as pd
import sys
import os
from sklearn.metrics import f1_score
from matplotlib import pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
from Skript.english.run_SAG_mnli import main as english_backend
from Skript.german.run_LR_SBERT import main as german_backend


class App(ttk.Frame):

    def __init__(self, parent):
        ttk.Frame.__init__(self)

        # Make the app responsive
        for index in [0, 1, 2]:
            self.columnconfigure(index=index, weight=1)
            self.rowconfigure(index=index, weight=1)

        # Create value list
        self.combo_list = ["Choose language of input data", "English", "German"]

        # Create a Frame for input widgets
        self.widgets_frame = ttk.Frame(self)
        self.widgets_frame.grid(
            row=1, column=1, sticky="nsew", rowspan=8
        )
        self.widgets_frame.columnconfigure(index=0, weight=1)
        root.lift(self.widgets_frame)

        # Set Menu list
        self.menubar = Menu(root)
        root.configure(menu=self.menubar)
        self.options_menu = Menu(self.menubar)
        self.options_menu.add_command(label='Fenster schließen', command=root.destroy)
        self.options_menu.add_cascade(label='Optionen', menu=self.options_menu)

        # create labelframe for the file names read in 
        labelframe = tk.LabelFrame(self.widgets_frame, text="Input File", height=80, width=300, font=("Segoeui 10"))
        labelframe.grid(row=25, column=0, padx=1, pady=15, sticky="nsew")
        text = tk.Label(labelframe, text="", font=("Segoeui  10"))
        text.pack()
        labelframe.update()

        # open filechooser for .csv-files, set the state for the "Start" button1 and show infoboxes
        self.csv_file_path = ""

        def import_csv_data():
            csv_file_path = askopenfilename(
                title="Open .csv file", initialdir='Dokumente', filetypes=(
                    ("Excel files", "*.xlsx"), ("csv files", "*.csv"), ("tsv files", "*.tsv"), ("all files", "*.*")))
            # update the labelframe with the file cut down to only filename w/o path
            text.configure(text=os.path.basename(csv_file_path))
            # windows path:
            csv_file_path = csv_file_path.replace("/", "\\")

            indexIdent = csv_file_path

            # Set environment for output.csv files
            output_str = 'Skript\\outputs\\test.tsv'

            # Windows path:
            output_str = resource_path(output_str)

            # Excel files are parsed into csv files
            if indexIdent.endswith('.xlsx'):

                # Check if file exists
                if os.path.exists(csv_file_path):
                    # showinfo(title="debug_info", message=output_str + "\n" + indexIdent)
                    read_file = pd.read_excel(indexIdent)
                    read_file.to_csv(output_str, index=None, header=True, quoting=csv.QUOTE_NONE, escapechar="\t",
                                     sep='\t')

                    # when the input data has been loaded, highlight the Start button to indicate that
                    # grading can now commence
                    self.style = ttk.Style(self)
                    self.style.configure('Wild.TButton', font=('Helvetica', 14, 'bold'),
                                         foreground='green')

                    self.button1.config(state=NORMAL, style='Wild.TButton')
                    print(self.button1.winfo_class())

                    labelframe.update()
                    root.update()
                    print(self.button1.winfo_class())

                else:
                    showinfo(
                        title="Information",
                        message="File " + csv_file_path + " could not be found."
                        # message="Please choose a file"
                    )



            else:
                showinfo(
                    title="Information",
                    message="File " + csv_file_path + " could not be opened. Is it an Excel Sheet?"
                    # message="Please choose a file"
                )

        # New output window for showing the content of a csv file

        def open_new_window():
            new_window = Toplevel(root)
            new_window.protocol("WM_DELETE_WINDOW", new_window.destroy)
            new_window.title("ASYST Evaluated Results")
            new_window.geometry("850x500")
            new_window.iconbitmap(resource_path("icon.ico"))
            lab = Label(new_window, text="Results\n\nClick on Save As button below to view the file",
                        font=("Segoeui 20 bold"))
            lab.pack(padx=0, pady=35)

            # container = ttk.Frame(new_window)
            # canvas = tk.Canvas(container)
            # scrollbary = ttk.Scrollbar(container, orient='vertical', command=canvas.yview)
            # scrollbar = ttk.Scrollbar(container, orient="horizontal", command=canvas.xview)
            # scrollable_frame = ttk.Frame(canvas)
            # scrollable_frame.bind(
            #     "<Configure>",
            #     lambda e: canvas.configure(
            #         scrollregion=canvas.bbox("all")
            #     )
            # )
            # canvas.configure(scrollregion=canvas.bbox("all"))
            # canvas.create_window((4, 4), window=scrollable_frame)

            csv_file_path = resource_path("Skript\\outputs\\predictions.txt");

            #############

            # Read the csv file and parse it into the table

            # with open((csv_file_path), "r", newline="", encoding="utf8") as f:
            #
            #     reader = csv.reader(f, delimiter="\t")
            #     r = 0
            #     for col in reader:
            #         c = 0
            #         for row in col:
            #             # variable column width
            #             col_width = 65
            #             anch = 'center'
            #             match c:
            #                 case 0:
            #                     col_width = 10  # ID is short
            #                     anch = 'w'
            #                 case 3:
            #                     col_width = 20  # label is short
            #                     anch = 'w'
            #                 case 4:
            #                     col_width = 20  # label is short
            #                     anch = 'w'
            #
            #             label = Label(scrollable_frame, width=col_width, height=4, text=row, wraplength=500,
            #                           anchor=anch, relief=RIDGE,
            #                           font=("Segoeui 10"))
            #             label.grid(row=r + 1, column=c + 1)
            #             string_c = "incorrect"
            #             if string_c in row:
            #                 label.config(bg="red")
            #             c += 1
            #         r += 1
            #
            # canvas.config(height=500, width=1500, xscrollcommand=scrollbar.set, yscrollcommand=scrollbary.set)
            # canvas.configure(xscrollcommand=scrollbar.set, yscrollcommand=scrollbary.set)
            # scrollbary.pack(side=RIGHT, fill=tk.Y)
            # scrollbar.pack(side=BOTTOM, fill=tk.X)

            ################################

            save_button = ttk.Button(new_window, text="Save as ...", command=save_as_excel)
            save_button.pack(side=BOTTOM, expand=True)

            # container.pack(padx=30, pady=15, fill="both", expand=True)
            # canvas.pack(fill="both", expand=True)

        def save_as_excel():

            csvfile = "Skript\\outputs\\predictions.txt"
            name = "predictions.xlsx"

            # for Windows:
            csvfile = resource_path(csvfile)

            t = tkinter.filedialog.asksaveasfile(initialfile=name, mode='w',
                                                 filetypes=[("All Files", "*.*"), ("Excel Files", "*.xlsx")],
                                                 defaultextension=".xlsx")

            if t is not None:  # Check if the user didn't click Cancel
                file_path = t.name  # Save the location of the saved file
                # print(file_path)

            workbook = xlsxwriter.Workbook(t.name)

            # changes here for format highlight correct and incorrect

            cell_format1 = workbook.add_format()
            cell_format1.set_pattern(1)  # This is optional when using a solid fill.
            cell_format1.set_bg_color('green')
            cell_format1.set_bold()

            cell_format2 = workbook.add_format()
            cell_format2.set_pattern(1)  # This is optional when using a solid fill.
            cell_format2.set_bg_color('red')
            cell_format2.set_bold()

            worksheet = workbook.add_worksheet()
            with open(csvfile, 'rt', encoding='utf8') as f:
                reader = csv.reader(f, delimiter="\t")
                for r, row in enumerate(reader):
                    for c, col in enumerate(row):
                        if col == "correct":
                            worksheet.write(r, c, col, cell_format1)
                        elif col == "incorrect":
                            worksheet.write(r, c, col, cell_format2)
                        else:
                            worksheet.write(r, c, col)

            workbook.close()
            t.close()
            os.system(file_path)

        def start_progress():

            # Initializing busy state for cursor
            root.config(cursor="wait")
            self.button1.config(state=DISABLED)
            self.button2.config(state=DISABLED)
            root.update()

            # start the correct backend pipeline
            if self.combobox.get() == 'English':
                showinfo(
                    title="Information",
                    message="Generating grade suggestions for English student answers. This may take a little while.")
                # run English backend
                english_backend()
            elif self.combobox.get() == 'German':
                showinfo(
                    title="Information",
                    message="Generating grade suggestions for German student answers. This may take a little while.")
                # run German/multilingual backend
                german_backend()

            self.button1.config(state=NORMAL)
            self.button2.config(state=NORMAL)
            root.update()
            root.config(cursor="")
            # Evaluation window
            open_new_window()

        self.button2 = ttk.Button(self.widgets_frame, text="Input file", command=import_csv_data, state=DISABLED)
        self.button2.grid(row=9, column=0, padx=5, pady=10, sticky="nsew")

        # select language, "Choose language" as default
        self.combobox = ttk.Combobox(
            self.widgets_frame, values=self.combo_list)
        self.combobox.current(0)
        self.combobox.grid(row=5, column=0, padx=5, pady=10, sticky="ew")

        # set state for button2("Input"-button) and if 'Spanish' is chosen in the combobox disable both buttons
        def set_buttons_state(event):
            self.button2.config(state="normal")
            # print('State changed')
            if self.combobox.get() == 'Spanish':
                showwarning(title="Information", message="Not available")
                self.button1.config(state="disabled")
                self.button2.config(state="disabled")

        # get events from changing combobox
        self.combobox.bind('<<ComboboxSelected>>', set_buttons_state)

        self.button1 = ttk.Button(self.widgets_frame, text="Start",
                                  command=start_progress,
                                  state=tk.DISABLED)
        self.button1.grid(row=12, column=0, padx=1, pady=5, sticky="nsew")


def resource_path(relative_path):
    if getattr(sys, 'frozen', False):
        # running in a bundle
        bundle_dir = sys._MEIPASS
    else:
        bundle_dir = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(bundle_dir, relative_path)


# Override stdout and stderr with NullWriter in GUI --noconsole mode
# This allows us to avoid a bug where tqdm try to write on NoneType
# https://github.com/tqdm/tqdm/issues/794
class NullWriter:
    def write(self, data):
        pass


if __name__ == "__main__":

    # Override stdout and stderr with NullWriter in GUI --noconsole mode
    # This allows us to avoid a bug where tqdm try to write on NoneType
    # https://github.com/tqdm/tqdm/issues/794
    if sys.stdout is None:
        sys.stdout = NullWriter()

    if sys.stderr is None:
        sys.stderr = NullWriter()

    root = tk.Tk()
    root.title("ASYST")

    # Set the theme

    root.tk.call("source", resource_path("azure.tcl"))
    root.tk.call("set_theme", "light")

    app = App(root)
    app.pack(fill="both", expand=True)

    root.update()
    root.geometry("850x600")

    root.iconbitmap(resource_path("icon.ico"))

    # stop the program completely upon closing the window
    root.protocol("WM_DELETE_WINDOW", root.destroy)

    root.mainloop()