palondomus/CaesarAIShowCase
0
1import pyaudio2import wave3import sys4import os5import speech_recognition as sr6import requests7class CaesarNotes:8 @staticmethod9 def record(noteargfilename,record_time,subject,translate=None): 10 frames = []11 try:12 if "CaesarAudioWAVs" not in os.listdir():13 os.mkdir("CaesarAudioWAVs")14 subject = subject.capitalize()15 if subject not in os.listdir("CaesarAudioWAVs"):16 os.mkdir(f"CaesarAudioWAVs/{subject}")17 filename = "CaesarAudioWAVs/{}/{}.wav".format(subject,noteargfilename) #"resonance_and_damping.wav"18 # set the chunk size of 1024 samples19 chunk = 102420 # sample format21 FORMAT = pyaudio.paInt1622 # mono, change to 2 if you want stereo23 channels = 124 # 44100 samples per second25 sample_rate = 4410026 record_seconds = record_time #5#900 seconds27 # initialize PyAudio object28 p = pyaudio.PyAudio()29 # open stream object as input & output30 stream = p.open(format=FORMAT,31 channels=channels,32 rate=sample_rate,33 input=True,34 output=True,35 frames_per_buffer=chunk)36 37 print("Recording...")38 for i in range(int(sample_rate / chunk * record_seconds)):39 data = stream.read(chunk)40 # if you want to hear your voice while recording41 # stream.write(data)42 frames.append(data)43 print("Finished recording.")44 # stop and close stream45 stream.stop_stream()46 stream.close()47 # terminate pyaudio object48 p.terminate()49 # save audio file50 # open the file in 'write bytes' mode51 wf = wave.open(filename, "wb")52 # set the channels53 wf.setnchannels(channels)54 # set the sample format55 wf.setsampwidth(p.get_sample_size(FORMAT))56 # set the sample rate57 wf.setframerate(sample_rate)58 # write the frames as bytes59 wf.writeframes(b"".join(frames))60 # close the file61 wf.close()62 except KeyboardInterrupt as kex:63 #print(frames)64 stream.stop_stream()65 stream.close()66 # terminate pyaudio object67 p.terminate()68 # save audio file69 # open the file in 'write bytes' mode70 wf = wave.open(filename, "wb")71 # set the channels72 wf.setnchannels(channels)73 # set the sample format74 wf.setsampwidth(p.get_sample_size(FORMAT))75 # set the sample rate76 wf.setframerate(sample_rate)77 # write the frames as bytes78 wf.writeframes(b"".join(frames))79 # close the file80 wf.close()81 if translate == "translate":82 print("Translating...")83 r = sr.Recognizer()84 if "CaesarNotes" not in os.listdir():85 os.mkdir("CaesarNotes")86 if subject not in os.listdir("CaesarNotes"):87 os.mkdir(f"CaesarNotes/{subject}")88 txtfilename = "CaesarNotes/{}/{}.txt".format(subject,filename.replace(".wav","").replace("CaesarAudioWAVs/","").replace(f"{subject}",""))89 with sr.AudioFile(filename) as source:90 # listen for the data (load audio to memory)91 audio_data = r.record(source)92 # recognize (convert from speech to text)93 text = r.recognize_google(audio_data)94 #print(text)95 with open(txtfilename,"w+") as f:96 f.write(text)97 with open(txtfilename,"r") as f:98 text = f.read()99 textlist = text.split("period")100 #print(textlist)101 sentences = ""102 with open(txtfilename,"w+") as f:103 for t in textlist:104 sentence = f"{t.rstrip().lstrip()}.\n".capitalize()105 print(sentence)106 sentences += sentence107 f.write(sentence)108 sendrevisionbank = input("Send to RevisionBank: (y) or (n)").lower()109 if sendrevisionbank == "y":110 cardname = f'{txtfilename.split("/")[0]}/{txtfilename.split("/")[1].replace(".txt","").capitalize()}'111 json = {"revisioncardscheduler":{"sendtoemail":"amari.lawal05@gmail.com","revisionscheduleinterval":60,"revisioncards":[{"subject":f"A-Level {cardname}","revisioncardtitle":cardname,"revisioncard":sentences}]}}112 loginjson = {"email":"amari.lawal05@gmail.com","password":"kya63amari"}113 try:114 print("Logging in...")115 access_token = requests.post("https://revisionbank.onrender.com/loginapi",json=loginjson).json()["access_token"]116 headers = {"Authorization": f"Bearer {access_token}"}117 print("Logged in.")118 except Exception as ex:119 print("Login Failed.{}:{}".format(type(ex),ex))120 121 try:122 print("Storing CaesarAI text...")123 response = requests.post("https://revisionbank.onrender.com/storerevisioncards",json=json,headers=headers).json()124 print("CaesarAI Stored.")125 except Exception as ex:126 print("CaesarAI Text not stored.".format(type(ex),ex))127 128 129 130 elif sendrevisionbank == "n":131 pass132 else:133 pass134 135 elif translate == None:136 pass137 else:138 pass139 @staticmethod140 def run():141 # the file name output you want to record into142 if len(sys.argv) == 2:143 if sys.argv[1] == "help":144 print("CaesarAI Notes Help: runcaesar <filename> <duration_seconds> <subject> <translate>")145 146 if len(sys.argv) <= 1:147 print("Type in your text file name as an argument.")148 elif len(sys.argv) == 4:149 noteargfilename = sys.argv[1]150 # TODO Type in minutes151 record_time = int(sys.argv[2])* 60 #3600 # 60 record_time - seconds152 if sys.argv[3].lower() == "physics":153 subject = "physics"154 translate = None155 CaesarNotes.record(noteargfilename,record_time,subject,translate)156 elif sys.argv[3].lower() == "computer_science":157 subject = "computer_science"158 translate = None159 CaesarNotes.record(noteargfilename,record_time,subject,translate)160 elif sys.argv[3].lower() == "maths":161 subject = "maths"162 translate = None163 CaesarNotes.record(noteargfilename,record_time,subject,translate)164 elif sys.argv[3].lower() == "ainotes":165 subject = "ainotes"166 translate = None167 CaesarNotes.record(noteargfilename,record_time,subject,translate)168 else:169 print(f"'{sys.argv[3].capitalize()}' is not a correct directory name.")170 171 172 elif len(sys.argv) > 5:173 print("Not right amount of arguments. 4 arguments")174 elif len(sys.argv) == 5:175 noteargfilename = sys.argv[1]176 # TODO Type in minutes177 record_time = int(sys.argv[2])* 60 #3600 # 60 record_time - seconds178 subject = sys.argv[3]179 translate = sys.argv[4]180 CaesarNotes.record(noteargfilename,record_time,subject,translate)181 182if __name__ == "__main__":183 CaesarNotes.run()