Mr.Messeks virtual assistant:

The Mr. Meeseeks project is a virtual assistant inspired by Rick and Morty. In the TV show, Mr. Meeseeks are created to fulfill an order, which in this case is similar. The Mr. Meeseeks Assist works with voice commands like Alexa and will fulfill many requests like playing music, security camera monitoring, chatbot functionality, automated reply messages on Whatsapp, and more.

This code uses the library speech recognition to detect the voice commands. Once the code is able to detect or interpret the speech and convert it to a string, it is necessary to define the words that will execute a command and then make them execute the pertinent function. There is an example of how Mr. Meeseeks is going to execute and play the function to play the song if he hears the word “play”.

r = sr.Recognizer()
    

    with sr.Microphone() as source:

        r.adjust_for_ambient_noise(source)
        audio = r.listen(source)

        try:
            print("Has hablado:   " + r.recognize_google(audio))
            text_input = r.recognize_google(audio)

            # Separar el input para detectar las palabras:
            list_input = text_input.split(" ")   
            
            # Si el input te play play the song
            if "play" in list_input:   <--- If play in the string sentence execute the function

                # Nombre de la cancion lo que hay detras del play
                nombre_cancion = text_input.split("play ")[-1]

                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)

                #Ejecutar la cancion:
                seleciona_lacanço(nombre_cancion)

This project can be extended very easily by adding more functionalities and improving the management of the Hardware. However, this project is fun for Rick and Morty lovers.

Code:

# Imports:

from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
import sys
import pprint
import webbrowser
import pyautogui
from time import sleep
import speech_recognition as sr
from gtts import gTTS
import os
import pandas as pd
import numpy as np
import seaborn as sns
from datetime import datetime
from math import *
from datetime import datetime as date
import matplotlib.pyplot as plt
from iteration_utilities import duplicates
from iteration_utilities import unique_everseen
import time

#Load Camera
import face_recognition
import cv2
from simple_facerec import SimpleFacerec
#from simple_facerec import SimpleFacerec
cap = cv2.VideoCapture(0)
import openai as ai
from selenium import webdriver
import random
from selenium.webdriver.common.by import By
import pytesseract
import requests

from email.message import EmailMessage
import ssl
import smtplib
import imghdr
ai.api_key = ""
old_text = cv2.imread('Cropped Image.jpg')


# Musica
## Poner cancion:


def seleciona_lacanço(canço):
    
    #Credencials API y autentificar
    client_id = ""
    client_secret = ""
    sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id, client_secret))

    #Para de sonar la canço anterior si es el cas
    pyautogui.press('stop')

    # Nombre de la canço introduit
    song = canço.upper()
    
    #Buscar el autor
    result = sp.search(song)
    autor = result["tracks"]["items"][0]['artists'][0]['name']
    #bot_escuchandocancion(song, autor)
    sleep(5)
    print("You are lisening: ", song, "-->", autor )  # <------- Parlar 
    
    #Ejecutar la cancion
    name_song = result["tracks"]["items"][0]["name"].upper()
    webbrowser.open(result["tracks"]["items"][0]["uri"])

## Apagar la musica:

def stop_song():
    
    #Credencials API y autentificar
    client_id = ""
    client_secret = ""
   sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id, client_secret))

    #Para de sonar la canço anterior si es el cas
    pyautogui.press('stop')


#Escoltar el que dice:

def estoy_escuchando_2(whats_app, conver):
    r = sr.Recognizer()
    

    with sr.Microphone() as source:

        r.adjust_for_ambient_noise(source)
        print("Habla ahora:")

        audio = r.listen(source)

        try:
            print("Has hablado:   " + r.recognize_google(audio))
            text_input = r.recognize_google(audio)

            #Detectar si es cancion:
            # Separar el input para detectar las palabras:
            list_input = text_input.split(" ")   
            
            if "Mr meeseeks" in list_input:
                print("hola")
                os.system("Aparcion_MR_Meeseks.mp3")
                
            if "meeseeks" in list_input:
                print("hola")
                os.system("Aparcion_MR_Meeseks.mp3")  
            
            # Si el input te play play the song
            if "play" in list_input:
                nombre_cancion = text_input.split("play ")[-1]
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la cancion:
                seleciona_lacanço(nombre_cancion)
                
            if "Play" in list_input:
                nombre_cancion = text_input.split("play ")[-1]
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la cancion:
                seleciona_lacanço(nombre_cancion)
                
            if "security" in list_input:  
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                print("Bien detectada security ")
                camara_de_seguridad()
                
                
            if "stop" in list_input and "music" in list_input:
                stop_song()
                seleciona_lacanço(nombre_cancion)
                stop_song()
                os.system("Alldone.mp3")
                
            if "WhatsApp" in list_input:
                print("entra en whats app")
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la WhatsApp
                whats_app = True
                
            if "what's" in list_input and "up" in list_input:
                print("entra en whats app")
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la WhatsApp
                whats_app = True
                
            if "WhatsApp" in list_input and "stop" in list_input:
                print("Salir entra en whats app")
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la WhatsApp
                whats_app = False
                
                
            if "chat" in list_input:
                print("Aqui si chat")
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                conver = True
if "news" in list_input: 
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                llegir_titulos()

        except Exception as e:
            text_input = "çç"
    
    print( "Lo que he dicho:" , text_input)
    return text_input, whats_app, conver



