|
''' |
|
Created By Lewis Kamau Kimaru |
|
https://towardsdev.com/building-a-voice-assistant-using-openai-api-and-flask-by-chatgpt-9f90a430b242 |
|
https://github.com/prathmeshChaudhari05/Voice-Assistant-Flask |
|
August 2023 |
|
''' |
|
|
|
from flask import Flask, render_template, request, redirect, url_for, send_from_directory |
|
from playsound import playsound |
|
import speech_recognition as sr |
|
from pyngrok import ngrok |
|
from gtts import gTTS |
|
import openai |
|
import os |
|
|
|
app = Flask(__name__) |
|
|
|
|
|
ngrok.set_auth_token("2UAhCqf5zP0cCgJzeadNANkbIqx_7ZJvhkDSNWccqMX2hyxXP") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
openai.api_key = 'YOUR_API_KEY' |
|
|
|
html_content = """ |
|
<!DOCTYPE html> |
|
<html> |
|
<head> |
|
<title>Voice Assistant</title> |
|
</head> |
|
<body> |
|
<h1>Voice Assistant</h1> |
|
<form method="POST"> |
|
<button type="submit">Ask me something!</button> |
|
</form> |
|
<audio controls> |
|
<source src="{{ url_for('static', filename='response.mp3') }}" type="audio/mpeg"> |
|
</audio> |
|
</body> |
|
</html> |
|
""" |
|
|
|
@app.route('/') |
|
def home(): |
|
|
|
return html_content |
|
|
|
|
|
def handle_form(): |
|
r = sr.Recognizer() |
|
with sr.Microphone() as source: |
|
print("Listening...") |
|
audio = r.listen(source) |
|
|
|
try: |
|
result = r.recognize_google(audio) |
|
print("result2:") |
|
print(r.recognize_google(audio, show_all=True)) |
|
response = openai.Completion.create( |
|
engine="davinci", |
|
prompt=result, |
|
max_tokens=60, |
|
n=1, |
|
stop=None, |
|
temperature=0.5, |
|
) |
|
if response.choices: |
|
tts = gTTS(text=response.choices[0].text, lang='en') |
|
else: |
|
tts = gTTS(text="I'm sorry, I didn't understand what you said", lang='en') |
|
filename = 'response.mp3' |
|
tts.save(filename) |
|
playsound(filename) |
|
os.remove(filename) |
|
except sr.UnknownValueError: |
|
print("Google Speech Recognition could not understand audio") |
|
except sr.RequestError as e: |
|
print("Could not request results from Google Speech Recognition service; {0}".format(e)) |
|
return html_content |
|
|
|
@app.route('/', methods=['POST']) |
|
def submit_textarea(): |
|
return handle_form() |
|
|
|
|
|
ngrok_tunnel = ngrok.connect(7860) |
|
public_url = ngrok_tunnel.public_url |
|
print('\nPublic URL✅:', public_url) |
|
|
|
print("\nFlask APP starting .......\n") |
|
|