-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongStorageGUI.py
More file actions
1952 lines (1502 loc) · 74.3 KB
/
longStorageGUI.py
File metadata and controls
1952 lines (1502 loc) · 74.3 KB
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
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import itertools
import random
from dotenv import load_dotenv
import tiktoken
import os
import openai
import pinecone
#import torch
from PyPDF2 import PdfReader
import PyPDF2
from tqdm import tqdm
import pickle
import jsonpickle
import re
import sys
import asyncio
import itertools
import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import nltk
from rake_nltk import Rake
from nltk.tokenize import sent_tokenize
from nltk import pos_tag
from nltk.tokenize import word_tokenize
import pytz
import telegram
# from telegram import Bot, Update
# from telegram.ext import Updater, CommandHandler, MessageHandler, filters, CallbackContext
# from telegram import Update
# from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
import threading
import time
import tkinter as tk
from tkinter import filedialog
import pytesseract
from PIL import Image
from pdf2image import convert_from_path
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import wolframalpha
nltk.download("punkt")
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
class Course:
def __init__(self, name, code, folder):
self.name = name
self.code = code
self.folder = folder
self.main_note = None
def set_main_note(self, main_note):
self.main_note = main_note
def __str__(self):
return f"Course: {self.name} ({self.code})\nFolder: {self.folder}\nMain Note: {self.main_note}"
class TableOfContents:
def __init__(self, contents):
self.contents = contents
def __str__(self):
return "\n".join([str(content) for content in self.contents])
def fill_end_pages(self):
for i, content in enumerate(self.contents):
if i + 1 < len(self.contents):
next_content = self.contents[i + 1]
if content.startPage == next_content.startPage:
content.endPage = content.startPage
else:
content.endPage = next_content.startPage - 1
else:
content.endPage = content.startPage
class Content:
def __init__(self, chapter, name, startPage, endPage=None):
self.chapter = chapter
self.name = name
self.startPage = startPage
self.endPage = endPage
def __str__(self):
if self.endPage:
return f"{self.chapter} {self.name} (pp. {self.startPage}-{self.endPage})"
else:
return f"{self.chapter} {self.name} (p. {self.startPage})"
class MainNote:
def __init__(self, name, total_pages, lessons, tableOfContents = None):
self.name = name
self.total_pages = total_pages
self.lessons = None #lessons
self.tableOfContents = tableOfContents
def __str__(self):
return f"Main Note: {self.name}\nTotal Pages: {self.total_pages}"
def add_transcript_to_latest_lesson(self, transcript):
if self.lessons:
self.lessons[-1].transcript = transcript
def addTableOfContentsManually(self):
runninString = ""
print("Type \'$$$\' to finish")
print()
contents = []
while runninString != "$$$":
chapter = input("Chapter: ")
name = input("Name: ")
startPage = input("Page")
cont = Content(chapter, name, startPage)
contents.append(cont)
print("Saved!")
print()
runninString = input("Stop?: ")
print()
self.tableOfContents = TableOfContents(contents)
print("[completed]")
print()
class Lesson:
def __init__(self, name, content,summary, listOfSubjects,firstPage, lastPage, date, dueDate, ease_factor=2.5, interval=1, repetitions=0, transcript=None):
self.name = name
self.content = content
self.summary = summary
self.listOfSubjects = listOfSubjects
self.firstPage = firstPage
self.lastPage = lastPage
self.date = datetime.date.today()
self.ease_factor = ease_factor
self.interval = interval
self.repetitions = repetitions
self.due_date = datetime.date.today() + datetime.timedelta(days=self.interval)
self.transcript = transcript
def update(self, quality):
if quality < 3:
self.repetitions = 0
self.interval = 1
else:
self.repetitions += 1
if self.repetitions == 1:
self.interval = 1
elif self.repetitions == 2:
self.interval = 6
else:
self.interval *= self.ease_factor
self.ease_factor += 0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02)
self.ease_factor = max(1.3, self.ease_factor)
self.due_date += datetime.timedelta(days=int(self.interval))
class FlashCard:
def __init__(self, front, back):
"""front is question and back is answer by convention"""
self.front = front
self.back = back
def checkAnswerIntelligently(self, answer, gpt4):
preCheck = True if answer.lower() in self.back.lower() else False
if preCheck:
return True
else:
response = askGpt(f"Given this question from a flashcard \"{self.front}\" and this being the correct answer \"{self.back}\", would you say that this attempt to answer the question is correct \"{answer}\"? Only answer with \"TRUE\" if is correct, else with \"FALSE\"", gpt4)
trueOrFalse = True if "true" in response.lower() else False
return trueOrFalse
def intelligentTest(self):
print(f"Question: {self.front}")
answ = input("Answer: ")
if self.checkAnswerIntelligently(answ, True):
print(f"Correct! Here is the back: {self.back}")
print()
return True
else:
print(f"Sorry! not correct, here is the back: {self.back}")
print()
return False
class Homework:
def __init__(self, CourseCode, description, difficulty=3, dueDate=None, numberOfQuestions=None):
self.CourseCode = CourseCode
self.description = description
self.difficulty = difficulty
self.dueDate = dueDate
self.numberOfQuestions = numberOfQuestions
def __str__(self):
return f"CourseCode: {self.CourseCode}, Description: {self.description}, Difficulty: {self.difficulty}, DueDate: {self.dueDate}, NumberOfQuestions: {self.numberOfQuestions}"
def generate_flashcards(transcript, n_keywords=10, window_size=1):
# Initialize RAKE
rake = Rake()
# Extract keywords from the transcript
rake.extract_keywords_from_text(transcript)
key_phrases = rake.get_ranked_phrases()[:n_keywords]
# Filter key phrases based on POS tags
key_phrases = filter_key_phrases(key_phrases)
# Tokenize the transcript into sentences
sentences = sent_tokenize(transcript)
# Create flashcards
flashcards = []
for key_phrase in key_phrases:
for i, sentence in enumerate(sentences):
if key_phrase in sentence:
front = f"What is {key_phrase}?"
back = sentence
# Add context from surrounding sentences if needed
if window_size > 1:
context = []
for j in range(i - window_size + 1, i + window_size):
if j >= 0 and j < len(sentences) and j != i:
context.append(sentences[j])
back = " ".join(context) + " " + back
flashcards.append(FlashCard(front, back))
break
return flashcards
def filter_key_phrases(key_phrases, pos_tags=('NN', 'NNS', 'NNP', 'NNPS')):
filtered_key_phrases = []
for phrase in key_phrases:
words = word_tokenize(phrase)
tagged_words = pos_tag(words)
if any(tag in pos_tags for _, tag in tagged_words):
filtered_key_phrases.append(phrase)
return filtered_key_phrases
def read_homework_file():
file_name = "telegram_messages.txt"
homework_list = []
with open(file_name, "r") as file:
for line in file.readlines():
line = line.strip()
if not line:
continue
parts = line.split(", ")
CourseCode = parts[0].upper().strip()
description = parts[1].strip()
difficulty = int(parts[2])
dueDate = datetime.datetime.now() + datetime.timedelta(days=int(parts[3]))
numberOfQuestions = int(parts[4])
homework = Homework(CourseCode, description, difficulty, dueDate, numberOfQuestions)
homework_list.append(homework)
with open(file_name, "w") as file:
file.write("")
return homework_list
def schedule_homework_events(homework_list):
for homework in homework_list:
num_days = (homework.dueDate.date() - datetime.datetime.now().date()).days
num_questions = homework.numberOfQuestions
difficulty = homework.difficulty
if num_days <= 0:
print(f"Skipping {homework.description}: due date has already passed.")
continue
questions_per_day = [0] * num_days
total_questions = 0
for i in range(num_questions):
index = i % num_days if difficulty < 3 else num_days - 1 - (i % num_days)
questions_per_day[index] += 1
total_questions += 1
current_question = 1
for day, num_questions in enumerate(questions_per_day):
if num_questions == 0:
continue
start_question = current_question
end_question = current_question + num_questions - 1
title = f"{homework.description} ({start_question}-{end_question}/{homework.numberOfQuestions})"
event_date = datetime.datetime.now().date() + datetime.timedelta(days=day + 1)
schedule_nearest_event(title, "Homework", "", event_date)
current_question += num_questions
# def schedule_homework_events(homework_list):
# for homework in homework_list:
# num_days = (homework.dueDate.date() - datetime.datetime.now().date()).days
# num_questions = homework.numberOfQuestions
# difficulty = homework.difficulty
# if num_days <= 0:
# print(f"Skipping {homework.description}: due date has already passed.")
# continue
# questions_per_day = [0] * num_days
# total_questions = 0
# for i in range(num_questions):
# index = i % num_days if difficulty < 3 else num_days - 1 - (i % num_days)
# questions_per_day[index] += 1
# total_questions += 1
# for day, num_questions in enumerate(questions_per_day):
# if num_questions == 0:
# continue
# start_question = total_questions - num_questions + 1
# end_question = total_questions
# title = f"{homework.description} ({start_question}-{end_question}/{homework.numberOfQuestions})"
# event_date = datetime.datetime.now().date() + datetime.timedelta(days=day + 1)
# schedule_nearest_event(title, "Homework", "", event_date)
# total_questions -= num_questions
def run_threaded_read_homework_file():
print("in Homework")
homework_list = read_homework_file()
schedule_homework_events(homework_list)
threading.Timer(300, run_threaded_read_homework_file).start() # Schedule the function to run again after 5 minutes (300 seconds)
def summarize_transcript(transcript):
tokenTotal = numTokensFromString(transcript)
maxTokens = 2950
ratio = 0.75
maxWords = int(maxTokens / ratio)
finalText = transcript.decode('utf-8') # decode the transcript parameter
words = finalText.split()
sections = []
if tokenTotal > maxTokens:
for i in range(0, len(words), maxWords):
section = " ".join(words[i:i + maxWords])
sections.append(section)
while totalSectionTokenCount(sections) > maxTokens:
print("Summarizing transcript sections...")
new_sections = []
for i, section in tqdm(enumerate(sections), total=len(sections)):
while numTokensFromString(section) > 2000:
section_words = section.split()
split_idx = len(section_words) // 2
section1 = " ".join(section_words[:split_idx])
section2 = " ".join(section_words[split_idx:])
section = section1
new_sections.append(section2)
summarized_section = askGpt(f"Please summarize this transcript section. It is a part of a bigger transcript and needs to be shortened. Here is the transcript: {section}", gpt4=False)##SWITCH
new_sections.append(summarized_section)
sections = new_sections
print("Total Token count: " + str(totalSectionTokenCount(sections)))
finalText = " ".join(sections)
finalText = askGpt(f"Please summarize this pieced up together transcript to the best of your ability: {finalText}", gpt4=False)
return finalText
def totalSectionTokenCount(sectionedTranscript):
summ = 0
for section in sectionedTranscript:
summ += numTokensFromString(section)
return summ
def review_due_lessons(courses, gpt4=False):
for course in courses:
main_note = course.main_note
if main_note is None:
print(f"No main note found for course: {course.name}")
continue
lessons = main_note.lessons
if lessons is None:
print(f"No lessons found for main note: {main_note.name}")
continue
for lesson in lessons:
print(f"Lesson {lesson.name} due {lesson.due_date}")
if lesson.due_date <= datetime.date.today():
# Generate examples
print()
print(f"||| {lesson.name} Review |||")
print()
print("Lets first try some generated examples:")
print()
subjects = ', '.join(lesson.listOfSubjects) if lesson.listOfSubjects is not None else 'No subjects provided'# and noExample = True
prompt = f"Generate examples for the lesson '{lesson.name}' with the following topics: {subjects}"
examples = askGptContext(prompt, lesson.summary, gpt4)
# Ask user for rating
print(f"Examples for lesson '{lesson.name}':\n{examples}")
print()
print("Lets first try some prolems now:")
print()
subjects = ', '.join(lesson.listOfSubjects) if lesson.listOfSubjects is not None else 'No subjects provided'# and noExample = True
prompt = f"Generate 3 problem questions for the lesson '{lesson.name}' with the following topics: {subjects}"
examples = askGptContext(prompt, lesson.summary, gpt4)
prompt2 = f"Generate 2 problem questions for the lesson '{lesson.name}' with the following summary: {lesson.summary}"
examples2 = askGpt(prompt2, gpt4)
# Ask user for rating
print(f"Problems for lesson '{lesson.name}':\n{examples}")
print(examples2)
f = input("Press any key to contiue.")
if(lesson.transcript == None):
print("Could not generate flashcards, no transcript detected")
else:
if isinstance(lesson.transcript, bytes):
passableTranscript = lesson.transcript.decode('utf-8')
flashcards = generate_flashcards(passableTranscript)
print()
print("Lets review terms now:")
print()
totalCards = len(flashcards)
correct = 0
for flashcard in flashcards:
boool = flashcard.intelligentTest()
if boool:
correct += 1
ratio = correct/totalCards*100
print(f"Percent right: {ratio}%")
else:
ratio = correct/totalCards*100
print(f"Percent right: {ratio}%")
rating = int(input(f"Rate the lesson '{lesson.name}' from 1 to 5: "))
while rating < 1 or rating > 5:
rating = int(input("Invalid input. Please rate the lesson from 1 to 5: "))
# Update lesson
lesson.update(rating)
save_courses(courses, DATA_FILE)
print()
print("progress saved")
print()
def waiting_wheel():
while True:
for char in "|/-\\":
sys.stdout.write(f'\r{char}')
sys.stdout.flush()
time.sleep(0.1)
def reviewLessons(course):
due_lessons = [lesson for lesson in course.lessons if lesson.due_date <= datetime.date.today()]
if not due_lessons:
print("No lessons to review today!")
return
lesson = random.choice(due_lessons)
print(f"Review: {lesson.content}")
quality = int(input("Quality (0-5): "))
lesson.update(quality)
print(f"Next review in {lesson.interval} days.")
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
pinecone.api_key = os.getenv("PINECONE_API_KEY")
pinecome_env = os.getenv("PINECONE_ENV")
WOLFRAM_APP_ID = os.getenv("WOLFRAM_APP_ID")
wolframClient = wolframalpha.Client(WOLFRAM_APP_ID)
pytesseract.pytesseract.tesseract_cmd = "C:/Users/aleja/AppData/Local/Programs/Tesseract-OCR/tesseract.exe"##change this to your own location
bot_token = os.getenv("TELEGRAM_TOKEN")
user_id =os.getenv("TELEGRAM_ID") ##change this to your own
####bot = telegram.Bot(token=bot_token)
#bot.send_message(chat_id=user_id, text="Hello from the Python script!")
REMARKABLE_FOLD_ID = "1CpSr4xKre26VB6q-iJokOHIsCTa_Q_sC"
CALC4_FOLD_ID = "1OlcJzaGqDONcJu08eRvXyrgOuAwnGr-Y"
ELECTRO1_FOLD_ID = "1XXA4uiCMLb22gP_Ga6gVO9BbhzUW86Ko"
MEC_SPECIAL_FOLD_ID = "1DcMuDlY6hS1YmTHa8wsQsmuikoGM-tHf"
QUANTUM1_FOLD_ID = "1Qfiv_m90UY8SjabCkR9tqOo__qf0VhTO"
THERMO_FOLD_ID = "1g3o26yOM9cEFjFiZ6vgGN0UxhLZfyAyl"
code_to_folder = {
"THR": THERMO_FOLD_ID,
"CA4": CALC4_FOLD_ID,
"QM1": QUANTUM1_FOLD_ID,
"MAS": MEC_SPECIAL_FOLD_ID,
"EM1": ELECTRO1_FOLD_ID
}
courses = None
CLIENT_SECRET_FILE = os.getenv("CLIENT_SECRET_FILE")
#SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
#SCOPES = ['https://www.googleapis.com/auth/drive']
SCOPES = ['https://www.googleapis.com/auth/drive', 'https://www.googleapis.com/auth/calendar']
DATA_FILE = "courses_data.json"
SAVING_FOLDER = "C:/Users/aleja/OneDrive/Escritorio/RemarkableGPT/mainSaving"
pineConeAPIkey = os.getenv("PINECONE_API_KEY2")
pinecone.init(api_key=pineConeAPIkey, environment=pinecome_env)
#pinecone.create_index("chunks", dimension=1536)
index = pinecone.Index("chunks")
def load_table_of_contents(contents_str):
contents = []
lines = contents_str.split("\n")
for line in lines:
match = re.match(r"(\d+(?:\.\d+)?(?:\.\d+)?)(.*?)\.*(\d+)", line)
if match:
chapter = match.group(1)
name = match.group(2).strip()
startPage = int(match.group(3))
contents.append(Content(chapter, name, startPage))
return TableOfContents(contents)
def driveProtocol2():
#time.sleep(600)
creds = get_credentials()
service = build('drive', 'v3', credentials=creds)
cleanAndSortDrive(service)
time.sleep(5)
remove_duplicates2(service)
holderList = []
#REMARKABLE_FOLD = ["REMARKABLE","1CpSr4xKre26VB6q-iJokOHIsCTa_Q_sC"]
CALC4_FOLD = ["CALC4","1OlcJzaGqDONcJu08eRvXyrgOuAwnGr-Y"]
ELECTRO1_FOLD = ["ELECTRO1", "1XXA4uiCMLb22gP_Ga6gVO9BbhzUW86Ko"]
MEC_SPECIAL_FOLD = ["MEC_SPECIAL", "1DcMuDlY6hS1YmTHa8wsQsmuikoGM-tHf"]
QUANTUM1_FOLD = ["QUANTUM1", "1Qfiv_m90UY8SjabCkR9tqOo__qf0VhTO"]
THERMO_FOLD = ["THERMO", "1g3o26yOM9cEFjFiZ6vgGN0UxhLZfyAyl"]
#holderList.append(REMARKABLE_FOLD)
holderList.append(CALC4_FOLD)
holderList.append(ELECTRO1_FOLD)
holderList.append(MEC_SPECIAL_FOLD)
holderList.append(QUANTUM1_FOLD)
holderList.append(THERMO_FOLD)
for folderObject in holderList:
download_pdf_notes(service, folderObject[1])
print("Synced Drive")
#time.sleep(600)
def process_transcripts(service, course):
folder_id = code_to_folder[course.code]
files = list_files_in_folder(service, folder_id)
for file in files:
if "transcript" in file['name'].lower():
# Download the transcript file
transcript = download_file_content(service, file['id'])
# Add the transcript to the latest lesson in the course's main_note
course.main_note.add_transcript_to_latest_lesson(transcript)
# Delete the transcript file from Google Drive
delete_file(service, file['id'])
def delete_file(service, file_id):
"""Deletes a file from Google Drive."""
try:
service.files().delete(fileId=file_id).execute()
except errors.HttpError as error:
print(f'An error occurred: {error}')
return None
print(f'File with ID {file_id} was deleted.')
def driveProtocol():
time.sleep(600)
creds = get_credentials()
service = build('drive', 'v3', credentials=creds)
courses = load_courses(DATA_FILE)
####asyncio.run(sendBotMessage("Starting Sync"))
while True:
cleanAndSortDrive(service)
remove_duplicates2(service)
holderList = []
#REMARKABLE_FOLD = ["REMARKABLE","1CpSr4xKre26VB6q-iJokOHIsCTa_Q_sC"]
CALC4_FOLD = ["CALC4","1OlcJzaGqDONcJu08eRvXyrgOuAwnGr-Y"]
ELECTRO1_FOLD = ["ELECTRO1", "1XXA4uiCMLb22gP_Ga6gVO9BbhzUW86Ko"]
MEC_SPECIAL_FOLD = ["MEC_SPECIAL", "1DcMuDlY6hS1YmTHa8wsQsmuikoGM-tHf"]
QUANTUM1_FOLD = ["QUANTUM1", "1Qfiv_m90UY8SjabCkR9tqOo__qf0VhTO"]
THERMO_FOLD = ["THERMO", "1g3o26yOM9cEFjFiZ6vgGN0UxhLZfyAyl"]
#holderList.append(REMARKABLE_FOLD)
holderList.append(CALC4_FOLD)
holderList.append(ELECTRO1_FOLD)
holderList.append(MEC_SPECIAL_FOLD)
holderList.append(QUANTUM1_FOLD)
holderList.append(THERMO_FOLD)
for folderObject in holderList:
download_pdf_notes(service, folderObject[1])
print("Synced Drive")
for course in courses:
file_path = os.path.join(course.folder, course.main_note.name)
newLesson =checkIfNewLesson(course.main_note, file_path)
updateLessons(course)
process_transcripts(service, course)
if newLesson:
course.main_note.lessons[-1] = updateNewestWithTranscript(course)
print("Courses saved and synced")
save_courses(courses, DATA_FILE)
time.sleep(600)
timer_thread = threading.Thread(target=driveProtocol, daemon=True)
def numTokensFromString(string: str) -> int:
"""Returns the number of tokens in a text string."""
encoding = tiktoken.get_encoding("cl100k_base")
num_tokens = len(encoding.encode(str(string)))
return num_tokens
def read_pdf_and_chunk(file_path, chunk_size, statusMessage):
"""Reads a PDF file and splits its content into chunks of the specified size."""
pdf_reader = PdfReader(file_path)
text = ""
for page_num in tqdm(range(len(pdf_reader.pages)), desc="Processing PDF"):
text += pdf_reader.pages[page_num].extract_text()
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
statusMessage.set("Done! Thank you for waiting")
return chunks
def remove_non_ascii(text):
"""Removes non-ASCII characters from a given text string."""
return ''.join([i if ord(i) < 128 else '' for i in text])
# def store_chunks(text_chunks):
# for chunk in text_chunks:
# chunk_embedding = get_embedding(chunk)
# upsert_response = index.upsert(vectors=[{"id": chunk, "values": chunk_embedding}])
def store_chunks(chunks):
"""Stores the given chunks and their embeddings in Pinecone."""
for chunk in tqdm(chunks, desc="Storing chunks"):
chunk_embedding = get_embedding(chunk)
# Clean the chunk to create an ASCII-based ID
chunk_id = remove_non_ascii(chunk)
upsert_response = index.upsert(vectors=[{"id": chunk_id, "values": chunk_embedding}])
def query_chunks(query, top_k=5):
"""Queries Pinecone for the top K most relevant chunks based on the input query."""
query_embedding = get_embedding(query)
chunk_scores = index.query(vector=query_embedding, top_k=top_k, include_values=True)
return [match for match in chunk_scores['matches']]
def get_embedding(text):
"""Generates an embedding for the given text using OpenAI's API."""
response = openai.Embedding.create(
input=text,
model="text-embedding-ada-002"
)
embeddings = response['data'][0]['embedding']
return embeddings
def askGptContextOLD(prompt, chunks, gpt4):
"""Asks GPT model a question with the provided context from relevant chunks"""
conversation = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": f"Here is context to my next question from my book \"{chunks}\""}, {"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model= "gpt-4" if gpt4 else "gpt-3.5-turbo",
messages=conversation,
max_tokens=3500,
n=1,
stop=None,
temperature=0.1,
)
message = response.choices[0].message["content"].strip()
return message
def askGptOLD(prompt, gpt4):
"""Asks GPT model a question """
conversation = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model= "gpt-4" if gpt4 else "gpt-3.5-turbo",
messages=conversation,
max_tokens=3500,
n=1,
stop=None,
temperature=0.1,
)
message = response.choices[0].message["content"].strip()
return message
def askGptContext(prompt, chunks, gpt4):
conversation = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": f"Here is context to my next question from my book \"{chunks}\""}, {"role": "user", "content": prompt}]
# Calculate available tokens for the response
context_tokens = numTokensFromString(chunks)
prompt_tokens = numTokensFromString(prompt)
max_allowed_tokens = 4000 # Set the maximum allowed tokens
available_tokens_for_response = max_allowed_tokens - (context_tokens + prompt_tokens)
# Ensure the available tokens for the response is within the model's limit
if available_tokens_for_response < 1:
raise ValueError("The input query and context are too long. Please reduce the length.")
max_retries = 4
for _ in range(max_retries + 1): # This will try a total of 5 times (including the initial attempt)
try:
response = openai.ChatCompletion.create(
model="gpt-4" if gpt4 else "gpt-3.5-turbo",
messages=conversation,
max_tokens=available_tokens_for_response,
n=1,
stop=None,
temperature=0.1,
)
message = response.choices[0].message["content"].strip()
# Count tokens
response_tokens = numTokensFromString(message)
total_tokens = context_tokens + prompt_tokens + response_tokens
# Calculate cost
cost_per_token = 0.06 if gpt4 else 0.002
cost = (total_tokens / 1000) * cost_per_token
# Update the cost file
updateCostFile(cost)
return message
except Exception as e:
if _ < max_retries:
print(f"Error occurred: {e}. Retrying {_ + 1}/{max_retries}...")
time.sleep(1) # You can adjust the sleep time as needed
else:
raise
def askGptContextOLD2(prompt, chunks, gpt4):
conversation = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": f"Here is context to my next question from my book \"{chunks}\""}, {"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model= "gpt-4" if gpt4 else "gpt-3.5-turbo",
messages=conversation,
max_tokens=3500,
n=1,
stop=None,
temperature=0.1,
)
message = response.choices[0].message["content"].strip()
# Count tokens
prompt_tokens = numTokensFromString(prompt)
response_tokens = numTokensFromString(message)
total_tokens = prompt_tokens + response_tokens
# Calculate cost
cost_per_token = 0.06 if gpt4 else 0.002
cost = (total_tokens / 1000) * cost_per_token
# Update the cost file
updateCostFile(cost)
return message
def askGpt(prompt, gpt4):
conversation = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}]
# Calculate available tokens for the response
prompt_tokens = numTokensFromString(prompt)
max_allowed_tokens = 4000 # Set the maximum allowed tokens
available_tokens_for_response = max_allowed_tokens - prompt_tokens
# Ensure the available tokens for the response is within the model's limit
if available_tokens_for_response < 1:
raise ValueError("The input query is too long. Please reduce the length of the input query.")
max_retries = 4
for _ in range(max_retries + 1): # This will try a total of 5 times (including the initial attempt)
try:
response = openai.ChatCompletion.create(
model="gpt-4" if gpt4 else "gpt-3.5-turbo",
messages=conversation,
max_tokens=available_tokens_for_response,
n=1,
stop=None,
temperature=0.1,
)
message = response.choices[0].message["content"].strip()
# Count tokens
response_tokens = numTokensFromString(message)
total_tokens = prompt_tokens + response_tokens
# Calculate cost
cost_per_token = 0.06 if gpt4 else 0.002
cost = (total_tokens / 1000) * cost_per_token
# Update the cost file
updateCostFile(cost)
return message
except Exception as e:
if _ < max_retries:
print(f"Error occurred: {e}. Retrying {_ + 1}/{max_retries}...")
time.sleep(1) # You can adjust the sleep time as needed
else:
raise
def askGptOLD2(prompt, gpt4):
conversation = [{"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model= "gpt-4" if gpt4 else "gpt-3.5-turbo",
messages=conversation,
max_tokens=3500,
n=1,
stop=None,
temperature=0.1,
)
message = response.choices[0].message["content"].strip()
# Count tokens
prompt_tokens = numTokensFromString(prompt)
response_tokens = numTokensFromString(message)
total_tokens = prompt_tokens + response_tokens
# Calculate cost
cost_per_token = 0.06 if gpt4 else 0.002
cost = (total_tokens / 1000) * cost_per_token
# Update the cost file
updateCostFile(cost)
return message
def updateCostFile(cost: float) -> None:
"""Updates the costTracking.txt file with the new cost."""
if not os.path.exists("costTracking.txt"):
with open("costTracking.txt", "w") as f:
f.write("0")
with open("costTracking.txt", "r") as f:
current_cost = float(f.read().strip())
new_cost = current_cost + cost
with open("costTracking.txt", "w") as f:
f.write(str(new_cost))
def get_credentials():
"""Obtains Google API credentials from the 'token.pickle' file or a new token if necessary."""
creds = None
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
creds = flow.run_local_server(port=0)
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return creds
def remove_duplicates(service):
"""Removes duplicate files from the specified Google Drive folders."""
for folder_id in code_to_folder.values():
query = f"'{folder_id}' in parents"
results = service.files().list(q=query, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
file_count = {}
for item in items:
# Extract file name without extension and " (#)" suffix
base_name = re.sub(r'\s\(\d+\)|\.\w+$', '', item['name'])
if base_name not in file_count:
file_count[base_name] = []
file_count[base_name].append(item)
for base_name, files in file_count.items():
if len(files) > 1:
files.sort(key=lambda x: x['name'])
# Delete the file without parentheses
service.files().delete(fileId=files[0]['id']).execute()
# Rename the file with parentheses
new_name = re.sub(r'\s\(\d+\)', '', files[1]['name'])
service.files().update(fileId=files[1]['id'], body={"name": new_name}).execute()
def remove_duplicates2(service):
"""Removes duplicate files from the specified Google Drive folders."""
for folder_id in code_to_folder.values():
query = f"'{folder_id}' in parents"
results = service.files().list(q=query, fields="nextPageToken, files(id, name, modifiedTime)").execute()
items = results.get('files', [])
file_count = {}
for item in items:
# Extract file name without extension and " (#)" suffix
base_name = re.sub(r'\s\(\d+\)|\.\w+$', '', item['name'])
if base_name not in file_count:
file_count[base_name] = []
file_count[base_name].append(item)
for base_name, files in file_count.items():
if len(files) > 1:
# Sort the files by modifiedTime in descending order
files.sort(key=lambda x: x['modifiedTime'], reverse=True)
# Keep the most recent file
most_recent_file = files.pop(0)
# Delete all other files with the same name
for file in files:
service.files().delete(fileId=file['id']).execute()
print(f"Deleted file: {file['name']}")
# Rename the most recent file by removing the " (#)" suffix if present
new_name = re.sub(r'\s\(\d+\)', '', most_recent_file['name'])
service.files().update(fileId=most_recent_file['id'], body={"name": new_name}).execute()
elif len(files) == 1: # If there's only one file with the base name, no need to delete anything
continue
def get_page_count(pdf_file_path):
"""Returns the number of pages in a PDF file."""
with open(pdf_file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
return len(pdf_reader.pages)