stop_song()


def estoy_escuchando():
    r = sr.Recognizer()
    

    with sr.Microphone() as source:

            r.adjust_for_ambient_noise(source)
            print("Habla ahora:")

            audio = r.listen(source)

        #try:
            print("Has hablado:   " + r.recognize_google(audio))
            text_input = r.recognize_google(audio)

            #Detectar si es cancion:
            # Separar el input para detectar las palabras:
            list_input = text_input.split(" ")   
            
            if "Mr meeseeks" in list_input:
                print("hola")
                os.system("Aparcion_MR_Meeseks.mp3")
                
            if "meeseeks" in list_input:
                print("hola")
                os.system("Aparcion_MR_Meeseks.mp3")  
            
            # Si el input te play play the song
            if "play" in list_input:
                nombre_cancion = text_input.split("play ")[-1]
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)  
                #Ejecutar la cancion:
                seleciona_lacanço(nombre_cancion)
                
            if "Play" in list_input:
                nombre_cancion = text_input.split("play ")[-1]
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)  
                #Ejecutar la cancion:
                seleciona_lacanço(nombre_cancion)
                
            if "security" in list_input:  
                print("Bien detectada security ")
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                #Mr Messeks voice
                os.system(random_num)
                #Ejecutar la camera:
                camara_de_seguridad()
                
                
            if "stop" in list_input and "music" in list_input:
                stop_song()
                os.system("Alldone.mp3") 
                
                
            if "WhatsApp" in list_input:
                print("entra en whats app")
                #Mr Messeks voice
                random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la WhatsApp:
                whats_app = True
                
            if "what's" in list_input and "up" in list_input:
                print("entra en whats app")
                #Mr Messeks voice
random_num = random.choice(lista_acceptar_tasca)
                os.system(random_num)
                #Ejecutar la WhatsApp:
                whats_app = True
                
            if "WhatsApp" in list_input and "stop" in list_input:
                #Mr Messeks voice
                os.system("Alldone.mp3") 
                print("Salir entra en whats app")
                whats_app = False
                
                
            if "chat" in list_input:
                print("Aqui si chat")
                conver = True
                print(conver, "AQUI QUE ? ")
                

                
            
                
            
            
            


        #except Exception as e:
         #   print("Error ")
    
    #print( "Lo que he dicho:" , text_input)
    return text_input, whats_app, conver


lista_acceptar_tasca = ["CandoImmrmeseeks.mp3", "uuuhnice.mp3", "uuuhokey.mp3", "uuuhyeahcando.mp3", "Yes_sirr.mp3"]


random_num = random.choice(lista_acceptar_tasca)
os.system(random_num)



# # Sortida de string com audio 
def bot_escuchandocancion(song, autor):

    # The text that you want to convert to audio
    mytext = ('You are lisening::' + song + 'of' + autor)

    # Language in which you want to convert
    language = 'en'

    myobj = gTTS(text=mytext, lang=language, slow=False)

    # Saving the converted audio in a mp3 file named
    # welcome
    myobj.save("welcome.mp3")

    # Playing the converted file
    os.system("welcome.mp3")

def bot_hablar(mytext):

    # Language in which you want to convert
    language = 'en'

    myobj = gTTS(text=mytext, lang=language, slow=False)

    # Saving the converted audio in a mp3 file named
    # welcome
    myobj.save("welcome.mp3")

    # Playing the converted file
    os.system("welcome.mp3")


