0% found this document useful (0 votes)
5 views3 pages

Voice Assistant with NLP and APIs

Uploaded by

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

Voice Assistant with NLP and APIs

Uploaded by

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

import pyttsx3

import speech_recognition as sr
import psutil
import os
import shutil
import logging
import random
import speedtest
import spacy
import requests
from textblob import TextBlob

# Initialize the English language model for NLP


nlp = [Link]("en_core_web_sm")

# Dictionary of response templates for Customizable Responses


responses = {
"greetings": ["Hello!", "Hi there!", "Hey!"],
"farewell": ["Goodbye!", "See you later!", "Take care!"]
}

# Define conversation states for Interactive Dialogues


class ConversationManager:
def __init__(self):
[Link] = "start"

def process_input(self, user_input):


if [Link] == "start":
if "hello" in user_input.lower():
[Link] = "greeted"
return "Hi there! How can I assist you?"
else:
return "Hello! How can I assist you?"

elif [Link] == "greeted":


if "help" in user_input.lower():
[Link] = "asked_for_help"
return "Sure, I'm here to help! What do you need assistance with?"
else:
return "How can I assist you today?"

elif [Link] == "asked_for_help":


# Handle user requests for assistance
return "Sure, let me know how I can assist you."

# Function to parse user input for Enhanced NLU


def parse_input(input_text):
doc = nlp(input_text)
# Extract entities, keywords, or intents from the input text
entities = [[Link] for ent in [Link]]
keywords = [[Link] for token in doc if not token.is_stop and
token.is_alpha]
return entities, keywords

# Function to generate a response based on a template key for Customizable


Responses
def generate_response(template_key):
if template_key in responses:
return [Link](responses[template_key])
else:
return "I'm sorry, I don't understand that."

# Function to retrieve data from an external API for Integration with External APIs
def get_api_data(api_url):
try:
response = [Link](api_url)
if response.status_code == 200:
return [Link]()
else:
return None
except [Link] as e:
print("Error:", e)
return None

# Function to analyze sentiment of text for Emotion Recognition


def analyze_sentiment(text):
blob = TextBlob(text)
sentiment_score = [Link]
if sentiment_score > 0.5:
return "positive"
elif sentiment_score < -0.5:
return "negative"
else:
return "neutral"

class VoiceAssistant:
def __init__(self):
[Link](level=[Link]) # Set logging level to DEBUG
[Link] = [Link]()
[Link] = [Link]()
[Link] = [Link]('voices')
self.voice_index = 0
self.rude_threshold = 0.5 # Adjust this threshold as needed
[Link]("Voice Assistant initialized.")
self.conversation_manager = ConversationManager()

