-
Notifications
You must be signed in to change notification settings - Fork 0
/
Main_Script.py
841 lines (743 loc) · 41.1 KB
/
Main_Script.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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# WARNING! The Cronofy Calendar Integration will NOT work as it stands, until you set a proper ID/ access token,
# so don't freak out if it doesn't work
import datetime, random, string, platform, pytz
from json import load, dump
from PyQt5 import QtCore, QtGui, QtWidgets
from pycronofy import *
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.sqlalchemy import SQLAlchemyJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
crono_cal = Client(access_token="Fill in here")
cal_id = 'Fill in your main calendar, or a list of your calendars, here'
jobstores = {
'default': SQLAlchemyJobStore(url='sqlite:///jobs.sqlite')
}
executors = {
'default': ThreadPoolExecutor(20),
'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
'coalesce': False,
'max_instances': 3
}
scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=pytz.utc)
scheduler.start()
listofsubjects = ["English", "Math", "Languages",
"Business", "Economics", "Geography", "History", "Psychology",
"Biology", "Chemistry", "Physics", "Computers", "Sports Science",
"Film", "Music", "Theatre", "Art"]
subjectgroups = {'english': ["English"],
'math': ["Math"],
'foreignlanguage': ["Languages"],
'humanities': ["Business", "Economics", "Geography", "History", "Psychology"],
'sciences': ["Biology", "Chemistry", "Physics", "Computers", "Sports Science"],
'extras': ["Film", "Music", "Theatre", "Art"]}
# Colour coding lookup table
colour_dict = {
'english': '#66b3ff', # Blue
'math': '#9999ff', # Light purple
'foreignlanguage': '#e3cd4f', # Yellow
'sciences': '#91bc8f', # Green
'humanities': '#fc9b1d', # Orange
'extras': '#ff8084', # Red
}
cal_id = 'Fill in your main calendar, or a list of your calendars, here'
def daysBetween(date2):
one_day = 1000 * 60 * 60 * 24
date1_ms = datetime.datetime.now().date()
date2_ms = date2
difference_delta = date2_ms - date1_ms # returns a timedelta object
difference_ms = difference_delta.total_seconds() * 1000
return round(difference_ms / one_day)
def datefromiso(datestring):
return datestring.split('T', 1)[0]
def randomiser_for_ids():
numbers = [str(i) for i in range(0, 10)]
ASCII = list(string.ascii_letters) + numbers * 2
random_id = [random.choice(ASCII) for i in range(0, 10)]
return ''.join(random_id)
def writetoJSON(dictobj, file='memory.json', ):
with open(file, mode='r+') as memory:
s = memory.read().replace(']', '')
memory.seek(0)
memory.truncate()
memory.write(s)
# Leaves an unclosed parentheses
with open(file, mode="a") as memory:
memory.write(', \n')
dump(dictobj, memory, indent=3)
memory.write(']')
# Closes that parentheses
def stylehandler(self):
with open('theme.json', mode='r') as memory:
s = load(memory)
if s["darktheme"]:
self.setdarktheme()
theme = '''{"darktheme":true}'''
else:
self.setlighttheme()
theme = '''{"darktheme":false}'''
def setdarktheme(self):
with open('dark.qss', 'r') as theme:
self.MainWindow.setStyleSheet(theme.read())
def setlighttheme(self):
with open('light.qss', 'r') as theme:
self.MainWindow.setStyleSheet(theme.read())
if platform.system == "Linux":
import notify2
notify2.init('App Name')
def notification(title, text, icon=None):
n = notify2.Notification(title, text, icon)
if platform.system == "Windows":
from win10toast import ToastNotifier
toaster = ToastNotifier()
def notification(title, text, icon=None):
toaster.show_toast(title, text, icon_path=icon, threaded=True)
if platform.system() == "Darwin":
import applescript
def notification(title, text, icon=None):
command = 'display notification ' + '\"' + text + '\"'
applescript.run(command, background=True)
def create_session(session, cronosession):
print(session, cronosession)
class Ui_MainWindow(QtWidgets.QMainWindow): # Most of this is autogenerated UI setup
def __init__(self, MainWindow, parent=None):
super(QtWidgets.QMainWindow, self).__init__(parent)
MainWindow.setObjectName("MainWindow")
MainWindow.resize(656, 581)
self.MainWindow = MainWindow
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.verticalLayoutWidget = QtWidgets.QWidget(self.centralWidget)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(9, 10, 271, 435))
self.verticalLayoutWidget.setObjectName("verticalLayoutWidget")
self.verticalLayout = QtWidgets.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setSizeConstraint(QtWidgets.QLayout.SetMinAndMaxSize)
self.verticalLayout.setContentsMargins(11, 11, 11, 11)
self.verticalLayout.setSpacing(6)
self.verticalLayout.setObjectName("verticalLayout")
self.todaybutton = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.todaybutton.setMinimumSize(QtCore.QSize(0, 0))
self.todaybutton.setMaximumSize(QtCore.QSize(16777215, 50))
self.todaybutton.setObjectName("todaybutton")
self.verticalLayout.addWidget(self.todaybutton)
self.weekbutton = QtWidgets.QPushButton(self.verticalLayoutWidget)
self.weekbutton.setMinimumSize(QtCore.QSize(0, 0))
self.weekbutton.setMaximumSize(QtCore.QSize(16777215, 50))
self.weekbutton.setObjectName("weekbutton")
self.verticalLayout.addWidget(self.weekbutton)
self.eventlist = QtWidgets.QListWidget(self.verticalLayoutWidget)
self.eventlist.setMaximumSize(QtCore.QSize(16777215, 270))
self.eventlist.setWordWrap(True)
self.eventlist.setObjectName("eventlist")
item = QtWidgets.QListWidgetItem()
font = QtGui.QFont()
font.setPointSize(15)
font.setBold(True)
font.setItalic(True)
font.setWeight(75)
item.setFont(font)
self.eventlist.addItem(item)
self.verticalLayout.addWidget(self.eventlist)
self.calendarbutton = QtWidgets.QPushButton(self.verticalLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.calendarbutton.sizePolicy().hasHeightForWidth())
self.calendarbutton.setSizePolicy(sizePolicy)
self.calendarbutton.setMinimumSize(QtCore.QSize(0, 45))
self.calendarbutton.setObjectName("calendarbutton")
self.verticalLayout.addWidget(self.calendarbutton)
self.newexambutton = QtWidgets.QPushButton(self.centralWidget)
self.newexambutton.setGeometry(QtCore.QRect(480, 20, 161, 31))
self.newexambutton.setMaximumSize(QtCore.QSize(200, 16777215))
self.newexambutton.setObjectName("newexambutton")
self.label_4 = QtWidgets.QLabel(self.centralWidget)
self.label_4.setGeometry(QtCore.QRect(320, 30, 91, 51))
self.label_4.setTextFormat(QtCore.Qt.RichText)
self.label_4.setObjectName("label_4")
self.gridlayout = QtWidgets.QWidget(self.centralWidget)
self.gridlayout.setGeometry(QtCore.QRect(290, 80, 361, 361))
self.gridlayout.setObjectName("gridlayout")
self.gridLayout = QtWidgets.QGridLayout(self.gridlayout)
self.gridLayout.setContentsMargins(11, 11, 11, 11)
self.gridLayout.setSpacing(6)
self.gridLayout.setObjectName("gridLayout")
self.changemodebutton = QtWidgets.QPushButton(self.centralWidget)
self.changemodebutton.setGeometry(475, 450, 165, 40)
self.changemodebutton.setText("Change Color Scheme")
self.newsessionbutton = QtWidgets.QPushButton(self.centralWidget)
self.newsessionbutton.setGeometry(QtCore.QRect(478, 70, 161, 31))
self.newsessionbutton.setMaximumSize(QtCore.QSize(200, 16777215))
self.newsessionbutton.setObjectName("newsessionbutton")
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 656, 22))
self.menuBar.setObjectName("menuBar")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
# Function calls and connections
self.todaybutton.clicked.connect(lambda: self.displaycheckboxestoday('memory.json'))
self.weekbutton.clicked.connect((lambda: self.displaycheckboxesweek('memory.json')))
self.newsessionbutton.clicked.connect(lambda: self.createsessionform())
self.changemodebutton.clicked.connect(lambda: self.changetheme())
self.newexambutton.clicked.connect(lambda: self.createform())
self.calendarbutton.clicked.connect(lambda: self.showcalendar())
QtCore.QMetaObject.connectSlotsByName(MainWindow)
with open('theme.json', 'a'):
''
with open('memory.json', 'a'):
''
# Initialise the files, to avoid potential name errors or file not found errors
with open('theme.json', mode='r') as memory:
s = load(memory)
try:
if s["darktheme"]:
self.setdarktheme()
theme = '''{"darktheme":true}'''
else:
self.setlighttheme()
theme = '''{"darktheme":false}'''
except FileNotFoundError or FileExistsError:
self.setlighttheme()
theme = '''{"darktheme":true}'''
with open('theme.json', mode='w') as memory:
memory.write(theme)
# Reads the theme, and sets accordingly
self.retranslateUi(MainWindow)
self.listfrommemory('memory.json')
self.displaycheckboxestoday('memory.json')
def retranslateUi(self, MainWindow): # Again, mostly auto-generated
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.todaybutton.setAccessibleName(_translate("MainWindow", "todaybutton"))
self.todaybutton.setText(_translate("MainWindow", "Today"))
self.weekbutton.setAccessibleName(_translate("MainWindow", "weekbutton"))
self.weekbutton.setText(_translate("MainWindow", "Next 7 Days"))
self.eventlist.setAccessibleName(_translate("MainWindow", "eventlist"))
__sortingEnabled = self.eventlist.isSortingEnabled()
self.eventlist.setSortingEnabled(False)
item = self.eventlist.item(0)
item.setText(_translate("MainWindow", "All Deadlines"))
self.eventlist.setSortingEnabled(__sortingEnabled)
self.calendarbutton.setAccessibleName(_translate("MainWindow", "calendarbutton"))
self.calendarbutton.setText(_translate("MainWindow", "View in Calendar"))
self.newexambutton.setAccessibleName(_translate("MainWindow", "newexambutton"))
self.newexambutton.setText(_translate("MainWindow", "New Exam"))
self.label_4.setText(_translate("MainWindow",
"<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; font-style:italic;\">Today</span></p></body></html>"))
self.newsessionbutton.setAccessibleName(_translate("MainWindow", "newsessionbutton"))
self.newsessionbutton.setText(_translate("MainWindow", "New Session"))
def listfrommemory(self, memfile='memory.json'): # Read events from memory, and create the list of deadlines
# Requires a highly specific data structure.
with open(memfile, 'r') as memory:
date_today = datetime.datetime.now().date().isoformat()
acceptable_args = ['deadline', 'exam', 'project', 'other'] # All things which are not sessions
deadlines = [thing for thing in load(memory) if
thing['type'].lower() in acceptable_args] # If thing is a deadline/project/whatever
upcoming_deadlines = [thing for thing in deadlines if thing['deadline'] >= date_today]
upcoming_deadlines = sorted(upcoming_deadlines, key=lambda k: k['deadline']) # Sorts by date
for thing in upcoming_deadlines:
x = thing['name'].upper()
y = '[' + thing['subject'] + ']:' # For visual/style reasons
z = thing['deadline'].split('T', 1)[0] # removes the time portion of datetime string
item = QtWidgets.QListWidgetItem(x + y + z)
for key, value in subjectgroups.items(): # This block colour codes the session appropriately.
# Probably not the most elegant code in the world, but it works
if thing['subject'] in value:
item.setBackground(QtGui.QColor(colour_dict[key]))
break
self.eventlist.addItem(item)
linebreak = QtWidgets.QListWidgetItem('')
self.eventlist.addItem(linebreak)
# Just for aesthetic reasons, leave linebreaks in
def displaycheckboxestoday(self, memory): # Displays 'TO-DO' articles for the day based on the memory file
for i in reversed(range(self.gridLayout.count())):
self.gridLayout.itemAt(i).widget().setParent(None)
boxnumber = 0 # Specifies the position/index
date_today = datetime.datetime.now().date() # Returns today's date in ISO format(date only)
date_today = str(date_today)
self.label_4.setText(
"<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; font-style:italic;\">Today</span></p></body></html>")
with open(memory, 'r') as jsonmem:
# Get all today's events using iso date handling
sessions = [item for item in load(jsonmem) if item['type'].lower() == 'session']
today_sessions = [item for item in sessions if datefromiso(item['start_time']) == date_today]
today_sessions = sorted(today_sessions, key=lambda k: k['start_time'])
for item in today_sessions:
self.eventcheckbox = QtWidgets.QCheckBox(self.gridlayout)
self.eventcheckbox.setText(item['description'])
for key, value in subjectgroups.items(): # Colour codes the session appropriately.
if item['subject'] in value:
self.eventcheckbox.setStyleSheet("background-color:" + colour_dict[key] + '; \n')
break
self.gridLayout.addWidget(self.eventcheckbox, boxnumber, 0, 1, 1)
boxnumber += 1
def displaycheckboxesweek(self, memory): # Displays 'TO-DO' articles for the next 7 days
for i in reversed(range(self.gridLayout.count())):
self.gridLayout.itemAt(i).widget().setParent(None)
boxnumber = 0
date_today = datetime.datetime.now().date() # Returns today's date in ISO format(date only)
date_today = datefromiso(str(date_today))
weeklater =(datetime.datetime.now() + datetime.timedelta(days=7)).isoformat()
self.label_4.setText(
"<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; font-style:italic;\">This Week</span></p></body></html>")
with open(memory, 'r') as jsonmem:
# Get all this week's events using iso date handling
sessions = [item for item in load(jsonmem) if item['type'].lower() == 'session']
thisweek = [item for item in sessions if
date_today <= datefromiso(item['start_time']) <= datefromiso(weeklater)]
thisweek = sorted(thisweek, key=lambda k: k['start_time'])
for item in thisweek:
self.eventcheckbox = QtWidgets.QCheckBox(self.gridlayout)
self.eventcheckbox.setText(item['description'])
for key, value in subjectgroups.items(): # Colour codes the session appropriately.
if item['subject'] in value:
self.eventcheckbox.setStyleSheet("background-color:" + colour_dict[key] + '; \n')
break
self.gridLayout.addWidget(self.eventcheckbox, boxnumber, 0, 1, 1)
boxnumber += 1
def createform(self):
self.window = QtWidgets.QMainWindow()
self.dialog = FormWindow(self.window)
self.window.show()
def createsessionform(self):
self.window = QtWidgets.QMainWindow()
self.dialog = Sessionform(self.window)
self.window.show()
def showcalendar(self):
self.window = QtWidgets.QDialog()
self.window.setStyleSheet("background-color:black")
self.dialog = Calendar(self.window)
self.window.show()
def setdarktheme(self):
stylesheet = '''
border-width: 2px;
border-radius: 4px;
padding: 2px;
border-style: outset;
border-color:#00FFFF
'''
with open('dark.qss', 'r') as theme:
self.MainWindow.setStyleSheet(theme.read())
self.todaybutton.setStyleSheet(stylesheet)
self.weekbutton.setStyleSheet(stylesheet)
self.eventlist.setStyleSheet(stylesheet)
self.calendarbutton.setStyleSheet(stylesheet)
self.newexambutton.setStyleSheet(stylesheet)
self.newsessionbutton.setStyleSheet(stylesheet)
self.label_4.setStyleSheet("color:cyan;")
self.darktheme = True
self.label_4.setText(
"<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; font-style:italic;\">Today</span></p></body></html>")
def setlighttheme(self):
stylesheet = '''border-style: outset;\n
border-width: 2px;\n
border-radius: 4px;\n
border-color: blue\n
'''
orangestylesheet = '''border-style: outset;\n
border-width: 2px;\n
border-radius: 4px;\n
border-color: darkorange\n
'''
with open('light.qss', 'r') as theme:
self.MainWindow.setStyleSheet(theme.read())
self.todaybutton.setStyleSheet(stylesheet)
self.label_4.setStyleSheet("color:blue;")
self.weekbutton.setStyleSheet(stylesheet)
self.eventlist.setStyleSheet(stylesheet)
self.calendarbutton.setStyleSheet(stylesheet)
self.newexambutton.setStyleSheet(orangestylesheet)
self.newsessionbutton.setStyleSheet(orangestylesheet)
self.darktheme = False
self.label_4.setText(
"<html><head/><body><p><span style=\" font-size:18pt; font-weight:600; font-style:italic;\">Today</span></p></body></html>")
def changetheme(self):
with open('theme.json', mode='r') as memory:
s = load(memory)
if not s["darktheme"]:
self.setdarktheme()
theme = '''{"darktheme":true}'''
else:
self.setlighttheme()
theme = '''{"darktheme":false}'''
with open('theme.json', mode='w') as memory:
memory.write(theme)
def schedule(self, event: dict, wordcount, chaptercount):
self.window.close()
deadline_date = datefromiso(event['deadline'])
days_available = daysBetween(datetime.date.fromisoformat(deadline_date)) # start time is iso string
time_required = wordcount / 250 + chaptercount * 1.5 # 90mins/chapter, and 250 words an hour.
daily_sessions = round(
time_required / days_available) if days_available > 0 else time_required # time required is a plain number of hours
frontloaded_days_int = round(days_available / 2) if days_available > 1 else 1 # number of days
for i in range(1, frontloaded_days_int + 1): # Everything within here repeats once a day
for session in range(5, round(min(2 * 2 * daily_sessions + 9, 18)),
2):
# Creates a new session 30 mins later, this block repeats within a single day TODO: Possibly refine using hours and minutes
self.write_session(datetime.time(hour=session), i, event)
for j in range(frontloaded_days_int, days_available):
for session in range(5, min(3 * daily_sessions + 9, 18), 3): # Caps the number of daily sessions
self.write_session(datetime.time(hour=session), j,event)
def write_session(self, time,
displacement,
memory_dict): # Time refers to the starting time(not date) of the session. Displacement refers to the hours/time before the session
free_time = crono_cal.read_free_busy(from_date=datetime.datetime.now(),
# to_date=datetime.date.fromisoformat('date_of_exam'), This is a method which does it for all days
to_date=datetime.datetime.now() + datetime.timedelta(
days=displacement), automatic_pagination=False)
# Does it only for one day(since we're already iterating through days, this is more convenient)
free_time=free_time.json()['free_busy']
free_times_filtered=[timeblock for timeblock in free_time if timeblock["free_busy_status"] == "free"]
if free_times_filtered: #TODO: refine this test
print('free time filtered exists')
for timeframe in free_times_filtered:
if timeframe['start'] <= time <= timeframe['end'] :
random_id= self.randomiser()
create_session(session=memory_dict,
cronosession={
'event_id':random_id,
'sessionplan': memory_dict['notes'],
'description': 'NA',
'start': time,
'end':(datetime.datetime.fromisoformat(time) + datetime.timedelta(minutes=90)).isoformat,
'reminders': [{"minutes": 10}]
})
# Returns the time 90 mins later, as an iso string
break
precomputed_end =(datetime.time(hour=time.hour + 1, minute=time.minute + 30)).isoformat()
# Ninety minutes later,for duration of session
session_summary = memory_dict['notes'] if memory_dict['notes'] \
else "Study Session " + memory_dict['subject']
constructed_date =(datetime.datetime.now().date() + datetime.timedelta(days=displacement)).isoformat()
eventID = randomiser_for_ids()
# Constructs a date using time and displacement parameters
session = {
'event_id': eventID,
'name': '',
'subject': memory_dict['subject'],
'description': 'Work On ' + "\'" + session_summary + "\'",
'plan': '',
'type': 'session',
'start_time': constructed_date + 'T' + time.isoformat(),
'end_time': constructed_date + 'T' + precomputed_end + 'GST', # Adds 90 minutes
'deadline': None
}
cronosession = {
'event_id': eventID,
'summary': 'Work On ' + "\'" + session_summary + "\'",
'description': "more whatnot",
'start': constructed_date + 'T' + time.isoformat(),
'end': constructed_date + 'T' + precomputed_end,
}
crono_cal.upsert_event(cal_id, cronosession)
writetoJSON(session)
notificationjob = scheduler.add_job(name='notification', func=notification,
args=[session['subject'], session['summary']],
run_date=time.isoformat())
class Sessionform(QtWidgets.QMainWindow):
def __init__(self, MainWindow, parent=None):
super(QtWidgets.QMainWindow, self).__init__(parent)
MainWindow.setObjectName("MainWindow")
MainWindow.resize(394, 472)
self.MainWindow = MainWindow
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.formLayoutWidget = QtWidgets.QWidget(self.centralWidget)
self.formLayoutWidget.setGeometry(QtCore.QRect(0, 0, 391, 431))
self.formLayoutWidget.setObjectName("formLayoutWidget")
self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
self.formLayout.setContentsMargins(11, 11, 11, 11)
self.formLayout.setSpacing(6)
self.formLayout.setObjectName("formLayout")
self.label_2 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_2.setObjectName("label_2")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2)
self.subject_box = QtWidgets.QComboBox(self.formLayoutWidget)
self.subject_box.setObjectName("subject_box")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.subject_box)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSpacing(6)
self.horizontalLayout.setObjectName("horizontalLayout")
self.formLayout.setLayout(2, QtWidgets.QFormLayout.LabelRole, self.horizontalLayout)
self.label_4 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_4.setObjectName("label_4")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_4)
self.dateTimeEdit = QtWidgets.QDateTimeEdit(self.formLayoutWidget)
self.dateTimeEdit.setObjectName("dateTimeEdit")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.dateTimeEdit)
self.label_3 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_3.setObjectName("label_3")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_3)
self.label_5 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_5.setObjectName("label_5")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.label_5)
self.sessionplan = QtWidgets.QPlainTextEdit(self.formLayoutWidget)
self.sessionplan.setObjectName("sessionplan")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.sessionplan)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setSpacing(6)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.pushButton = QtWidgets.QPushButton(self.formLayoutWidget)
self.pushButton.setMaximumSize(QtCore.QSize(200, 16777215))
self.pushButton.setObjectName("pushButton")
self.horizontalLayout_4.addWidget(self.pushButton)
self.formLayout.setLayout(6, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_4)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setSpacing(6)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.formLayout.setLayout(8, QtWidgets.QFormLayout.LabelRole, self.horizontalLayout_3)
self.summary = QtWidgets.QPlainTextEdit(self.formLayoutWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.summary.sizePolicy().hasHeightForWidth())
self.summary.setSizePolicy(sizePolicy)
self.summary.setMaximumSize(QtCore.QSize(250, 25))
self.summary.setObjectName("summary")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.summary)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 394, 22))
self.menuBar.setObjectName("menuBar")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
for i in range(0, len(listofsubjects) - 1): self.subject_box.addItem(listofsubjects[i])
self.retranslateUi(MainWindow)
self.pushButton.clicked.connect(lambda: self.save_event())
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "Subject"))
self.label_4.setText(_translate("MainWindow", "Date"))
self.label_3.setText(_translate("MainWindow", "Event"))
self.label_5.setText(_translate("MainWindow", "Plan/Notes"))
self.pushButton.setText(_translate("MainWindow", "Save Event"))
self.dateTimeEdit.setDate(QtCore.QDate.currentDate())
def save_event(self):
iso_date = self.dateTimeEdit.dateTime().toPyDateTime()
iso_date_utc = iso_date.astimezone(pytz.utc).isoformat()
plusninety_utc =(datetime.datetime.fromisoformat(iso_date_utc) + datetime.timedelta(minutes=90)).astimezone(
pytz.utc).isoformat()
eventID = randomiser_for_ids()
memory_dict = {
'event_id': eventID,
'type': "Session",
'name': self.summary.toPlainText(),
'subject': self.subject_box.currentText(),
'start_time': iso_date_utc,
'end_time': plusninety_utc,
'deadline': iso_date_utc,
'plan': self.sessionplan.toPlainText(),
'description': self.sessionplan.toPlainText()
}
cronofy_dict = {
'event_id': eventID,
'summary': memory_dict['name'],
'description': self.sessionplan.toPlainText(),
'start': iso_date_utc,
'end': plusninety_utc,
# 90 minutes later
}
print(iso_date_utc)
writetoJSON(memory_dict)
crono_cal.upsert_event(cal_id, cronofy_dict)
notificationjob = scheduler.add_job(name='notification', func=notification,
args=[memory_dict['subject'], memory_dict['description']],
run_date=iso_date_utc)
self.close()
class FormWindow(QtWidgets.QMainWindow):
def __init__(self, MainWindow, parent=None):
super(QtWidgets.QMainWindow, self).__init__(parent)
MainWindow.setObjectName("MainWindow")
MainWindow.resize(355, 437)
self.MainWindow = MainWindow
self.centralWidget = QtWidgets.QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.formLayoutWidget = QtWidgets.QWidget(self.centralWidget)
self.formLayoutWidget.setGeometry(QtCore.QRect(10, 10, 341, 361))
self.formLayoutWidget.setObjectName("formLayoutWidget")
self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
self.formLayout.setContentsMargins(11, 11, 11, 11)
self.formLayout.setSpacing(6)
self.formLayout.setObjectName("formLayout")
self.label = QtWidgets.QLabel(self.formLayoutWidget)
self.label.setObjectName("label")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label)
self.event_type_box = QtWidgets.QComboBox(self.formLayoutWidget)
self.event_type_box.setObjectName("event_type_box")
self.event_type_box.addItem("")
self.event_type_box.addItem("")
self.event_type_box.addItem("")
self.event_type_box.addItem("")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.event_type_box)
self.label_2 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_2.setObjectName("label_2")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_2)
self.subject_box = QtWidgets.QComboBox(self.formLayoutWidget)
self.subject_box.setObjectName("subject_box")
for i in range(0, len(listofsubjects) - 1): self.subject_box.addItem(listofsubjects[i])
self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.subject_box)
self.horizontalLayout = QtWidgets.QHBoxLayout()
self.horizontalLayout.setSpacing(6)
self.horizontalLayout.setObjectName("horizontalLayout")
self.formLayout.setLayout(3, QtWidgets.QFormLayout.LabelRole, self.horizontalLayout)
self.label_3 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_3.setObjectName("label_3")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.label_3)
self.label_4 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_4.setObjectName("label_4")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_4)
self.dateTimeEdit = QtWidgets.QDateTimeEdit(self.formLayoutWidget)
self.dateTimeEdit.setObjectName("dateTimeEdit")
self.dateTimeEdit.setMinimumSize(QtCore.QSize(100, 20))
self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.dateTimeEdit)
self.label_5 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_5.setObjectName("label_5")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.label_5)
self.summary = QtWidgets.QPlainTextEdit(self.formLayoutWidget)
self.summary.setMaximumSize(QtCore.QSize(200, 100))
self.summary.setObjectName("sessionplan")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.summary)
self.plan = QtWidgets.QPlainTextEdit(self.formLayoutWidget)
self.plan.setMaximumSize(QtCore.QSize(200, 100))
self.plan.setObjectName("summary")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.plan)
self.label_6 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_6.setObjectName("label_6")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.label_6)
self.label_7 = QtWidgets.QLabel(self.formLayoutWidget)
self.label_7.setObjectName("label_7")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.label_7)
self.word_count = QtWidgets.QSpinBox(self.formLayoutWidget)
self.word_count.setMaximum(90000)
self.word_count.setSingleStep(200)
self.word_count.setProperty("value", 0)
self.word_count.setObjectName("word_count")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.word_count)
self.chapter_count = QtWidgets.QSpinBox(self.formLayoutWidget)
self.chapter_count.setObjectName("chapter_count")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.chapter_count)
self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
self.horizontalLayout_3.setSpacing(6)
self.horizontalLayout_3.setObjectName("horizontalLayout_3")
self.formLayout.setLayout(11, QtWidgets.QFormLayout.LabelRole, self.horizontalLayout_3)
self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
self.horizontalLayout_4.setSpacing(6)
self.horizontalLayout_4.setObjectName("horizontalLayout_4")
spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
self.horizontalLayout_4.addItem(spacerItem)
self.save_button = QtWidgets.QPushButton(self.formLayoutWidget)
self.save_button.setMaximumSize(QtCore.QSize(200, 16777215))
self.save_button.setObjectName("pushButton")
self.horizontalLayout_4.addWidget(self.save_button)
self.formLayout.setLayout(9, QtWidgets.QFormLayout.FieldRole, self.horizontalLayout_4)
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtWidgets.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 355, 22))
self.menuBar.setObjectName("menuBar")
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtWidgets.QToolBar(MainWindow)
self.mainToolBar.setObjectName("mainToolBar")
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtWidgets.QStatusBar(MainWindow)
self.statusBar.setObjectName("statusBar")
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
self.save_button.clicked.connect(self.save_event)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "Event type"))
self.dateTimeEdit.setDate(QtCore.QDate.currentDate())
self.event_type_box.setItemText(0, _translate("MainWindow", "Exam"))
self.event_type_box.setItemText(1, _translate("MainWindow", "Project"))
self.event_type_box.setItemText(2, _translate("MainWindow", "Deadline"))
self.event_type_box.setItemText(3, _translate("MainWindow", "Other"))
self.label_2.setText(_translate("MainWindow", "Subject"))
self.label_3.setText(_translate("MainWindow", "Summary/Notes"))
self.label_4.setText(_translate("MainWindow", "Deadline"))
self.label_5.setText(_translate("MainWindow", "Plan"))
self.label_6.setText(_translate("MainWindow", "Word count"))
self.label_7.setText(_translate("MainWindow", "Chapter count"))
self.save_button.setText(_translate("MainWindow", "Save Event"))
def save_event(self):
iso_date = self.dateTimeEdit.dateTime().toPyDateTime()
iso_date_utc = iso_date.astimezone(pytz.utc).isoformat()
eventID = randomiser_for_ids()
memory_dict = {
'event_id': eventID,
'type': self.event_type_box.currentText(),
'subject': self.subject_box.currentText(),
'deadline': iso_date_utc,
'wordcount': self.word_count.value(),
'chaptercount': self.chapter_count.value(),
'notes': self.summary.toPlainText(),
'summary': self.plan.toPlainText(),
'name': self.summary.toPlainText(),
'description': self.summary.toPlainText()
# Delivers a GST date/time
}
cronofy_dict = {
'event_id': eventID,
'summary': memory_dict['notes'],
'description': "An important deadline",
'start': iso_date_utc,
'end':(datetime.datetime.fromisoformat(iso_date_utc) + datetime.timedelta(hours=2)).isoformat()
# 2 hours later, uses UTC
}
writetoJSON(memory_dict)
crono_cal.upsert_event(cal_id, cronofy_dict)
notificationjob = scheduler.add_job(name='notification', func=notification,
args=[memory_dict['subject'], memory_dict['description']],
run_date=iso_date_utc)
Ui_MainWindow.schedule(ui, memory_dict, self.word_count.value(), self.chapter_count.value())
self.close()
class Calendar(QtWidgets.QCalendarWidget):
def __init__(self, parent=None):
QtWidgets.QCalendarWidget.__init__(self, parent)
self.setMinimumSize(QtCore.QSize(500, 500))
self.setMaximumSize(QtCore.QSize(5000, 5000))
self.setSelectionMode(True)
self.currentPageChanged.connect(lambda: self.updateCells())
self.setStyleSheet("background-color:white;\n color:black")
def paintCell(self, painter, rect, date):
QtWidgets.QCalendarWidget.paintCell(self, painter, rect, date)
with open('memory.json', mode='r') as memory:
exams = [i for i in load(memory) if i['type'].lower() in ['deadline', 'exam', 'project', 'other']]
x = date.toPyDate().isoformat() # ISO format of a calendar date(this should run on every cell of the calendar)
for exam in exams:
if x == datefromiso(exam['deadline']):
# Finds the required colour based on the dictionary
for(key, value) in subjectgroups.items():
if exam['subject'] in value:
painter.setBrush(QtGui.QColor(colour_dict[key]))
painter.drawRect(rect)
painter.setBrush(QtGui.QColor('#ffffff'))
painter.drawText(rect.center(), str(date.day()))
painter.drawText(rect.bottomLeft(), exam['subject'])
break
def screenshot(self):
QtGui.QPixmap.grabWindow(app.desktop().winId()).save(datetime.datetime.now().isoformat(), 'jpg')
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow(MainWindow)
MainWindow.show()
sys.exit(app.exec_())