# # Chat Bot:
# ## Meu
def most_frequent(List):
    return max(set(List), key = List.count)


# In[17]:


def chat_bot_meu_prparar():
    txtdata = pd.read_table("_chat_03_2023.txt", on_bad_lines='skip') # --> Enter the .txt flie here
    # Column with all the information:
    column_name = txtdata.columns[0]
    # Separate the information in different columns
    txtdata["Date"] = txtdata[column_name].str.split(" ").str.get(0).str.title()
    txtdata["Hour"] = txtdata[column_name].str.split(" ").str.get(1).str.title()
    txtdata["Name"] = txtdata[column_name].str.split(" ").str.get(2).str.title()
    txtdata["Content"] = txtdata[column_name].str.split(":").str.get(3)
    # columns to keep:
    columns_save = ['Date', 'Hour', 'Name', 'Content']
    # New df:
    df = txtdata[columns_save]
    # Delet "[" brakets "]" and ":" 
    df["Date"] = df["Date"].str.split("[").str.get(1)
    df["Hour"] = df["Hour"].str.split("]").str.get(0)
    df["Name"] = df["Name"].str.split(":").str.get(0)
    # Save the df without any nan values
    df = df[~df["Date"].isna()]
    df = df[df["Content"].str.contains("omitted") == False]
    # Crate a new column to merge the conversations:
    df["Change"] = "" 
    df["Count"] = ""

    # Max num of rows to do the while loop:
    max_fun = df["Name"].count()
    max_fun = max_fun - 2
    # Create a loop that detects when it change writer, and count all the changes
    # Get and Error but sill work
    i = 0
    coun = 0
    while i <= max_fun:
        if (df["Name"].iloc[i+1] == df["Name"].iloc[i]):
            i = i + 1
            df["Change"].iloc[i]= 1


            df["Count"].iloc[i ] = coun

        else: 
            i = i + 1
            df["Change"].iloc[i] = 0

            coun = coun + 1
            df["Count"].iloc[i] = coun
    # Group the mensatgess of the same writer together until it change
    df_gr = df.groupby(df["Count"]).first()
    
    return df_gr


#df_gr = chat_bot_meu_prparar()


def chat_bot_meu(df_gr, msg):
# read our mesatge and get all the words
    #msg = input("Me:")
    list_msg =  msg.split(" ")
    
    # Save the possible answers
    Posiibles_respostes = []
    
    # Read all the mesatges to detect the once are similars are our msg
    max_fun = df_gr["Name"].count()
    max_fun = max_fun - 1
    i = 0 
    max_count = 0
    while i < max_fun:
        
        try:
            #Get the content
            content = df_gr["Content"].iloc[i]

            # Counter of similar words of our msg and the content
            count_simitud= 0
            
            # Loop for all the words in our msg
            for paraula in list_msg:
                
                # If the word in the msg is in the content add 1 in to the counter
                if paraula in content:
                    count_simitud = count_simitud +1

            # If the number of similar word is the maximum delet all the oder saved answares

if count_simitud > max_count:
                Posiibles_respostes = []

            # If the number of similar word is the maximum or eaqual save the maximum, the position of the maximum, and all the possible answares:
            if count_simitud >= max_count:
                
                max_count = count_simitud
                num_max = i

                resposta_provisional = num_max + 1
                
                # List with the possible answars:
                resposta = df_gr["Content"].iloc[resposta_provisional]
                Posiibles_respostes.append(resposta)
        
        except:
            pass

        # Add 2 because we want to read the content of the same person
        i = i + 2
    
    # Get the most frequant answare:
    resposta_def = most_frequent(Posiibles_respostes)
    
    resposta_def = resposta_def.replace("baby", "")
    

    
    # Print the answare of the Bot
    print("Bot:" , resposta_def)
    print("")



## GPT
def chat(question,chat_log = None) -> str:
    
    completion = ai.Completion()
    
    if(chat_log == None):
        chat_log = start_chat_log
    prompt = f"{chat_log}Human: {question}\nAI:"
    response = completion.create(prompt = prompt, engine =  "davinci", temperature = 0.85,top_p=1, frequency_penalty=0, 
    presence_penalty=0.7, best_of=10,max_tokens=150,stop = "\nHuman: ")
    return response.choices[0].text

