Personal Assistant Bot
Personal Assistant Bot
import os
import json
import time
import speech_recognition as sr
import pyttsx3
import openai
import hashlib
import datetime
import requests
import pytz
tts_engine = pyttsx3.init()
openai.api_key = os.getenv('OPENAI_API_KEY')
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()
response_cache = {}
WIKIPEDIA_API_URL = "https://en.wikipedia.org/api/rest_v1/page/summary/"
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]
else:
")
try:
return translation['translatedText']
except Exception as e:
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:
except Exception as e:
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
return command
except Exception as e:
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:
time.sleep(60)
return get_response_from_gpt(prompt)
except Exception as e:
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)
print(time_announcement)
speak_response(time_announcement)
def main():
announce_current_time()
while True:
command = listen_to_command()
if "exit" in command.lower():
speak_response("Goodbye!")
break
if "weather" in command.lower():
response = get_weather(location)
response = fetch_wikipedia_summary(topic)
else:
response = get_response_from_gpt(command)
print(f"Response: {response}")
speak_response(response)
if __name__ == "__main__":
main()