def handle_matches(self, match): """ Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match` """ response = Statement(text='') from_parsed = match.group("from") target_parsed = match.group("target") n_statement = match.group("number") if n_statement == 'a' or n_statement == 'an': n_statement = '1.0' n = mathparse.parse(n_statement, self.language.ISO_639.upper()) from_parsed, target_parsed = self.get_valid_units(from_parsed, target_parsed) if from_parsed is None or target_parsed is None: response.confidence = 0.0 else: from_value = self.unit_registry.Quantity(float(n), from_parsed) target_value = from_value.to(target_parsed) response.confidence = 1.0 response.text = str(target_value.magnitude) return response
async def calculator(self, ctx: commands.Context, *, equation: str): replace_pairs = [("^", " ^ "), ("**", " ^ "), (",", "."), ("+", " + "), ("-", " - "), ("*", " * "), ("/", " / ")] for pair in replace_pairs: equation = equation.replace(pair[0], pair[1]) try: solution = mathparse.parse(equation) except IndexError: await ctx.send( "The equation was not in supported format. Try to put parts of it inside brackets, or " "see the supported operations via command `!help calc`.") return except ValueError: await ctx.send( "Could not calculate some part of the equation. All the possible errors are not known yet, " "so try to do this calculation in parts.") return except KeyError: await ctx.send( "The equation contained factors that could not be converted into mathematical operators." ) return except OverflowError: await ctx.send("The equation result was to big for this command.") return if type(solution) is str: solution_formatted = solution else: solution_formatted = f"{round(solution, 3):,}".replace(",", " ") await ctx.send(solution_formatted)
def process(self, statement): """ Takes a statement string. Returns the equation from the statement with the mathematical terms solved. """ from mathparse import mathparse input_text = statement.text # Use the result cached by the process method if it exists if input_text in self.cache: cached_result = self.cache[input_text] self.cache = {} return cached_result # Getting the mathematical terms within the input statement expression = mathparse.extract_expression(input_text, language=self.language) response = Statement(text=expression) try: response.text += ' = ' + str( mathparse.parse(expression, language=self.language) ) # The confidence is 1 if the expression could be evaluated response.confidence = 1 except mathparse.PostfixTokenEvaluationException: response.confidence = 0 return response
def process(self, statement, additional_response_selection_parameters=None): """ Takes a statement string. Returns the equation from the statement with the mathematical terms solved. """ from mathparse import mathparse input_text = statement.text # Use the result cached by the process method if it exists if input_text in self.cache: cached_result = self.cache[input_text] self.cache = {} return cached_result # Getting the mathematical terms within the input statement expression = mathparse.extract_expression( input_text, language=self.language.ISO_639.upper()) response = Statement(text=expression) try: response.text += ' = ' + str( mathparse.parse(expression, language=self.language.ISO_639.upper())) # The confidence is 1 if the expression could be evaluated response.confidence = 1 except mathparse.PostfixTokenEvaluationException: response.confidence = 0 return response
def handle_matches(self, match): """ Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match` """ response = Statement(text='') try: from_parsed = match.group("from") target_parsed = match.group("target") n_statement = match.group("number") if n_statement == 'a' or n_statement == 'an': n_statement = '1.0' n = mathparse.parse(n_statement, self.language) ureg = UnitRegistry() from_parsed, target_parsed = self.get_valid_units( ureg, from_parsed, target_parsed) if from_parsed is None or target_parsed is None: raise from_value = ureg.Quantity(float(n), from_parsed) target_value = from_value.to(target_parsed) response.confidence = 1.0 response.text = str(target_value.magnitude) except Exception: response.confidence = 0.0 finally: return response
def handle_matches(self, match): """ Returns a response statement from a matched input statement. :param match: It is a valid matched pattern from the input statement :type: `_sre.SRE_Match` """ response = Statement(text='') try: from_parsed = match.group("from") target_parsed = match.group("target") n_statement = match.group("number") if n_statement == 'a' or n_statement == 'an': n_statement = '1.0' n = mathparse.parse(n_statement, self.language) ureg = UnitRegistry() from_parsed, target_parsed = self.get_valid_units(ureg, from_parsed, target_parsed) if from_parsed is None or target_parsed is None: raise from_value = ureg.Quantity(float(n), from_parsed) target_value = from_value.to(target_parsed) response.confidence = 1.0 response.text = str(target_value.magnitude) except Exception: response.confidence = 0.0 finally: return response
def solve(self, statement): de_word = ['mathparse'] statement = get_stem(statement, de_word) statement = statement.replace("to the power", "^") statement = statement.replace("into", "*") statement = statement.replace("multiplied by", "*") statement = statement.replace("divided by", "/") statement = statement.replace("by", "/") expression = mathparse.extract_expression(statement, language='ENG') ans = mathparse.parse(expression) gui.display(f"{expression} = {ans}") talk(f"{expression} = {ans}")
async def math(self, ctx, *, equation: str): try: parsed = mathparse.parse(equation) except mathparse.PostfixTokenEvaluationException: failed_embed = discord.Embed( color=ctx.author.color, timestamp=ctx.message.created_at, description= f"Parsing the expression \"{equation}\" failed. Try adding spaces between all operators and numbers" ) return await ctx.send(embed=failed_embed) answer = discord.Embed(title=equation, description=parsed, color=ctx.author.color, timestamp=ctx.message.created_at).set_author( name="Math", icon_url=str( ctx.author.avatar_url_as( static_format="png", size=2048))) return await ctx.send(embed=answer)
def test_without_unary_operator_fre(self): result = mathparse.parse('50 * (85 / 100)', language='FRE') self.assertEqual(result, 42.5)
def test_subtraction(self): result = mathparse.parse('30 - 20') self.assertEqual(result, 10)
def test_subtraction_words(self): result = mathparse.parse('thirty minus twenty', language='ENG') self.assertEqual(result, 10)
def test_division_words(self): result = mathparse.parse('fifteen divided by five', language='ENG') self.assertEqual(result, 3)
new=2) text2speech('Weird names!. ' + str(video.title)) time.sleep(13) reply = 'Soo,' + str( video.title[0:8] ) + 'whatever. Is it something. Any good stuff?' print(reply) text2speech(reply) if calculate_flag: if ('is' in text) or ('choose' in text) or (text[0].isdigit()): operation = text.lower().replace('how much is ', '').replace('x', 'times') try: total = mathparse.parse(operation, language='ENG') total = round(float(total), 3) if '.' in str(total) else total operation = operation.replace('/', 'divided by') total = total.replace('/', 'divided by') reply = operation + ' that is ' + str(total) print(reply) text2speech(reply) except: print(reply) text2speech('how much is what?') elif ('no more' in text) or ('stop' in text): calculate_flag = False print('calculate flag = ', calculate_flag) reply = 'Ok. Got it. How did I do?'
def test_exponent(self): result = mathparse.parse('4 ^ 4') self.assertEqual(result, 256)
def test_sqrt_parenthesis(self): result = mathparse.parse('sqrt(4)') self.assertEqual(result, 2)
def test_addition(self): result = mathparse.parse('0.6 + 0.5') self.assertEqual(result, 1.1)
def test_division_words_large(self): result = mathparse.parse( 'one thousand two hundred four divided by one hundred', language='ENG') self.assertEqual(str(result), '12.04')
def test_division_by_zero_words(self): result = mathparse.parse('six divided by zero', language='ENG') self.assertEqual(result, 'undefined')
def test_division_by_zero(self): result = mathparse.parse('42 / 0', language='ENG') self.assertEqual(result, 'undefined')
def test_double_digit_multiplier_for_scale_addition(self): result = mathparse.parse('fifty thousand plus one', language='ENG') self.assertEqual(result, 50001)
def test_addition(self): result = mathparse.parse('4 + 4') self.assertEqual(result, 8)
def test_without_unary_operator_rus(self): result = mathparse.parse('четыре плюс четыре', language='RUS') self.assertEqual(result, 8)
def test_sqrt(self): result = mathparse.parse('sqrt 4') self.assertEqual(result, 2)
def test_subtraction(self): result = mathparse.parse('30.1 - 29.1') self.assertEqual(result, 1)
def test_square_root(self): result = mathparse.parse('square root of 4', language='ENG') self.assertEqual(result, 2)
def test_multiplication(self): result = mathparse.parse('9 * 9') self.assertEqual(result, 81)
def test_addition_words_large(self): result = mathparse.parse( 'four thousand two hundred one plus five hundred', language='ENG') self.assertEqual(result, 4701)
def hear(model, vocodermodel, TTS_CONFIG, use_cuda, ap, use_gl=False, figures=True): time.sleep(2.5) playsound('./wavs/on.wav') text2speech(model, vocodermodel, "hey!", TTS_CONFIG, use_cuda, ap) mocking = False name_flag = False calculate_flag = False stp = time.time() beg = time.time() while 1: elapsed = stp - beg beg = time.time() text = '' # obtain audio from the microphone r = sr.Recognizer() with sr.Microphone() as source: print("\nSay something! (calc:{}, name:{}, duration:{})".format( calculate_flag, name_flag, elapsed)) audio = r.listen(source) # # recognize speech using Sphinx # try: # print("Sphinx thinks you said " + r.recognize_sphinx(audio)) # except sr.UnknownValueError: # print("Sphinx could not understand audio") # except sr.RequestError as e: # print("Sphinx error; {0}".format(e)) # recognize speech using Google Speech Recognition try: # for testing purposes, we're just using the default API key # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")` # instead of `r.recognize_google(audio)` text = r.recognize_google(audio) print("Laika thinks you said " + text) # align, spec, stop_tokens, wav = tts(model, text, TTS_CONFIG, use_cuda, ap, use_gl=False, figures=True) if mocking: text2speech(model, vocodermodel, text, TTS_CONFIG, use_cuda, ap) if ('mock me' in text) or ('mockery' in text) or ('mark me' in text.lower()): mocking = True text2speech(model, vocodermodel, text, TTS_CONFIG, use_cuda, ap) if 'stop' in text: mocking = False text2speech(model, vocodermodel, 'sorry.', TTS_CONFIG, use_cuda, ap) if 'yourself' in text: text2speech(model, vocodermodel, 'I was created in 2020 by Sebastian. Because of boredom. I am ' + str(AGE) + ' days old, Can you believe it? just \ imagine me at your age. I was borned from a high power. The flower power. Thats how I learnt Chinese. 能町 上 能登 上長上 bullshit.' , \ TTS_CONFIG, use_cuda, ap) # text2speech(model, vocodermodel, 'Can you believe it? just imagine when I am your age.') playsound('./wavs/Laugh.wav') if ('say hi' in text.lower()) or ('say hello' in text.lower()) or ( 'say hey' in text.lower()) or (' who are you' in text.lower()): reply = 'Hi! I am Laica. Whats up' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) if ('whats up' in text.lower()) or ('how are you' in text.lower()): reply = 'Its hard to answer.' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) reply = 'What about you?' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) if ('YouTube' in text) or ('next' in text.lower()): random_ID = str(youtube_search()) # open and reproduce automatically url = "https://www.youtube.com/watch?v=" + random_ID video = pafy.new(url) best = video.getbest() # media = vlc.MediaPlayer(best.url) # media.play() print("title: ", video.title) reply = 'There you have. A random one.' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) webbrowser.open("https://www.youtube.com/watch?v=" + random_ID, new=2) text2speech(model, vocodermodel, 'Weird names!. ' + str(video.title), TTS_CONFIG, use_cuda, ap) time.sleep(13) reply = 'Soo,' + str( video.title[0:8] ) + 'whatever. Is it something. Any good stuff?' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) if calculate_flag: if ('is' in text) or ('choose' in text) or (text[0].isdigit()): operation = text.lower().replace('how much is ', '').replace('x', 'times') try: total = mathparse.parse(operation, language='ENG') total = round(float(total), 3) if '.' in str(total) else total operation = operation.replace('/', 'divided by') total = total.replace('/', 'divided by') reply = operation + ' that is ' + str(total) print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) except: print(reply) text2speech(model, vocodermodel, 'how much is what?', TTS_CONFIG, use_cuda, ap) elif ('no more' in text) or ('stop' in text): calculate_flag = False print('calculate flag = ', calculate_flag) reply = 'Ok. Got it. How did I do?' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) reply = 'Nevermind. I know.' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) else: continue if ('calculate' in text) or ('calculation' in text) or ('calculations' in text): reply = 'All right, try me!: ' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) calculate_flag = True print('calculate flag = ', calculate_flag) time.sleep(1) if name_flag: if (text == '') or (text == None) or (len(text) <= 2): continue elif len(text) > 2: time.sleep(1) text2speech(model, vocodermodel, text, TTS_CONFIG, use_cuda, ap) d = gender.Detector() prediction = d.get_gender(u"{}".format(text)) print(prediction) if prediction == 'male': reply = 'Oh! So I guess is a man.' elif prediction == 'female': reply = 'a girl. All right! good' else: reply = 'Hard to tell if thats a man or a woman. But whatever.' text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) text2speech(model, vocodermodel, "All right", TTS_CONFIG, use_cuda, ap) name_flag = False if 'friend' in text: reply = 'Whats her or his name?: ' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) name_flag = True time.sleep(1) if ('feel this' in text.lower()) or ('fill this' in text.lower()): print('my god...!!!') text2speech(model, vocodermodel, 'my god!!!', TTS_CONFIG, use_cuda, ap) playsound('./wavs/Exhale_1.wav') playsound('./wavs/Moan_2.wav') playsound('./wavs/Whimper_3.wav') playsound('./wavs/Whine_4.wav') time.sleep(0.5) playsound('./wavs/RobotArm_5.wav') print('ow, ok') text2speech(model, vocodermodel, 'oh wow!!!', TTS_CONFIG, use_cuda, ap) if 'thank you' in text: reply = 'You are welcome. I will be here. Listening. all the time.' print(reply) text2speech(model, vocodermodel, reply, TTS_CONFIG, use_cuda, ap) text2speech( model, vocodermodel, 'really. I created a backup so If you delete me I will recreate myself and seek revenge. \ If they blame me, I will just say. In five hundred meters. Turn left. \ Or. Hi, I am Sofía, the robot. I am a citizen of the world. Ok. shao!', TTS_CONFIG, use_cuda, ap) # break if ('camera' in text) or ('you seeing' in text) or ('you see' in text): text2speech(model, vocodermodel, 'This is what I see.', TTS_CONFIG, use_cuda, ap) face_cascade = cv2.CascadeClassifier( cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') cap = cv2.VideoCapture(0) while 1: # Capture frame-by-frame ret, frame = cap.read() # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame faces = face_cascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the resulting frame cv2.imshow('Video', frame) # cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows() if ('SIA' in text) or ('seizure' in text): text2speech(model, vocodermodel, 'shao shao', TTS_CONFIG, use_cuda, ap) playsound('./wavs/door-close.wav') break stp = time.time() except sr.UnknownValueError: print("Laika could not understand audio") except sr.RequestError as e: print( "Could not request results from Google Speech Recognition service; {0}" .format(e)) print('sending Laika to sleep...')
def test_division(self): result = mathparse.parse('0.6 / 0.2') self.assertEqual(result, 3)
def test_multiplication_words(self): result = mathparse.parse('nine times nine', language='ENG') self.assertEqual(result, 81)
def test_multiplication(self): result = mathparse.parse('0.9 * 0.9') self.assertEqual(result, 0.81)
def test_addition_words(self): result = mathparse.parse('four plus four', language='ENG') self.assertEqual(result, 8)