def modify_start_message(chat_log,question,answer) -> str:
    if chat_log == None:
        chat_log = start_chat_log
    chat_log += f"Human: {question}\nAI: {answer}\n"
    return chat_log


# In[23]:


def chat_bot_GPT( question):
        ai.api_key = ""

        completion = ai.Completion()

        start_chat_log = """Human: Hello, I am Human.
        AI: Hello, human I am openai gpt3.
        Human: How are you?
        AI: I am fine, thanks for asking. 
        """

        resposta = chat(question,start_chat_log)
        resposta = resposta.split("\n")[0]
        resposta = resposta.replace("openai gpt3", "Enric")
        print("AI: ",resposta)
        return resposta


def Meeseeks_calling():
    r = sr.Recognizer()

    with sr.Microphone() as source:

        r.adjust_for_ambient_noise(source)
        print("Habla ahora:")

        audio = r.listen(source)

        try:
            print("Has hablado:   " + r.recognize_google(audio))
            text_input = r.recognize_google(audio)

            #Detectar si es cancion:
            # Separar el input para detectar las palabras:
            list_input = text_input.split(" ")   
            
            if "Mr meeseeks" in list_input:
                os.system("Aparcion_MR_Meeseks.mp3")
                habaldo = True
                
            if "meeseeks" in list_input:
                os.system("Aparcion_MR_Meeseks.mp3") 
                habaldo = True
                
            if "Mr" in list_input and "music" in list_input:
                os.system("Aparcion_MR_Meeseks.mp3") 
                habaldo = True
                
            if "mr." in list_input and "music" in list_input:
                os.system("Aparcion_MR_Meeseks.mp3") 
                habaldo = True 
                
            
            else:
                habaldo = True
                

            
            msg = estoy_escuchando()
            list_msg =  msg.split(" ")           
              
            
            


        except Exception as e:
            print("Error ")
            
    return text_input, habaldo


# # Facial recognition:

# In[26]:


sfr = SimpleFacerec()
sfr.load_encoding_images(r"path images faces")

def facial_recognition():
    
    name = ""
    ret, frame = cap.read()
    # Detect faces:
    
    face_locations, face_names = sfr.detect_known_faces(frame)
    
    for face_loc, name in zip(face_locations, face_names):
        y1, x1, y2, x2 = face_loc[0], face_loc[1], face_loc[2], face_loc[3]
        
        cv2.putText(frame, name,(x1, y1 - 10), cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 200), 2)
        cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 0, 200), 4)
        
    print(name)
        
    return name

def saludar(name, dic_today):
    hora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Limpiar dictionary si és un dia nuevo:
    try:
        ultima_fecha = dic_today[list(dic_today.keys())[0]]
        ultimo_dia = ultima_fecha[8:10]

        if hora[8:10] != ultimo_dia:
                dic_today = {}
    except:
        pass


# Se ha visto hoy ? 
    personas_vistas_hoy = list(dic_today.keys())
    if name in personas_vistas_hoy:
        dic_today[name] = hora
        
    else:
        time.sleep(1.5)
        saludo = "Hi" + name        
        bot_hablar(saludo)
        dic_today[name] = hora
        
    return dic_today
        
    
    


# # Camara de seguridad:

import cv2
import mediapipe as mp
import time
from datetime import datetime
from math import *
from datetime import datetime as date

cap = cv2.VideoCapture(0)
#Pose traking:
mpDraw = mp.solutions.drawing_utils
mpPose = mp.solutions.pose
pose = mpPose.Pose()

foto_enviada = False
def camara_de_seguridad():
    foto_enviada = False
    pTime = 0
    last_seg = 61
    i = 0

    x_list = []
    y_list = []
    
    parar_camara = True
    while parar_camara == True:

        # Conar segundos para mandar foto reportando movimiento:
        hora = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        decimal_segundo = hora[-2]

        success, img = cap.read()
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        results = pose.process(imgRGB)

        if results.pose_landmarks:
            mpDraw.draw_landmarks(img, results.pose_landmarks, mpPose.POSE_CONNECTIONS)
            for id, lm in enumerate(results.pose_landmarks.landmark):
                h, w, c = img.shape
                #print(id, lm)
                cx, cy = int(lm.x * w) ,int(lm.y * h)

                if id == 12 or id == 11 or id == 23 or id == 24:

                    #print("Hay un essser en esta camara", decimal_segundo, foto_enviada)

                    if (decimal_segundo in ["1", "3", "5"]):
                        foto_enviada = False

                    if (decimal_segundo in ["0", "2", "4"]) and foto_enviada == False:
                        print("enviar foto")
                        foto_enviada = True
                        bot_hablar("GET OUT OF MY ROOM!")
                        cv2.imwrite('intruso.jpg', img)
                        send_intruso_email()

        cv2.imshow("Video_pedo", img)
        
        r = sr.Recognizer()

        with sr.Microphone() as source:


