0% found this document useful (0 votes)
15 views7 pages

Personal Assistant Bot

Hiiii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views7 pages

Personal Assistant Bot

Hiiii
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Personal Assistant Bot Script

import os

import json

import time

import speech_recognition as sr

from google.cloud import speech, translate_v2 as translate

from google.oauth2 import service_account

import pyttsx3

import openai

import hashlib

import datetime

import requests

import pytz

# Initialize the TTS engine

tts_engine = pyttsx3.init()

# Set your OpenAI API key

openai.api_key = os.getenv('OPENAI_API_KEY')

# Set up Google Cloud clients

credentials = service_account.Credentials.from_service_account_file('path/to/your-service-account-file.json

speech_client = speech.SpeechClient(credentials=credentials)

translate_client = translate.Client(credentials=credentials)
# Initialize recognizer

recognizer = sr.Recognizer()

# Cache to store responses

response_cache = {}

# Wikipedia API endpoint

WIKIPEDIA_API_URL = "https://en.wikipedia.org/api/rest_v1/page/summary/"

# Function to get the current weather

def get_weather(location="New York"):

api_key = os.getenv('WEATHER_API_KEY') # Make sure to set your weather API key in the environme

base_url = "http://api.openweathermap.org/data/2.5/weather?"

complete_url = f"{base_url}q={location}&appid={api_key}&units=metric"

response = requests.get(complete_url)

data = response.json()

if data["cod"] != "404":

main = data["main"]

weather = data["weather"][0]

return f"The weather in {location} is {weather['description']} with a temperature of {main['temp']}°C."

else:

return "Sorry, I couldn't find the weather for that location."

# Function to set a reminder

def set_reminder(reminder_text, reminder_time):


with open("reminders.txt", "a") as file:

file.write(f"Reminder: {reminder_text} at {reminder_time}

")

return f"Reminder set for {reminder_text} at {reminder_time}."

# Function to translate text

def translate_text(text, target_language):

try:

translation = translate_client.translate(text, target_language=target_language)

return translation['translatedText']

except Exception as e:

print(f"Error translating text: {e}")

return "Sorry, I encountered an error while translating the text."

# Function to fetch information from Wikipedia

def fetch_wikipedia_summary(topic):

try:

response = requests.get(f"{WIKIPEDIA_API_URL}{topic}")

data = response.json()

if "extract" in data:

return data["extract"]

else:

return "Sorry, I couldn't find information on that topic."

except Exception as e:

print(f"Error fetching Wikipedia summary: {e}")

return "Sorry, I encountered an error while fetching information."


def listen_to_command():

with sr.Microphone() as source:

print("Listening...")

recognizer.adjust_for_ambient_noise(source)

audio = recognizer.listen(source)

audio_content = audio.get_wav_data()

try:

response = speech_client.recognize(

config=speech.RecognitionConfig(

encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,

sample_rate_hertz=16000,

language_code="en-US",

),

audio=speech.RecognitionAudio(content=audio_content)

command = response.results[0].alternatives[0].transcript

print(f"Recognized command: {command}")

return command

except Exception as e:

print(f"Error recognizing speech: {e}")

return "Sorry, I did not understand that."

def get_response_from_gpt(prompt):
cache_key = hashlib.sha256(prompt.encode()).hexdigest()

if cache_key in response_cache:

return response_cache[cache_key]

try:

response = openai.Completion.create(

engine="davinci",

prompt=prompt,

max_tokens=150

response_text = response.choices[0].text.strip()

response_cache[cache_key] = response_text

return response_text

except openai.error.RateLimitError:

print("Rate limit exceeded. Waiting for a while before retrying...")

time.sleep(60)

return get_response_from_gpt(prompt)

except Exception as e:

print(f"Error calling OpenAI API: {e}")

return "Sorry, I encountered an error while processing your request."

def speak_response(response):

tts_engine.say(response)

tts_engine.runAndWait()
def announce_current_time():

india_tz = pytz.timezone('Asia/Kolkata')

current_time = datetime.datetime.now(india_tz)

formatted_time = current_time.strftime("%I:%M %p")

time_announcement = f"The current time in India is {formatted_time}."

print(time_announcement)

speak_response(time_announcement)

def main():

announce_current_time()

print("Assistant is ready. Say 'exit' to terminate.")

while True:

command = listen_to_command()

if "exit" in command.lower():

speak_response("Goodbye!")

break

# Handle specific commands

if "weather" in command.lower():

location = command.split("in")[-1].strip() if "in" in command.lower() else "New York"

response = get_weather(location)

elif "remind me to" in command.lower():

reminder_text = command.split("remind me to")[-1].strip()

reminder_time = (datetime.datetime.now() + datetime.timedelta(minutes=1)).strftime("%H:%M")

response = set_reminder(reminder_text, reminder_time)

elif "translate to marathi" in command.lower():


text_to_translate = command.split("translate to marathi")[-1].strip()

response = translate_text(text_to_translate, target_language="mr")

elif "translate to english" in command.lower():

text_to_translate = command.split("translate to english")[-1].strip()

response = translate_text(text_to_translate, target_language="en")

elif "tell me about" in command.lower():

topic = command.split("tell me about")[-1].strip()

response = fetch_wikipedia_summary(topic)

else:

response = get_response_from_gpt(command)

print(f"Response: {response}")

speak_response(response)

if __name__ == "__main__":

main()

You might also like