from ast import Break
import speech_recognition as sr
import pyttsx3
import wikipedia
import datetime
import webbrowser
import sys
import cv2
import numpy as np
    
# Initialize the recognizer and text-to-speech engine
recognizer = sr.Recognizer()
engine = pyttsx3.init()
   
# Function to speak text
def speak(text):
    engine.say(text)
    engine.runAndWait()

# Function to listen and recognize speech
def listen():
    with sr.Microphone() as source:
        print("Listening...")
        audio = recognizer.listen(source)
        try:
            query = recognizer.recognize_google(audio)
            print(f"You said: {query}")
            return query
        except sr.UnknownValueError:

            speak("Sorry Captain.")
            return None
        except sr.RequestError:
            speak("Sorry, I'm having trouble connecting to the service.")
            return None

# Function to process commands
def process_command(command):
    command = command.lower()

    if 'hello' in command:
        speak("Hello! I am ZORO. From project Laughtale , How can I assist you today?")
    elif 'what is the current time' in command:
        now = datetime.datetime.now()
        current_time = now.strftime("%H:%M")
        speak(f"The current time is {current_time}")

    elif 'what is the date today' in command:
        today = datetime.date.today()
        speak(f"Today's date is {today}")

    elif "open artificial intelligence treasure" in command:
        speak("summoning AI treasury")
        
    elif 'open presentation making artificial intelligence' in command:
        webbrowser.open("https://slidesgo.com/ai-presentations")
        speak("Opening A I for making presentations and PPT's")


    elif 'open wikipedia' in command:
        webbrowser.open("https://www.wikipedia.org")
        speak("Opening Wikipedia")

    elif 'open google' in command:
        webbrowser.open("https://www.google.com")
        speak("Opening Google.")

    elif 'open youtube' in command:
        webbrowser.open("https://www.youtube.com")
        speak("Opening YouTube.")

    elif "open facebook" in command:
        webbrowser.open("https://www.facebook.com")
        speak("Opening Facebook")

    

    elif "open twitter" in command:
        webbrowser.open("https://www.twitter.com")
        speak("Opening Twitter")

    elif "open instagram" in command:
        webbrowser.open("https://www.instagram.com")
        speak("Opening Instagram")

    elif "camera detection" in command:
        speak("Opening camera detection")
        # Load the pre-trained Haar Cascade classifier for face detection
        face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

        # Open the default camera (camera index 0)
        cap = cv2.VideoCapture(0)

        if not cap.isOpened():
            print("Error: Could not open camera.")
            exit()

        while True:
         # Capture frame-by-frame
            ret, frame = cap.read()

            if not ret:
                print("Error: Could not read frame.")
                break

        # Convert the frame to grayscale (Haar Cascades require grayscale images)
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Detect faces in the grayscale image
        faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

        # Draw rectangles around the detected faces
        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

        # Display the resulting frame
        cv2.imshow('Live Camera Feed', frame)

        # Break the loop if 'q' is pressed
        if cv2.waitKey(1) & 0xFF == ord('q'):
            print("error found")
            Break
            
        # Release the camera and close the window
        cap.release()
        cv2.destroyAllWindows()

    elif 'close the program' in command:
        speak("goodbye!")
        sys.exit()
    else:
        speak("Sorry, Say it again Please.")

# Main loop
def main():
    speak("Hello Captain.")
    while True:
        command = listen()
        if command:
            process_command(command)

if __name__ == "__main__":
    main()