r.adjust_for_ambient_noise(source)
            print("Habla ahora:")

            audio = r.listen(source)

            try:
                print("Has hablado:   " + r.recognize_google(audio))
                text_input = r.recognize_google(audio)
                
                #Detectar si es cancion:
                # Separar el input para detectar las palabras:
                list_input = text_input.split(" ")   

                if "stop" in list_input:
                    os.system("Alldone.mp3")
                    print("Salir de la camara:")
                    parar_camara = False

            
            except:
                pass


        key = cv2.waitKey(1)    
        if key == 27:
            break

    cap.release()
    cv2.destroyAllWindows()


# In[33]:


#camara_de_seguridad()
## Email
def send_intruso_email():
    
    #Emisor
    email_emisor = ""
    contra_emisor = ""

    #Receptor
    email_receptor = ""
    
    #Mensaje:
    asunto = "Intruder!!"
    cuerpo = "You have an intruder in your room!"
    
    #__________________________________MENSAJE_____________________________
    em = EmailMessage()
    
    # Emisor
    em["From"] = email_emisor

    #receeptor:
    em["To"] = email_receptor

    # Asunto
    em["Subject"] = asunto
    
    #Definir correo
    em.set_content(cuerpo)
    contexto = ssl.create_default_context()
    
    # Abrir la foto:
    with open('intruso.jpg', 'rb') as f:
        file_data = f.read()
        file_type = imghdr.what(f.name)
        file_name = f.name

    # Añadir la foto:
    em.add_attachment(file_data, maintype='image', subtype=file_type, filename=file_name)

    
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context = contexto) as smtp:
        smtp.login(email_emisor, contra_emisor)
        smtp.sendmail(email_emisor, email_receptor, em.as_string())


# ## Tweepy:
import tweepy
API_Key_Consumer = ""
API_Key_Secret_Consumer = ""
Access_Token = ""
Access_Token_Secret = ""

auth = tweepy.OAuthHandler(API_Key_Consumer, API_Key_Secret_Consumer )
auth.set_access_token(Access_Token, Access_Token_Secret )
api = tweepy.API(auth)

def send_intruso():
    # upload media
    media = api.media_upload(filename='intruso.jpg')# send with media
    recipient_id = ""
    api.send_direct_message(recipient_id=recipient_id, text='There is an intruder at home!', attachment_type='media', attachment_media_id=media.media_id)


# # Whats app replay
browser = webdriver.Chrome(executable_path = r"path\chromedriver.exe")
browser.get("https://web.whatsapp.com/")


def resposta_CHATGP3(question):
        completion = ai.Completion()
        start_chat_log = """Human: Hello, I am Human. AI: Hello, human I am openai gpt3. Human: How are you? AI: I am fine, thanks for asking.  """
        
        resposta = (chat(question,start_chat_log))
        
        try:
            resposta = resposta.split("Human:")[0]
        except:
            pass
        
        return resposta

def chat(question,chat_log = None) -> str:
    completion = ai.Completion()
    if(chat_log == None):
        chat_log = start_chat_log
    prompt = f"{chat_log}Human: {question}\nAI:"
    response = completion.create(prompt = prompt, engine =  "davinci", temperature = 0.85,top_p=1, frequency_penalty=0, 
    presence_penalty=0.7, best_of=10,max_tokens=150,stop = "\nHuman: ")
    return response.choices[0].text

def modify_start_message(chat_log,question,answer) -> str:
    if chat_log == None:
        chat_log = start_chat_log
    chat_log += f"Human: {question}\nAI: {answer}\n"
    return chat_log

