我正在制作一個語音助手,它曾經很慢,所以我想使用其他 python 檔案中的一些功能,因為代碼會變得更大,這可能會使程式慢得多,所以我決定發布一些超過七個的功能行到另一個名為 Features.py 的檔案中,我還將所有功能添加到一個類中,以便它可能變得更快 現在有些功能不起作用,所以我在谷歌上搜索了很多,但我沒有找到答案,我希望有一個好的回答
Main.py 代碼
import datetime
import os # os module is used to open files and run commands on the cmd and a lot of other features installation:deafult by python
import webbrowser
import cv2
import pyautogui
import pyttsx3 # pyttsx3 is module for text to speech installation:pip install pyttsx3
import requests
# speechrecogntion is the module which is used for recognizing audio and converting into text installation:pip install speechrecogntion
import speech_recognition as sr
from pyttsx3.drivers import sapi5
import functools
hour = datetime.datetime.now().hour
class HoverAssist():
@functools.lru_cache()
def __init__(self) -> None:
self.hour = int(datetime.datetime.now().hour)
self.engine = pyttsx3.init()
self.voices = self.engine.getProperty('voices')
self.engine.setProperty('voice', self.voices[0].id)
@functools.lru_cache()
def speak(self, audio):
self.engine.say(audio)
print(" ")
print(f"Hover Said: {audio}")
self.engine.runAndWait()
@functools.lru_cache()
def listen(self):
while 1:
listener = sr.Recognizer()
try:
with sr.Microphone() as source:
audio = listener.listen(source, timeout=1.0)
response = listener.recognize_google(audio)
response = response.lower()
if "hawa" in response or "how" in response:
self.speak("How can I help you?")
self.Analyze()
else:
pass
except sr.WaitTimeoutError:
pass
except sr.UnknownValueError:
pass
except sr.RequestError:
print("Network error.")
@functools.lru_cache()
def takecommand(self):
listener = sr.Recognizer()
command = ""
try:
with sr.Microphone() as source:
voice = listener.listen(source, phrase_time_limit=4)
command = listener.recognize_google(voice)
print(f"User Said: {command}")
print(" ")
except sr.WaitTimeoutError:
pass
except sr.UnknownValueError:
pass
except sr.RequestError:
print("Network error.")
return command.lower()
@functools.lru_cache()
def wish(self, hour):
if hour > 0 and hour < 12:
self.speak('Good Morning')
elif hour > 12 and hour > 15:
self.speak('Good Afternoon')
else:
self.speak('Good Evening')
@functools.lru_cache()
def Analyze(self):
query = self.takecommand().lower()
if query == "open notepad":
os.system("notepad")
elif "what is the time" in query:
min = datetime.datetime.now().strftime("%I:%M %p")
self.speak(f"It is {min}")
elif 'browser' in query:
self.speak("opening Browser ")
webbrowser.open("https://www.google.com")
elif 'open cmd' in query or 'open command prompt' in query:
self.speak('Opening CMD')
os.system("start cmd")
elif 'open camera' in query:
self.capture = cv2.VideoCapture(0)
while True:
ret, img = self.capture.read()
cv2.imshow('Camera', img)
k = cv2.waitKey(27)
if k == 27:
break
elif 'close camera' in query:
self.capture.release()
self.capture.destroyAllWindows()
elif 'ip address' in query:
ip = requests.get('https://api.ipify.org').text
self.speak(f"your ip is {ip}")
elif 'wikipedia' in query:
self.speak('Searching Wikipedia')
import wikipedia
query = query.replace('wikipedia', '')
results = wikipedia.summary(query, sentences=3)
self.speak('Accoding to wikipedia' results)
elif 'open youtube' in query:
self.speak("Opening Youtube")
webbrowser.open('www.youtube.com')
elif 'open stack overflow' in query:
self.speak("Opening Stackoverflow")
webbrowser.open('www.stackoverflow.com')
elif 'search' in query:
self.speak("Searching The Internet")
search = query.replace("search", "")
webbrowser.open(f'www.google.com/search?q={search}')
elif 'i am going' in query:
self.speak(
"ok i will open ..security camera. to secure your device")
from Feature import Security_Cam
Security_Cam()
elif 'open' in query.lower():
from Feature import Webopener
query = query.replace("open", "")
query = query.replace("chrome", "")
self.speak(f"Opening {query} ")
Webopener.webopen(query=query)
elif "weather" in query:
from Feature import Weather
w = Weather()
self.speak(w)
elif 'how' in query:
import pywikihow
how = pywikihow.search_wikihow(query, max_results=1)
assert len(how) == 1
self.speak(how[0].summary)
elif 'shutdown' in query or 'shut down' in query:
self.speak('Shutting Down Windows')
os.system("shutdown /s /t 00")
elif 'switch the window' in query:
self.speak("I'll switch the window for you")
pyautogui.hotkey("Alt", "Tab")
elif 'take a screenshot' in query:
self.speak("taking screenshot buddy")
pyautogui.hotkey("Win", "prtsc")
elif "volume up" in query:
pyautogui.press("volumeup")
elif "volume down" in query:
pyautogui.press("volumedown")
elif "remind me" in query:
import threading
self.speak("What should i remind you for")
name = self.takecommand()
self.speak("When Should I Remind You")
time = self.takecommand()
from Feature import Reminder
tt = time
tt = tt.replace(".", "")
tt = tt.upper()
h = threading.Thread(target=lambda: Reminder(tt, name))
elif "play" in query:
import pywhatkit
query = query.replace("play", "")
self.speak(f"Playing {query}")
pywhatkit.playonyt(query)
elif "note" in query:
from Feature import Takenote
Takenote()
elif "alarm" in query:
self.speak(
"Sir Please Tell Me The Time to set alarm. For Example, Set Alarm to 5:30 A.M")
tt = self.takecommand()
tt = tt.replace("set alarm to ", "")
tt = tt.replace(".", "")
tt = tt.upper()
import threading
from Feature import Alarm
m = threading.Thread(target=lambda: Alarm(tt)).start()
elif "timer" in query:
import threading
from Feature import Timer
query = query.replace("set a timer for ", "")
query = query.replace("minutes", "")
query = query.replace("minute", "")
t = threading.Thread(target=lambda: Timer(int(query))).start()
else:
pass
Hover = HoverAssist()
Hover.wish(hour=hour)
Hover.listen()
功能.py
import pyttsx3
import threading
import speech_recognition as sr
import datetime
import os
import cv2
import webbrowser
import requests
import wikipedia
import winsound
import webbrowser
import pyautogui
from pyttsx3.drivers import sapi5
import pywhatkit
import pywikihow
from googlesearch import search
import webbrowser
hour = int(datetime.datetime.now().hour)
engine = pyttsx3.init()
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[1].id)
def speak(audio):
engine.say(audio)
print(" ")
print(f"Hover Said: {audio}")
engine.runAndWait()
def takecommand():
try:
listener = sr.Recognizer()
with sr.Microphone() as source:
voice = listener.listen(source)
command = listener.recognize_google(voice)
print(command)
except sr.WaitTimeoutError:
pass
except sr.UnknownValueError:
pass
except sr.RequestError:
print("Network error.")
return command.lower()
def Security_Cam():
speak("ok i will open ..security camera. to secure your device")
cam = cv2.VideoCapture(0)
while cam.isOpened():
ret, frame1 = cam.read()
ret, frame2 = cam.read()
diff = cv2.absdiff(frame1, frame2)
gray = cv2.cvtColor(diff, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(
dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) < 20000:
continue
x, y, w, h = cv2.boundingRect(c)
cv2.rectangle(frame1, (x, y), (x w, y h), (0, 255, 0), 2)
winsound.PlaySound('alert.wav', winsound.SND_ASYNC)
if cv2.waitKey(10) == ord('q'):
break
cv2.imshow('Secure Cam', frame1)
def Webopener():
USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0"
def webopen(query):
# scraping data
urls = []
for j in search(query=query, tld="co.in", num=1, stop=1, pause=1):
webbrowser.open(j)
print("done")
def Alarm(Timing):
altime = str(datetime.datetime.now().strptime(Timing, "%I:%M %p"))
altime = altime[11:-3]
Horeal = altime[:2]
Horeal = int(Horeal)
Mireal = altime[3:5]
Mireal = int(Mireal)
speak(f"Done Set an Reminder for {Timing}")
while True:
if Horeal == datetime.datetime.now().hour:
if Mireal == datetime.datetime.now().minute:
print("The alarm has been completed")
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
elif Mireal<datetime.datetime.now().minute:
break
def Weather():
from bs4 import BeautifulSoup
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
res = requests.get(f'https://www.google.com/search?q=weather&oq=weather&aqs=chrome.0.35i39l2j0l4j46j69i60.6128j1j7&sourceid=chrome&ie=UTF-8',headers=headers)
soup = BeautifulSoup(res.text,'html.parser')
location = soup.select('#wob_loc')[0].getText().strip()
info = soup.select('#wob_dc')[0].getText().strip()
weather = soup.select('#wob_tm')[0].getText().strip()
precipitation = soup.select('#wob_pp')[0].getText().strip()
humidity = soup.select('#wob_hm')[0].getText().strip()
windspeed =soup.select('#wob_ws')[0].getText().strip()
information = f"It is {weather}°F There are {precipitation} % chances of rainfall It is {info}.the wind is blowing in a speed of {windspeed}. The humidity is {humidity} % in {location} "
return information
def Takenote():
speak("What is The Name of the Note")
name = takecommand()
speak("Please Tell Me What Should I Take Note Of")
hnote = open(name, "a")
note = takecommand()
hnote.write(f"{note}\n")
hnote.close()
def Reminder(Timing,reminder):
import datetime
import winsound
altime = str(datetime.datetime.now().strptime(Timing, "%I:%M %p"))
altime = altime[11:-3]
Horeal = altime[:2]
Horeal = int(Horeal)
Mireal = altime[3:5]
Mireal = int(Mireal)
speak(f"Done Set an Reminder for {Timing} and {reminder}")
while True:
if Horeal == datetime.datetime.now().hour:
if Mireal == datetime.datetime.now().minute:
print(reminder)
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
elif Mireal<datetime.datetime.now().minute:
break
def Timer(mins):
import time
secs = mins*60
time.sleep(secs)
mins = f"{mins}minutes"
speak(f"The {mins} Timer has been completed")
winsound.PlaySound('alert.wav', winsound.SND_FILENAME)
謝謝
uj5u.com熱心網友回復:
如果它們在同一目錄中,您可以簡單地將 features.py 匯入為
import features
雖然有點代碼會有所幫助。
uj5u.com熱心網友回復:
你應該試試
from Feature import function_name
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/337521.html
上一篇:為什么下面的代碼輸出[<__main__.Bookobjectat0x00000207911F1FD0>]。雖然我希望輸出我添加的書籍串列
下一篇:python物件建構式的問題
