-
Notifications
You must be signed in to change notification settings - Fork 0
/
ARTI_GUI.py
602 lines (510 loc) · 24.9 KB
/
ARTI_GUI.py
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
from tkinter import *
from tkinter import ttk, scrolledtext, messagebox
from tkinter import filedialog as fd
from tkinter.filedialog import asksaveasfile
import os
import sys
# ARTI needs Python three
# as much as you need... me ;)
# Time's computation function was selected after evaluating the following articles' infos:
# https://kodify.net/hugo/strings/reading-time-text/
# https://qualcherisposta.it/quante-parole-si-pronunciano-un-minuto
# last update: 2022/19/01
class Installation:
"""
Manages the installation GUI.
If it is the first execution OR the user doesn't dispose of the needed libs
asks him if he wants to download them, in which case the program proceeds
with the installation. Else, he can easly close the window.
"""
def __init__(self):
# ------------------------------- Termination variable. Default = False; if True wont open App.
self.__termination__ = False
# ------------------------------- Installation root creation
self.__installation_root__ = Tk()
width = self.__installation_root__.winfo_screenwidth()
if width<1680:
self.__installation_root__.tk.call("tk", "scaling", 1)
if width>2000:
self.__installation_root__.tk.call("tk", "scaling", 1.5)
self.__installation_root__.update()
# path logo
logo = __get_path__("utils\\images\\aRTi_white_giant.png")
# -----------------logo
self.__logo__ = PhotoImage(file=logo)
# path logo
logo_min = __get_path__("utils\\images\\aRTi_medium.png")
# -----------------logo minimized
self.__mini_logo__ = PhotoImage(file=logo_min)
# path ico
ico = __get_path__("utils\\images\\aRTi_white_giant_ico.ico")
#-----------------ico
self.__ico__ = ico
#set root icon
self.__set_ico__()
#set root title
self.__title__ = "Program Installation"
self.__set_title__(self.__title__)
#---------------------------------- Master installation frame creation
self.__master_frame__ = Frame(self.__installation_root__)
self.__master_frame__.grid(row=0, column =0)
#---------------------------------- Dialog Frame creation
self.__up_dialog_frame__ = Frame(self.__master_frame__)
self.__up_dialog_frame__.grid(row=0, sticky= W, padx=(5))
#---------------------------------- Image installation lbl
self.__image_lbl__ = Label(self.__up_dialog_frame__, image = self.__mini_logo__, justify="center")
self.__image_lbl__.grid(row=0, column=0, padx=(10), pady=10)
#---------------------------------- Welcome installation Frame creation
self.__welcome_frame__ = Frame(self.__up_dialog_frame__)
self.__welcome_frame__.grid(row=0, column =1, sticky=W, padx=(5))
#---------------------------------- Welcome installation lbl
self.__welcome_lbl__ = Label(self.__welcome_frame__, text='Welcome to aRTi!', font=("Berlin Sans FB Demi", 30, "bold"), justify="left")
self.__welcome_lbl__.grid(row=0, column = 1, sticky =N + W, pady=5)
#---------------------------------- Instruction installation lbl
self.__instruction_lbl__ = Label(self.__welcome_frame__, justify ="left", text='Since it is the first execution of the program you need to download \nand install the following libraries in order to correctly run aRTi.\n\nPlease make sure that your device has network connectivity.', font=("Times New Roman", 12))
self.__instruction_lbl__.grid(row=1, column = 1, sticky =N + W, pady=10)
# ---------------------------------------------------- TEXTBOX Frame
self.__box_frame__ = LabelFrame(self.__master_frame__, text="The following packages will be installed:", padx=5, pady=5)
self.__box_frame__.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky=E + W + N + S)
self.__installation_root__.columnconfigure(0, weight=1)
self.__installation_root__.rowconfigure(1, weight=1)
self.__box_frame__.rowconfigure(0, weight=1)
self.__box_frame__.columnconfigure(0, weight=1)
# Create the textbox widget
self.__txt_box__ = scrolledtext.ScrolledText(self.__box_frame__, width=40, height=10, font=("Times New Roman", 12))
self.__txt_box__.grid(row=0, column=0, sticky=E + W + N + S)
self.__txt_box__.insert(INSERT, self.__get_packages__())
self.__txt_box__.configure(state="disabled")
#-----------------------------------------------Accept frame creation
self.__accept_frame__ = Frame(self.__master_frame__)
self.__accept_frame__.grid(row=2, padx=(10), pady=10, sticky = W)
#accept installation boolean variable
self.__accept_terms__ = BooleanVar()
# check button
self.__check_btn__ = Checkbutton(self.__accept_frame__, text="I accept to download and install the previous packages. Click the 'Next' button to continue", variable=self.__accept_terms__, onvalue=True, offvalue=False, command = self.__manage_next_btn__)
self.__check_btn__.grid(row = 0, sticky = W)
#next button
self.__next_btn__ = Button(self.__accept_frame__, text='Next', state = DISABLED, width=10, command = self.__bar__)
self.__next_btn__.grid(row=2, sticky=E + S, pady=10)
#termination program variable
terminate = BooleanVar()
#progress bar
self.__progress__ = ttk.Progressbar(self.__accept_frame__, orient=HORIZONTAL, length=600, mode ="determinate")
self.__progress__.grid(row=1, sticky = W)
#defines min and max root dimension
self.__installation_root__.update()
self.__installation_root__.minsize(self.__installation_root__.winfo_width(), self.__installation_root__.winfo_height())
self.__installation_root__.maxsize(self.__installation_root__.winfo_width(), self.__installation_root__.winfo_height())
#terminate installation, open app
self.__installation_root__.mainloop()
def get_terimantion(self):
"""
Returns the termination variable
:return:
the termination variable = True if libs were correctly installed
"""
return self.__termination__
def __set_ico__(self):
"""
Sets the icon of the installation root
:return:
"""
self.__installation_root__.iconbitmap(self.__ico__)
self.__installation_root__.wm_iconphoto(True, self.__logo__)
def __set_title__(self, title):
"""
Sets installation root title
:param title: string which contains installation root title
:return:
"""
self.__installation_root__.title(title)
def __get_packages__(self):
"""
Puts into a string all of the libraries required to correctly run aRTi.
Libraries names and versions are taken from the requirements.txt file.
The test is in the form:
pack = "lib_1==#version_1\nlib_2==#version_2\n[...]\nlib_n==version_n\n"
:return:
A string containing all the Packages required for the installation of aRTi
"""
pack = "\n"
with open("requirements.txt", 'r') as f:
for line in f:
pack = pack + line + "\n"
return pack
def __manage_next_btn__(self):
"""
Enables and Disables the next button in the installation root.
If the checkbox value, accept_terms, is set to True the next button is activated.
:return:
"""
self.__next_btn__.configure(state="disabled" if not self.__accept_terms__.get() else "normal")
def __install_libs__(self):
"""
Download and installs required libraries from requirement.txt file
:return:
"""
import sys
import subprocess
# implement pip as a subprocess:
subprocess.run(["pip3", "install", "-r", "requirements.txt"], shell=True, capture_output=True)
def __import_packs__(self):
"""
Imports needed packages while managing the progress bar
:return:
"""
self.__installation_root__.update_idletasks()
import os.path
self.__progress__["value"] = 76
self.__installation_root__.update_idletasks()
import PyPDF2
self.__progress__["value"] = 87
self.__installation_root__.update_idletasks()
import docx
self.__progress__["value"] = 100
self.__installation_root__.update_idletasks()
def __disable_widgets__(self):
"""
Disables check_btn and next_btn.
:return:
"""
self.__check_btn__.configure(state=DISABLED)
self.__next_btn__.configure(state=DISABLED)
def __bar__(self):
"""
Manages the progress bar while installing the required processes and importing
required packages.
Destroys installation root after installation.
:return:
"""
# disable checkbox and next buttons
self.__disable_widgets__()
# download and install packages
self.__progress__["value"] = 5
self.__installation_root__.update_idletasks()
self.__install_libs__()
self.__progress__["value"] = 55
self.__import_packs__()
self.__termination__ = True
#destroy the installation root
self.__installation_root__.destroy()
class App:
"""
Defines the aRTi GUI.
Pressing the "Select File" button the user can simply choose the desired file that has one of the following extentions:
- .pdf
- .docx
- .txt
Pressing the "Start" button, the program will compute the reading time of the doc.
The game is done.
"""
def __init__(self):
# ------------------------------- Installation root creation
self.__root__ = Tk()
width = self.__root__.winfo_screenwidth()
if width<1680:
self.__root__.tk.call("tk", "scaling", 1)
if width>2000:
self.__root__.tk.call("tk", "scaling", 1.5)
self.__root__.update()
self.__root__.configure(background="white")
# path logo
logo = __get_path__("utils\\images\\aRTi_white_giant.png")
# -----------------logo
self.__logo__ = PhotoImage(file=logo)
# path logo
logo_min = __get_path__("utils\\images\\aRTi_200.png")
# -----------------logo minimized
self.__mini_logo__ = PhotoImage(file=logo_min)
# path ico
ico = __get_path__("utils\\images\\aRTi_white_giant_ico.ico")
#-----------------ico
self.__ico__ = ico
#set root icon
self.__set_ico__()
#set root title
self.__title__ = "aRTi"
self.__set_title__(self.__title__)
#---------------------------------- Master frame creation
self.__master_frame__ = Frame(self.__root__, background="white")#F6ECEC
self.__master_frame__.grid(row=0, sticky=W+N)
#---------------------------------- Dialog Frame creation
self.__up_dialog_frame__ = Frame(self.__master_frame__, background="white")
self.__up_dialog_frame__.grid(padx=(10), pady=10, sticky=W+N)
#---------------------------------- Image lbl
self.__image_lbl__ = Label(self.__up_dialog_frame__, image = self.__mini_logo__, background="white")
self.__image_lbl__.grid(row=1, column = 0, padx=(10), sticky = N)
#---------------------------------- clolorusso label
self.__clo_lbl__ = Label(self.__up_dialog_frame__, text =" by clolorusso\n\n\n\n", background="white",font=("Bahnschrift Light",10))
self.__clo_lbl__.grid(row=2, column = 0, sticky = N)
self.__right_frame__ = Frame(self.__master_frame__, borderwidth = 2,background="#F8FAFC")
self.__right_frame__.grid(row=0, column=1, sticky=W, padx=(10), pady=10)
#---------------------------------- Instruction Frame creation
self.__instruction_frame__ = Frame(self.__right_frame__, borderwidth = 2,background="#F8FAFC")
self.__instruction_frame__.grid(row=0, column = 0, sticky=W, padx=(10), pady=10)
#---------------------------------- Instruction lbl
title_arti = "_____ aR"+u'\u231B' +"Ti _____"
# path logo
arti_line = __get_path__("utils\\images\\aRTi_lines_700x58.png")
# -----------------logo minimized
self.__arti_line__ = PhotoImage(file=arti_line)
Label(self.__instruction_frame__, justify ="left", image = self.__arti_line__,text=title_arti, font=("Berlin Sans FB Demi", 60, "bold"), background="#F8FAFC").grid(row=0, column = 0, sticky=W)
instructions = "Howdy Guys!!!\n\nSeems like you're in a desperate need for help or else " \
"you'd have never downloaded \nand installed a program retrieved from a " \
"remote corner of GitHub...\n\nAnyway, aRTi is here to HELP YOU!!\n\n" \
"Are you interested in discovering the READING TIME of your speech or a book?\n" \
"You just have to select the doc ('.txt', '.docx' or '.pdf' only) by clicking the " \
"'Select File' \nbutton. Afterwards, press 'Start' and the game is done."
Label(self.__instruction_frame__, justify ="left", text=instructions, font=("Bahnschrift Light", 12), background="#F8FAFC").grid(row=1, column = 0, sticky = W)
# Perfomed lbl
Label(self.__instruction_frame__,text="Instructions:", background="#F6FBFF",font=("Berlin Sans FB Demi",16), justify="left").grid(row=2, column=0, pady = 10, sticky = W)
self.__filename__ = StringVar()
# Perfomed lbl
self.__perf_txt__ = Label(self.__instruction_frame__,text="Press 'Select File' button and choose your file.", background="#F6FBFF",font=("Bahnschrift Light",12), justify="left")
self.__perf_txt__.grid(row=3, column=0, pady = 5, sticky = W)
#-----------------------------------------------File name frame creation
self.__fname_frame__ = Frame(self.__up_dialog_frame__, padx=5, pady=5, relief = GROOVE, background="white")
self.__fname_frame__.grid(row=0, column = 0, padx=(10), sticky = S)
#EMPTY
#Label(self.__fname_frame__,text="", background="white",font=("Bahnschrift Light",10), justify="center").grid(row=0, column=0, sticky = S, pady = 60)
# Compute your
Label(self.__fname_frame__,text="\n\nCompute your", background="white",font=("Berlin Sans FB Demi",12, "bold"), justify="center").grid(row=0, column=0, sticky = S)
#Reading Time txt label
self.__RT_txt__ = Label(self.__fname_frame__,text="Reading Time", background="white",font=("Berlin Sans FB Demi", 30, "bold"), justify="center")
self.__RT_txt__.grid(row=1, column=0, sticky = S)
#file name string
# with
Label(self.__fname_frame__,text="with\n\n\n", background="white",font=("Berlin Sans FB Demi",12, "bold"), justify="center").grid(row=2, column=0, sticky = S)
#EMPTY
#Label(self.__fname_frame__,text="", background="white",font=("Bahnschrift Light",10), justify="center").grid(row=5, column=0, sticky = S, pady = 5)
#-----------------------------------------------Computation frame creation
self.__computation_frame__ = LabelFrame(self.__up_dialog_frame__,text="\n Make your choice: ", padx=5, pady=5, borderwidth = 0.4, relief = GROOVE, background="#F6FBFF",font=("Berlin Sans FB Demi",12, "bold"))
self.__computation_frame__.grid(row=3, column = 0, padx=(10), pady=5, sticky = S)
#reading time value
self.__reading_time__ = StringVar()
button_color = "#E1F3FF"
#Select file button
self.__select_btn__ = Button(self.__computation_frame__, text ="Select File", height = 2, width=15,command = self.__select_file__, background=button_color,borderwidth=1, relief = SUNKEN,cursor="hand2",font=("Bahnschrift Light",10))
self.__select_btn__.grid(row=0, column = 0, padx=10,pady=10, sticky = E+N+S)
# start button
self.__start_btn__ = Button(self.__computation_frame__, text ="Start", state = DISABLED, height = 2, width=15, command = self.__compute__, background=button_color,borderwidth=1, relief = SUNKEN,cursor="arrow",font=("Bahnschrift Light",10))
self.__start_btn__.grid(row=0, column = 1, padx=10,pady=10, sticky=W+N+S)
# ---------------------------------------------------- TEXTBOX Frame
self.__box_frame__ = LabelFrame(self.__right_frame__, text=" Reading time is:", padx=5, pady=5, borderwidth=0.4,background="#F6FBFF",font=("Berlin Sans FB Demi",12))
self.__box_frame__.grid(row=1, column=0, columnspan=3, padx=10, pady=10, sticky=E + W + N + S)
self.__root__.columnconfigure(0, weight=1)
self.__root__.rowconfigure(1, weight=1)
self.__box_frame__.rowconfigure(0, weight=1)
self.__box_frame__.columnconfigure(0, weight=1)
# Create the textbox widget
self.__txt_box__ = Text(self.__box_frame__, width=40, height=10, font=("Bahnschrift Light", 12), state = DISABLED, cursor = "arrow")
self.__txt_box__.grid(row=0, column=0, sticky=E + W + N + S)
#defines min and max root dimension
self.__root__.update()
self.__root__.minsize(self.__root__.winfo_width(), self.__root__.winfo_height())
self.__root__.mainloop()
def __compute__(self):
"""
Computes reading time
:return:
"""
self.__txt_box__.configure(state=NORMAL)
self.__txt_box__.delete("1.0", END)
self.__txt_box__.configure(state="disabled")
if not self.__file_name__ == "":
path = self.__file_name__
warning = False
minutes, secs, warning = self.__compute_time__(path)
# get file name from path
file_name = os.path.basename(path)
if warning:
pass
elif not (minutes == 0 and secs == 0):
#get string containing reading time
self.__reading_time__ = "Reading time for " +file_name+" is:\n\n" + str(minutes) + " minutes and " + str(secs) + " seconds.\n\nPlease select another file for a new computation."
self.__txt_box__.configure(state=NORMAL)
self.__txt_box__.insert(INSERT, self.__reading_time__)
self.__txt_box__.configure(state="disabled")
else:
messagebox.showinfo("Info!", file_name +
" outputted 0 minutes and 0 seconds.\nReasons maybe one of the following:"
"\n-\tthe file is empty;"
"\n-\tthe file contains only images;"
"\n-\tthe file is corrupted."
"\n\nSelect another file for a new computation.")
self.__start_btn__.configure(state="disabled", cursor="arrow")
self.__perf_txt__.config(text= "Press 'Select File' button and choose your file for a new computation.")
def __select_file__(self):
"""
Let the user select a file. The file type must be one of the allowed ones (see self.__filetypes__ function).
Enables and disables start button.
:return:
"""
self.__file_name__ = fd.askopenfilename(
title = "Select File",
initialdir="\\",
filetypes = self.__filetypes__()
)
#Enables and disables start button
self.__start_btn__.configure(state = NORMAL if not self.__file_name__ == "" else DISABLED, cursor="hand2" if not self.__file_name__ == "" else "arrow")
file_name = os.path.basename(self.__file_name__)
#specify doc selected
doc_select_rd_txt = "Reading time will be computed for\n" + file_name + "\n\nPress 'Start' to continue"
self.__perf_txt__.config(text = doc_select_rd_txt if not file_name == "" else "Press 'Select File' button and choose your file.")
def __filetypes__(self):
"""
Returns all of the filetypes allowed
:return:
tuple of all of the filetypes allowed
"""
filetypes = (
("*.pdf", "*.pdf"),
("*.txt", "*.txt"),
("*.docx", "*.docx")
)
return filetypes
def __set_ico__(self):
"""
Sets the icon of the installation root
:return:
"""
self.__root__.iconbitmap(self.__ico__)
self.__root__.wm_iconphoto(True, self.__logo__)
def __set_title__(self, title):
"""
Sets installation root title
:param title: string which contains installation root title
:return:
"""
self.__root__.title(title)
#app methods
def __getWordNumbTxt__(self, path):
"""
Computates the total of words in the TXT.
:param path: path of the file
:return:
number_of_words: total of words in the doc.
"""
with open(path, 'r', encoding='utf-8', errors="ignore") as inF:
number_of_words = 0
for line in inF:
word_list = line.split()
number_of_words += len(word_list)
return number_of_words
def __getWordNumbDocx__(self, path):
"""
Computates the total of words in the DOCX.
:param path: path of the file
:return:
number_of_words: total of words in the doc.
"""
doc = docx.Document(path)
number_of_words = 0
for para in doc.paragraphs:
txt = para.text
word_list = txt.split()
number_of_words += len(word_list)
return number_of_words
def __getWordNumbPDF__(self, path):
"""
Computates the total of words in the PDF.
:param path: path of the file
:return:
number_of_words: total of words in the doc.
"""
import PyPDF2
# creating an object
file = open(path, 'rb')
# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file,strict=False)
number_of_words = 0
for page in fileReader.pages:
for line in page.extractText().splitlines():
word_list = line.split()
number_of_words += len(word_list)
file.close()
return number_of_words
def __get_number_of_words__(self, path):
"""
Calls the method to computate the total number of words
:param path: path of the file
:return:
number_of_words: total number of words in the doc
"""
number_of_words = 0
warning = False
try:
if path.endswith(".txt"):
number_of_words = self.__getWordNumbTxt__(path)
elif path.endswith(".docx"):
number_of_words = self.__getWordNumbDocx__(path)
elif path.endswith(".pdf"):
number_of_words = self.__getWordNumbPDF__(path)
except Exception as e:
warning = True
messagebox.showwarning("Warning", "The file you selected maybe protected by password.\nPlease select another file.")
return number_of_words, warning
def __compute_time__(self, path):
"""
Computes reading time.
:param path: file's path
:return:
minutes: minutes of reading
secs: seconds of reading
"""
minutes = 0
secs = 0
number_of_words, warning = self.__get_number_of_words__(path)
if not warning:
# 200 = average number of words that can be read in a minute
dvd = number_of_words / 200
minutes = self.__compute_minutes__(dvd)
secs = self.__compute_seconds__(dvd)
return minutes, secs, warning
def __compute_minutes__(self, dvd):
"""
Computes minutes
:param dvd: number of words divided by the avg number of words tha can be read in a minute
:return: minutes of reading
"""
return round(dvd)
def __compute_seconds__(self, dvd):
"""
Computes seconds
:param dvd: number of words divided by the avg number of words tha can be read in a minute
:return: seconds of reading
"""
secs = round((dvd * 60) % 1, 3)
return int(str(secs)[2:])
def __get_path__(relative_path):
"""
if (hasattr(sys, "_MEIPASS")):
return os.path.join(sys._MEIPASS, relative_path)
else:
return relative_path
"""
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
if __name__ == '__main__':
# use this for CLI execution
# to export exe comment this and
# delete comment from bottom code
termination = False
try:
import os.path
import PyPDF2
import docx
termination = True
except ModuleNotFoundError:
install = Installation()
termination = install.get_terimantion()
if termination:
app = App()
"""
# Pyinstaller needs only this
app = App()
"""