def listen(self):
try:
with [Link]() as source:
[Link]("Listening for command...")
audio = [Link](source)
[Link]("Audio captured.")
command = [Link].recognize_google(audio).lower()
[Link](f"Recognized command: {command}")
return command
except [Link]:
[Link]("Speech recognition could not understand audio.")
return None
except [Link] as e:
[Link](f"Could not request results from Google Speech
Recognition service: {e}")
return None

def speak(self, text):


[Link](f"Speaking: {text}")
[Link](text)
[Link]()
[Link]("Speech completed.")
def change_voice(self):
self.voice_index = (self.voice_index + 1) % len([Link])
[Link]('voice', [Link][self.voice_index].id)
[Link](f"Changed voice to: {[Link][self.voice_index].name}")

def insult(self):
insults = ["You're a waste of oxygen.", "I'd tell you to go fuck yourself,
but I'm sure you'd be disappointed.",
"You're as useless as a knitted condom.", "I'd slap you, but
shit splatters.",
"Your birth certificate is an apology letter from the condom
factory.", "You're not pretty enough to be this stupid.",
"If you had a brain, it would be lonely.", "You're about as
useful as a screen door on a submarine.",
"I'd call you a cunt, but you lack the warmth and depth.",
"You're proof that evolution can go in reverse.",
"You're not pretty enough to be this stupid.", "The only way
you'll ever get laid is if you crawl up a chicken's ass and wait.",
"Your family tree is a cactus, because everybody on it is a
prick.", "I refuse to engage in a battle of wits with an unarmed person.",
"You're so ugly, when your mom dropped you off at school, she
got a fine for littering.",
"You're not just wrong, you're stupid.", "I'd agree with you,
but then we'd both be wrong.",
"You're the reason the gene pool needs a lifeguard.", "You're
like Mondays, nobody likes you.",
"I'd call you dumb as a rock, but at least a rock has a use.",
"If laughter is the best medicine, your face must be curing the world.",
"You're so fat, you have to use a selfie stick to get your belt
buckle in the shot.", "Is your ass jealous of the amount of shit that just came out
of your mouth?",
"The only way you'll ever get laid is if you crawl up a
chicken's ass and wait.", "You're like a hemorrhoid, a pain in the ass who won't go
away.",
"You're the human version of period cramps.", "You're not pretty
enough to be this stupid.",
"You're not just a douchebag, you're the entire douche.", "If
you're going to be a smartass, first you have to be smart. Otherwise, you're just
an ass."]
return [Link](insults)

def insult_response(self):
if [Link]() > self.rude_threshold:
[Link]([Link]())
else:
[Link]("Sure, I can help you with that.")

def get_disk_space(self):
total, used, free = shutil.disk_usage("/")
[Link](f"Total disk space: {total // (2**30)} gigabytes.")
[Link](f"Used disk space: {used // (2**30)} gigabytes.")
[Link](f"Free disk space: {free // (2**30)} gigabytes.")

def get_cpu_usage(self):
[Link](f"CPU usage: {ps

Common questions

Powered by AI

The Voice Assistant might face challenges such as maintaining context over multiple exchanges, especially if inputs are ambiguous or if there are interruptions. Solutions could include implementing a memory system that tracks conversation state and past interactions, leveraging advanced NLP models for better context interpretation, and setting up rules to manage topic shifts. Machine learning algorithms could also be trained to predict user needs based on past interactions, enhancing context retention beyond simple state machines .

The VoiceAssistant class uses the 'speech_recognition' library for recognizing speech. It initializes a Recognizer instance to listen for audio input from the microphone and converts it to text using Google's speech recognition service. For generating audio responses, it employs the 'pyttsx3' library to convert text to speech, speaking the audio through the system's speaker hardware .

The system manages disk space checks by using shutil.disk_usage, which returns the total, used, and free disk space. The VoiceAssistant then communicates this information by generating spoken messages that convey the amount of disk space in gigabytes. This allows the user to receive immediate auditory feedback regarding the state of their system's storage .

The system determines current CPU usage using the psutil library, which provides details on system utilization metrics. This information is then communicated to the user through the text-to-speech functionality of the VoiceAssistant, which verbally informs the user of the current CPU usage by converting the relevant numeric data into spoken words .

External APIs are used in the Voice Assistant system to retrieve data that can enrich interactions, such as fetching real-time information from web services. The system handles potential errors during API calls using a try-except block to catch RequestException errors. If a request is successful (HTTP status code 200), it returns the JSON response. If an error occurs during the request, the exception is caught, and it returns None, allowing the system to handle such errors gracefully .

The ConversationManager class in the document is designed to handle different conversational states using a state machine-like structure. It starts in the 'start' state and transitions to the 'greeted' state upon detecting the word 'hello' in the user input. If the user asks for help by including the word 'help', it transitions to the 'asked_for_help' state. This logic allows for managing interactions by processing input and returning appropriate responses for each state .

Python's spaCy is used for natural language processing tasks, such as parsing the user's input to extract entities and keywords, which are then utilized for various interpretations within the system. TextBlob is employed for sentiment analysis, determining the emotional tone of the input text. These tools give the system robust capabilities to understand and appropriately respond to user inputs beyond simple text matching .

The system employs TextBlob for sentiment analysis of user input. It calculates the sentiment polarity score of the input text to determine sentiment. A score greater than 0.5 is classified as 'positive', less than -0.5 as 'negative', and any score in between as 'neutral'. This method allows for a quantified analysis of sentiment based on input text .

The ethical implications of the Voice Assistant's ability to use rude language are significant. This feature could lead to unexpected user distress, promote negative interactions, or result in miscommunication of the assistant's intended friendliness and helpfulness. Key considerations should include user consent, potential impacts on different demographics, and alignment with the social norms and values of targeted user groups. These issues necessitate careful configuration of the usage conditions and safeguards to prevent misuse .

Response customization in the system is achieved through predefined templates stored in a dictionary. The function generate_response selects a random response from these templates based on the provided template_key. If the key is found in the dictionary, a corresponding response is randomly chosen; otherwise, a default response indicating a lack of understanding is returned. This mechanism allows for diverse interactions yet manages them systematically .

You might also like