def responde_whats():
    
    # Ejecutar cada segundo
    m = time.strftime("%S")  
    m = int(m)
    res = m%2
    
    if res == 0:
        
        #________________Screemshot_____________________________________________________________
        
        browser.save_screenshot('Chat.png')
        #browser.save_screenshot('Chat.png')
        
        # Guardar texto en   img
        img = cv2.imread('Chat.png')
        cv2.imshow("original", img)

        # Cropping an image
                #eje y superior /in eje x menor /  major

        cropped_image = img[780:820, 650:1700 ]  # Depende de las mediadas de la pantalla

        # Display cropped image
        cv2.imshow("cropped", cropped_image)
        cv2.imwrite("Cropped Image.jpg", cropped_image)
        cv2.waitKey(27)
        new_text = cv2.imread('Cropped Image.jpg')
        old_text = cv2.imread('Cropped Image_old.jpg')
        
        difference = cv2.subtract(new_text, old_text)
        b, g, r = cv2.split(difference)        
        if cv2.countNonZero(b) == 0 and cv2.countNonZero(g) == 0 and cv2.countNonZero(r) == 0:
            print("The images are completely Equal")
            time.sleep(10)
            
        
        else:
        
            print("No son iguals")
            #_____________________________SCREMSHOT TO TXT____________________________________________
            pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract"        
            texto = pytesseract.image_to_string("Cropped Image.jpg")        
            texto = texto.replace("\n", " ")     

            ##___RESPOSTA CHAT BOT_______________________________________________________________
            #resposta = resposta_chatBot(texto)
            resposta = resposta_CHATGP3(texto)
            #_enviar resposta
            elements = browser.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[1]/div/div[1]')
            elements.send_keys(resposta)
            But_env = browser.find_element(By.XPATH, '//*[@id="main"]/footer/div[1]/div/span[2]/div/div[2]/div[2]/button/span')
            But_env.click()

            time.sleep(10)

            browser.save_screenshot('Chat.png')

            # Guardar texto en   img
            img = cv2.imread('Chat.png')
            cv2.imshow("original", img)

            # Cropping an image
                    #eje y superior /in eje x menor /  major
            cropped_image = img[780:820, 650:1700 ] 

            # Display cropped image
            cv2.imshow("cropped", cropped_image)
            cv2.imwrite("Cropped Image_old.jpg", cropped_image)
            cv2.waitKey(27)
            


            time.sleep(0.5)


# # News
def llegir_titulos(): 
    
    time.sleep(1)
    
    list_comp_country = [ "SAP", "AAPL", "RIO"]
    
    # READ THE NEWS:
    news = requests.get("https://financialmodelingprep.com/api/v3/stock_news?limit=50&apikey=APIKEY").json()    
    
    for company in list_comp_country:
            try:
                # Get the news of the companies:
                news = requests.get("https://financialmodelingprep.com/api/v3/stock_news?tickers="  + company + "&limit=1900000&apikey=APIKEY").json()  
                # Titulo:
                titulo = news[1]["title"] 
                print(titulo)

                titulo = " news of:   " + company + titulo
                bot_hablar(titulo)
                time.sleep(7)
            except:
                pass

# # Main
# person saw
dic_today = {}
dic_week = {}

habaldo = False
whats_app = False
conver = False
while True:
    
    

#_______________________________________LISEN____________________________________________________    
    #try:
        # read our mesatge and get all the words
    if habaldo != True:
            text_input, habaldo = Meeseeks_calling()
            #print("intro 1")
            habaldo = True
            
        
    else:
            #print( "Otro" )
            #print("intro 2")
            habaldo = True
            msg, whats_app, conver = estoy_escuchando_2(whats_app, conver)
            #print( "Lo que he dicho_ MIAN:" , msg)
            #list_msg =  msg.split(" ")
            #print("Otro")
            


    
    #except:
        #sleep(1)
        #pass
    
    
#_______________________________________FACE RECOGNITION____________________________________________________    
    try:
        name = facial_recognition()

        # Saludar si te ve por primera vez hoy
        dic_today = saludar(name, dic_today)
    except:
        pass
    
    
    
    
#_____________________________________Camara de Whats app:_____________________________________________________

# Comando de voz
# Ejeccucion:
    #if whats_app == True:
     #   responde_whats()
    
# Chat conver 

    print("conver", conver, msg)

    if conver == True:
        print("Esta dentro chat")
        chat_bot_GPT(text_input)
        chat_bot_meu(df_gr, text_input)
        
        

#____________________________________________BREAK______________________________________________________________    
    
    
    
    """if key == 27:
        break"""

cap.release()
cv2.destroyAllWindows()

Leave a Comment

Your email address will not be published. Required fields are marked *